@meteora-ag/cp-amm-sdk 1.1.4 → 1.1.5-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,23 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var __pow = Math.pow;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }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;
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) => {
@@ -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
  ]
@@ -6923,6 +7486,7 @@ var cp_amm_default = {
6923
7486
 
6924
7487
 
6925
7488
 
7489
+
6926
7490
  var _web3js = require('@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
 
6962
7543
 
6963
7544
  // src/constants.ts
6964
7545
 
6965
-
7546
+ var _bnjs = require('bn.js'); var _bnjs2 = _interopRequireDefault(_bnjs);
6966
7547
  var CP_AMM_PROGRAM_ID = new (0, _web3js.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;
6974
- var MIN_SQRT_PRICE = new (0, _anchor.BN)("4295048016");
6975
- var MAX_SQRT_PRICE = new (0, _anchor.BN)("79226673521066979257578248091");
7554
+ var ONE_Q64 = new (0, _bnjs2.default)(1).shln(SCALE_OFFSET);
7555
+ var MAX_EXPONENTIAL = new (0, _bnjs2.default)(524288);
7556
+ var MAX = new (0, _bnjs2.default)(2).pow(new (0, _bnjs2.default)(128)).sub(new (0, _bnjs2.default)(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;
7563
+ var MIN_SQRT_PRICE = new (0, _bnjs2.default)("4295048016");
7564
+ var MAX_SQRT_PRICE = new (0, _bnjs2.default)("79226673521066979257578248091");
6976
7565
  var MIN_CU_BUFFER = 5e4;
6977
7566
  var MAX_CU_BUFFER = 2e5;
7567
+ var DYNAMIC_FEE_SCALING_FACTOR = new (0, _bnjs2.default)(1e11);
7568
+ var DYNAMIC_FEE_ROUNDING_OFFSET = new (0, _bnjs2.default)(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
- var BIN_STEP_BPS_U128_DEFAULT = new (0, _anchor.BN)("1844674407370955");
7573
+ var BIN_STEP_BPS_U128_DEFAULT = new (0, _bnjs2.default)("1844674407370955");
6983
7574
  var MAX_PRICE_CHANGE_BPS_DEFAULT = 1500;
7575
+ var U128_MAX = new (0, _bnjs2.default)("340282366920938463463374607431768211455");
7576
+ var U64_MAX = new (0, _bnjs2.default)("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,728 +7809,1799 @@ function getAllPositionNftAccountByOwner(connection, user) {
7211
7809
  });
7212
7810
  }
7213
7811
 
7214
- // src/helpers/fee.ts
7812
+ // src/helpers/computeUnits.ts
7215
7813
 
7216
7814
 
7217
- // src/math/feeMath.ts
7218
7815
 
7219
- var MAX_EXPONENTIAL = new (0, _anchor.BN)(524288);
7220
- var ONE = new (0, _anchor.BN)(1).shln(SCALE_OFFSET);
7221
- var MAX = new (0, _anchor.BN)(2).pow(new (0, _anchor.BN)(128)).sub(new (0, _anchor.BN)(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 (0, _anchor.BN)(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 (0, _anchor.BN)(1)).isZero()) {
7238
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7239
- }
7240
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7241
- if (!exp.and(new (0, _anchor.BN)(2)).isZero()) {
7242
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7243
- }
7244
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7245
- if (!exp.and(new (0, _anchor.BN)(4)).isZero()) {
7246
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7247
- }
7248
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7249
- if (!exp.and(new (0, _anchor.BN)(8)).isZero()) {
7250
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7251
- }
7252
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7253
- if (!exp.and(new (0, _anchor.BN)(16)).isZero()) {
7254
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7255
- }
7256
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7257
- if (!exp.and(new (0, _anchor.BN)(32)).isZero()) {
7258
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7259
- }
7260
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7261
- if (!exp.and(new (0, _anchor.BN)(64)).isZero()) {
7262
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7263
- }
7264
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7265
- if (!exp.and(new (0, _anchor.BN)(128)).isZero()) {
7266
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7267
- }
7268
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7269
- if (!exp.and(new (0, _anchor.BN)(256)).isZero()) {
7270
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7271
- }
7272
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7273
- if (!exp.and(new (0, _anchor.BN)(512)).isZero()) {
7274
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7275
- }
7276
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7277
- if (!exp.and(new (0, _anchor.BN)(1024)).isZero()) {
7278
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7279
- }
7280
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7281
- if (!exp.and(new (0, _anchor.BN)(2048)).isZero()) {
7282
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7283
- }
7284
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7285
- if (!exp.and(new (0, _anchor.BN)(4096)).isZero()) {
7286
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7287
- }
7288
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7289
- if (!exp.and(new (0, _anchor.BN)(8192)).isZero()) {
7290
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7291
- }
7292
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7293
- if (!exp.and(new (0, _anchor.BN)(16384)).isZero()) {
7294
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7295
- }
7296
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7297
- if (!exp.and(new (0, _anchor.BN)(32768)).isZero()) {
7298
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7299
- }
7300
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7301
- if (!exp.and(new (0, _anchor.BN)(65536)).isZero()) {
7302
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7303
- }
7304
- squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
7305
- if (!exp.and(new (0, _anchor.BN)(131072)).isZero()) {
7306
- result = result.mul(squaredBase).shrn(SCALE_OFFSET);
7816
+
7817
+
7818
+
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
+ _web3js.ComputeBudgetProgram.setComputeUnitLimit({ units: 14e5 }),
7826
+ ...instructions
7827
+ ];
7828
+ const testTransaction = new (0, _web3js.VersionedTransaction)(
7829
+ new (0, _web3js.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: _web3js.PublicKey.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 (0, _anchor.BN)(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 (0, _anchor.BN)(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 _web3js.ComputeBudgetProgram.setComputeUnitLimit({ units });
7885
+ });
7320
7886
 
7321
- // src/math/mathUtils.ts
7887
+ // src/helpers/utils.ts
7322
7888
 
7323
7889
  var _decimaljs = require('decimal.js'); var _decimaljs2 = _interopRequireDefault(_decimaljs);
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 (0, _anchor.BN)(1));
7328
- }
7329
- return div;
7330
- }
7331
- function q64ToDecimal(num, decimalPlaces) {
7332
- return new (0, _decimaljs2.default)(num.toString()).div(_decimaljs2.default.pow(2, 64)).toDecimalPlaces(decimalPlaces);
7333
- }
7334
- function decimalToQ64(num) {
7335
- return new (0, _anchor.BN)(num.mul(_decimaljs2.default.pow(2, 64)).floor().toFixed());
7336
- }
7337
-
7338
- // src/helpers/curve.ts
7339
-
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 (0, _anchor.BN)(slippage)).div(new (0, _anchor.BN)(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 (0, _anchor.BN)(1))).div(denominator);
7896
+ if (slippageBps > 0) {
7897
+ if (swapMode === 2 /* ExactOut */) {
7898
+ const slippageFactor = new (0, _anchor.BN)(BASIS_POINT_MAX + slippageBps);
7899
+ result = amount.mul(slippageFactor).div(new (0, _anchor.BN)(BASIS_POINT_MAX));
7900
+ } else {
7901
+ const slippageFactor = new (0, _anchor.BN)(BASIS_POINT_MAX - slippageBps);
7902
+ result = amount.mul(slippageFactor).div(new (0, _anchor.BN)(BASIS_POINT_MAX));
7903
+ }
7347
7904
  } else {
7348
- const quotient = amount.shln(SCALE_OFFSET * 2).div(liquidity);
7349
- result = sqrtPrice.add(quotient);
7905
+ result = amount;
7350
7906
  }
7351
7907
  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 (0, _anchor.BN)(1))).div(denominator);
7368
- }
7369
- return product.div(denominator);
7370
- }
7371
- function getAmountBFromLiquidityDelta(liquidity, currentSqrtPrice, minSqrtPrice, rounding) {
7372
- const one = new (0, _anchor.BN)(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 (0, _anchor.BN)(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 (0, _anchor.BN)(1)).div(liquidity);
7382
- const result = sqrtPrice.sub(quotient);
7383
- if (result.isNeg()) {
7384
- throw new Error("sqrt price cannot be negative");
7385
- }
7386
- return result;
7387
- }
7388
- function getNextSqrtPriceFromAmountARoundingDown(sqrtPrice, liquidity, amount) {
7389
- if (amount.isZero()) {
7390
- return sqrtPrice;
7908
+ };
7909
+ var getPriceImpact = (amountIn, amountOut, currentSqrtPrice, aToB, tokenADecimal, tokenBDecimal) => {
7910
+ if (amountIn.eq(new (0, _anchor.BN)(0))) {
7911
+ return new (0, _decimaljs2.default)(0);
7391
7912
  }
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");
7913
+ if (amountOut.eq(new (0, _anchor.BN)(0))) {
7914
+ throw new Error("Amount out must be greater than 0");
7396
7915
  }
7397
- const numerator = liquidity.mul(sqrtPrice);
7398
- const result = numerator.div(denominator);
7399
- return result;
7916
+ const spotPrice = getPriceFromSqrtPrice(
7917
+ currentSqrtPrice,
7918
+ tokenADecimal,
7919
+ tokenBDecimal
7920
+ );
7921
+ const executionPrice = new (0, _decimaljs2.default)(amountIn.toString()).div(new (0, _decimaljs2.default)(amountOut.toString())).mul(
7922
+ _decimaljs2.default.pow(
7923
+ 10,
7924
+ aToB ? tokenBDecimal - tokenADecimal : tokenADecimal - tokenBDecimal
7925
+ )
7926
+ );
7927
+ let priceImpact;
7928
+ let actualExecutionPrice;
7929
+ if (aToB) {
7930
+ actualExecutionPrice = new (0, _decimaljs2.default)(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 (0, _anchor.BN)(2)).sub(currentSqrtPrice.pow(new (0, _anchor.BN)(2))).abs();
7939
+ return new (0, _decimaljs2.default)(diff.toString()).div(new (0, _decimaljs2.default)(currentSqrtPrice.pow(new (0, _anchor.BN)(2)).toString())).mul(100).toNumber();
7940
+ };
7941
+ var getPriceFromSqrtPrice = (sqrtPrice, tokenADecimal, tokenBDecimal) => {
7942
+ const decimalSqrtPrice = new (0, _decimaljs2.default)(sqrtPrice.toString());
7943
+ const price = decimalSqrtPrice.mul(decimalSqrtPrice).mul(new (0, _decimaljs2.default)(__pow(10, tokenADecimal - tokenBDecimal))).div(_decimaljs2.default.pow(2, 128));
7944
+ return price;
7945
+ };
7946
+ var getSqrtPriceFromPrice = (price, tokenADecimal, tokenBDecimal) => {
7947
+ const decimalPrice = new (0, _decimaljs2.default)(price);
7948
+ const adjustedByDecimals = decimalPrice.div(
7949
+ new (0, _decimaljs2.default)(__pow(10, tokenADecimal - tokenBDecimal))
7950
+ );
7951
+ const sqrtValue = _decimaljs2.default.sqrt(adjustedByDecimals);
7952
+ const sqrtValueQ64 = sqrtValue.mul(_decimaljs2.default.pow(2, 64));
7953
+ return new (0, _anchor.BN)(sqrtValueQ64.floor().toFixed());
7954
+ };
7955
+ var getUnClaimReward = (poolState, positionState) => {
7956
+ const totalPositionLiquidity = positionState.unlockedLiquidity.add(positionState.vestedLiquidity).add(positionState.permanentLockedLiquidity);
7957
+ const feeAPerTokenStored = new (0, _anchor.BN)(
7958
+ Buffer.from(poolState.feeAPerLiquidity).reverse()
7959
+ ).sub(new (0, _anchor.BN)(Buffer.from(positionState.feeAPerTokenCheckpoint).reverse()));
7960
+ const feeBPerTokenStored = new (0, _anchor.BN)(
7961
+ Buffer.from(poolState.feeBPerLiquidity).reverse()
7962
+ ).sub(new (0, _anchor.BN)(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
+
7992
+
7993
+
7994
+
7995
+
7996
+
7997
+
7998
+ function calculatePreFeeAmount(transferFee, postFeeAmount) {
7999
+ if (postFeeAmount.isZero()) {
8000
+ return new (0, _anchor.BN)(0);
8001
+ }
8002
+ if (transferFee.transferFeeBasisPoints === 0) {
8003
+ return postFeeAmount;
8004
+ }
8005
+ const maximumFee = new (0, _anchor.BN)(transferFee.maximumFee.toString());
8006
+ if (transferFee.transferFeeBasisPoints === _spltoken.MAX_FEE_BASIS_POINTS) {
8007
+ return postFeeAmount.add(maximumFee);
8008
+ }
8009
+ const ONE_IN_BASIS_POINTS = new (0, _anchor.BN)(_spltoken.MAX_FEE_BASIS_POINTS);
8010
+ const numerator = postFeeAmount.mul(ONE_IN_BASIS_POINTS);
8011
+ const denominator = ONE_IN_BASIS_POINTS.sub(
8012
+ new (0, _anchor.BN)(transferFee.transferFeeBasisPoints)
8013
+ );
8014
+ const rawPreFeeAmount = numerator.add(denominator).sub(new (0, _anchor.BN)(1)).div(denominator);
8015
+ if (rawPreFeeAmount.sub(postFeeAmount).gte(maximumFee)) {
8016
+ return postFeeAmount.add(maximumFee);
8017
+ }
8018
+ return rawPreFeeAmount;
7400
8019
  }
7401
- function getNextSqrtPriceFromOutput(sqrtPrice, liquidity, outAmount, isB) {
7402
- if (sqrtPrice.isZero()) {
7403
- throw new Error("sqrt price must be greater than 0");
8020
+ function calculateInverseFee(transferFee, postFeeAmount) {
8021
+ const preFeeAmount = calculatePreFeeAmount(transferFee, postFeeAmount);
8022
+ return new (0, _anchor.BN)(
8023
+ _spltoken.calculateFee.call(void 0, transferFee, BigInt(preFeeAmount.toString())).toString()
8024
+ );
8025
+ }
8026
+ function calculateTransferFeeIncludedAmount(transferFeeExcludedAmount, mint, currentEpoch) {
8027
+ if (transferFeeExcludedAmount.isZero()) {
8028
+ return {
8029
+ amount: new (0, _anchor.BN)(0),
8030
+ transferFee: new (0, _anchor.BN)(0)
8031
+ };
7404
8032
  }
7405
- if (isB) {
7406
- return getNextSqrtPriceFromAmountBRoundingUp(
7407
- sqrtPrice,
7408
- liquidity,
7409
- outAmount
7410
- );
7411
- } else {
7412
- return getNextSqrtPriceFromAmountARoundingDown(
7413
- sqrtPrice,
7414
- liquidity,
7415
- outAmount
7416
- );
8033
+ const transferFeeConfig = _spltoken.getTransferFeeConfig.call(void 0, mint);
8034
+ if (transferFeeConfig === null) {
8035
+ return {
8036
+ amount: transferFeeExcludedAmount,
8037
+ transferFee: new (0, _anchor.BN)(0)
8038
+ };
7417
8039
  }
8040
+ const epochFee = _spltoken.getEpochFee.call(void 0, transferFeeConfig, BigInt(currentEpoch));
8041
+ const transferFee = epochFee.transferFeeBasisPoints == _spltoken.MAX_FEE_BASIS_POINTS ? new (0, _anchor.BN)(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 = _spltoken.getTransferFeeConfig.call(void 0, mint);
8050
+ if (transferFeeConfig === null) {
8051
+ return {
8052
+ amount: transferFeeIncludedAmount,
8053
+ transferFee: new (0, _anchor.BN)(0)
8054
+ };
8055
+ }
8056
+ const transferFeeIncludedAmountN = BigInt(
8057
+ transferFeeIncludedAmount.toString()
8058
+ );
8059
+ const transferFee = _spltoken.calculateFee.call(void 0,
8060
+ _spltoken.getEpochFee.call(void 0, transferFeeConfig, BigInt(currentEpoch)),
8061
+ transferFeeIncludedAmountN
8062
+ );
8063
+ const transferFeeExcludedAmount = new (0, _anchor.BN)(
8064
+ (transferFeeIncludedAmountN - transferFee).toString()
8065
+ );
8066
+ return {
8067
+ amount: transferFeeExcludedAmount,
8068
+ transferFee: new (0, _anchor.BN)(transferFee.toString())
8069
+ };
8070
+ }
8071
+
8072
+ // src/helpers/vestings.ts
8073
+
8074
+
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 (0, _anchor.BN)(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 (0, _anchor.BN)(0);
8098
+ }
8099
+ if (periodFrequency.isZero()) {
8100
+ return cliffUnlockLiquidity;
8101
+ }
8102
+ let passedPeriod = new (0, _anchor.BN)(currentPoint).sub(cliffPoint).div(periodFrequency);
8103
+ passedPeriod = _bnjs.min.call(void 0, passedPeriod, new (0, _anchor.BN)(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
+
8115
+
8116
+ // src/math/poolFees/baseFee.ts
8117
+
8118
+
8119
+ // src/math/poolFees/rateLimiter.ts
8120
+
8121
+
8122
+ // src/math/feeMath.ts
8123
+
8124
+
8125
+ // src/math/utilsMath.ts
8126
+
8127
+
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 (0, _bnjs2.default)(1));
8132
+ }
8133
+ return div;
8134
+ }
8135
+ function q64ToDecimal(num, decimalPlaces) {
8136
+ return new (0, _decimaljs2.default)(num.toString()).div(_decimaljs2.default.pow(2, 64)).toDecimalPlaces(decimalPlaces);
8137
+ }
8138
+ function decimalToQ64(num) {
8139
+ return new (0, _bnjs2.default)(num.mul(_decimaljs2.default.pow(2, 64)).floor().toFixed());
8140
+ }
8141
+ function sqrt(value) {
8142
+ if (value.isZero()) {
8143
+ return new (0, _bnjs2.default)(0);
8144
+ }
8145
+ if (value.eq(new (0, _bnjs2.default)(1))) {
8146
+ return new (0, _bnjs2.default)(1);
8147
+ }
8148
+ let x = value;
8149
+ let y = value.add(new (0, _bnjs2.default)(1)).div(new (0, _bnjs2.default)(2));
8150
+ while (y.lt(x)) {
8151
+ x = y;
8152
+ y = x.add(value.div(x)).div(new (0, _bnjs2.default)(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 (0, _bnjs2.default)(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 (0, _bnjs2.default)(1)).isZero()) {
8172
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8173
+ }
8174
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8175
+ if (!exp.and(new (0, _bnjs2.default)(2)).isZero()) {
8176
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8177
+ }
8178
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8179
+ if (!exp.and(new (0, _bnjs2.default)(4)).isZero()) {
8180
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8181
+ }
8182
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8183
+ if (!exp.and(new (0, _bnjs2.default)(8)).isZero()) {
8184
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8185
+ }
8186
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8187
+ if (!exp.and(new (0, _bnjs2.default)(16)).isZero()) {
8188
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8189
+ }
8190
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8191
+ if (!exp.and(new (0, _bnjs2.default)(32)).isZero()) {
8192
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8193
+ }
8194
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8195
+ if (!exp.and(new (0, _bnjs2.default)(64)).isZero()) {
8196
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8197
+ }
8198
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8199
+ if (!exp.and(new (0, _bnjs2.default)(128)).isZero()) {
8200
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8201
+ }
8202
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8203
+ if (!exp.and(new (0, _bnjs2.default)(256)).isZero()) {
8204
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8205
+ }
8206
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8207
+ if (!exp.and(new (0, _bnjs2.default)(512)).isZero()) {
8208
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8209
+ }
8210
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8211
+ if (!exp.and(new (0, _bnjs2.default)(1024)).isZero()) {
8212
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8213
+ }
8214
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8215
+ if (!exp.and(new (0, _bnjs2.default)(2048)).isZero()) {
8216
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8217
+ }
8218
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8219
+ if (!exp.and(new (0, _bnjs2.default)(4096)).isZero()) {
8220
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8221
+ }
8222
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8223
+ if (!exp.and(new (0, _bnjs2.default)(8192)).isZero()) {
8224
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8225
+ }
8226
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8227
+ if (!exp.and(new (0, _bnjs2.default)(16384)).isZero()) {
8228
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8229
+ }
8230
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8231
+ if (!exp.and(new (0, _bnjs2.default)(32768)).isZero()) {
8232
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8233
+ }
8234
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8235
+ if (!exp.and(new (0, _bnjs2.default)(65536)).isZero()) {
8236
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8237
+ }
8238
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8239
+ if (!exp.and(new (0, _bnjs2.default)(131072)).isZero()) {
8240
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8241
+ }
8242
+ squaredBase = squaredBase.mul(squaredBase).shrn(SCALE_OFFSET);
8243
+ if (!exp.and(new (0, _bnjs2.default)(262144)).isZero()) {
8244
+ result = result.mul(squaredBase).shrn(SCALE_OFFSET);
8245
+ }
8246
+ if (result.isZero()) {
8247
+ return new (0, _bnjs2.default)(0);
8248
+ }
8249
+ if (invert) {
8250
+ result = MAX.div(result);
8251
+ }
8252
+ return result;
7418
8253
  }
7419
8254
 
7420
- // src/helpers/fee.ts
7421
-
7422
- function getBaseFeeNumerator(feeSchedulerMode, cliffFeeNumerator, period, reductionFactor) {
7423
- let feeNumerator;
7424
- if (feeSchedulerMode == 0 /* Linear */) {
7425
- feeNumerator = cliffFeeNumerator.sub(period.mul(reductionFactor));
7426
- } else {
7427
- const bps = reductionFactor.shln(SCALE_OFFSET).div(new (0, _anchor.BN)(BASIS_POINT_MAX));
7428
- const base = ONE.sub(bps);
7429
- const result = pow(base, period);
7430
- feeNumerator = cliffFeeNumerator.mul(result).shrn(SCALE_OFFSET);
8255
+ // src/math/feeMath.ts
8256
+ function toNumerator(bps, feeDenominator) {
8257
+ try {
8258
+ const numerator = mulDiv(
8259
+ bps,
8260
+ feeDenominator,
8261
+ new (0, _anchor.BN)(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");
7431
8267
  }
7432
- return feeNumerator;
7433
8268
  }
7434
- function getDynamicFeeNumerator(volatilityAccumulator, binStep, variableFeeControl) {
7435
- if (variableFeeControl.isZero()) {
7436
- return new (0, _anchor.BN)(0);
8269
+ function getFeeInPeriod(cliffFeeNumerator, reductionFactor, passedPeriod) {
8270
+ if (reductionFactor.isZero()) {
8271
+ return cliffFeeNumerator;
7437
8272
  }
7438
- const squareVfaBin = volatilityAccumulator.mul(new (0, _anchor.BN)(binStep)).pow(new (0, _anchor.BN)(2));
7439
- const vFee = variableFeeControl.mul(squareVfaBin);
7440
- return vFee.add(new (0, _anchor.BN)(99999999999)).div(new (0, _anchor.BN)(1e11));
8273
+ const bps = reductionFactor.shln(SCALE_OFFSET).div(new (0, _anchor.BN)(BASIS_POINT_MAX));
8274
+ const base = ONE_Q64.sub(bps);
8275
+ const result = pow(base, new (0, _anchor.BN)(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;
7441
8284
  }
7442
- function getFeeNumerator(currentPoint, activationPoint, numberOfPeriod, periodFrequency, feeSchedulerMode, cliffFeeNumerator, reductionFactor, dynamicFeeParams) {
7443
- let feeNumerator;
7444
- if (Number(periodFrequency) == 0 || new (0, _anchor.BN)(currentPoint).lt(activationPoint)) {
7445
- feeNumerator = cliffFeeNumerator;
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
+ }
7446
8296
  } else {
7447
- const period = _anchor.BN.min(
7448
- new (0, _anchor.BN)(numberOfPeriod),
7449
- new (0, _anchor.BN)(currentPoint).sub(activationPoint).div(periodFrequency)
7450
- );
7451
- feeNumerator = getBaseFeeNumerator(
7452
- feeSchedulerMode,
7453
- cliffFeeNumerator,
7454
- period,
7455
- reductionFactor
7456
- );
8297
+ if (tradeDirection === 0 /* AtoB */) {
8298
+ feesOnInput = false;
8299
+ feesOnTokenA = false;
8300
+ } else {
8301
+ feesOnInput = true;
8302
+ feesOnTokenA = false;
8303
+ }
7457
8304
  }
7458
- if (dynamicFeeParams) {
7459
- const { volatilityAccumulator, binStep, variableFeeControl } = dynamicFeeParams;
7460
- const dynamicFeeNumberator = getDynamicFeeNumerator(
7461
- volatilityAccumulator,
7462
- new (0, _anchor.BN)(binStep),
7463
- new (0, _anchor.BN)(variableFeeControl)
7464
- );
7465
- feeNumerator = feeNumerator.add(dynamicFeeNumberator);
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 (0, _anchor.BN)(poolFees.dynamicFee.binStep),
8315
+ new (0, _anchor.BN)(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;
7466
8325
  }
7467
- return feeNumerator.gt(new (0, _anchor.BN)(MAX_FEE_NUMERATOR)) ? new (0, _anchor.BN)(MAX_FEE_NUMERATOR) : feeNumerator;
7468
8326
  }
7469
- function getFeeMode(collectFeeMode, btoA) {
7470
- const feeOnInput = btoA && collectFeeMode === 1 /* OnlyB */;
7471
- const feesOnTokenA = btoA && collectFeeMode === 0 /* BothToken */;
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 (0, _anchor.BN)(0);
8363
+ if (hasReferral) {
8364
+ referralFee = protocolFee.muln(poolFees.referralFeePercent).divn(100);
8365
+ }
8366
+ const protocolFeeAfterReferral = protocolFee.sub(referralFee);
8367
+ let partnerFee = new (0, _anchor.BN)(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
+ );
7472
8390
  return {
7473
- feeOnInput,
7474
- feesOnTokenA
8391
+ amount: excludedFeeAmount,
8392
+ tradingFee: splitFeesResult.tradingFee,
8393
+ protocolFee: splitFeesResult.protocolFee,
8394
+ partnerFee: splitFeesResult.partnerFee,
8395
+ referralFee: splitFeesResult.referralFee
7475
8396
  };
7476
8397
  }
7477
- function getTotalFeeOnAmount(amount, tradeFeeNumerator) {
7478
- return mulDiv(
7479
- amount,
8398
+ function getExcludedFeeAmount(tradeFeeNumerator, includedFeeAmount) {
8399
+ const tradingFee = mulDiv(
8400
+ includedFeeAmount,
7480
8401
  tradeFeeNumerator,
7481
8402
  new (0, _anchor.BN)(FEE_DENOMINATOR),
7482
8403
  0 /* Up */
7483
8404
  );
8405
+ const excludedFeeAmount = includedFeeAmount.sub(tradingFee);
8406
+ return { excludedFeeAmount, tradingFee };
7484
8407
  }
7485
- function getSwapAmount(inAmount, sqrtPrice, liquidity, tradeFeeNumerator, aToB, collectFeeMode) {
7486
- let feeMode = getFeeMode(collectFeeMode, !aToB);
7487
- let actualInAmount = inAmount;
7488
- let totalFee = new (0, _anchor.BN)(0);
7489
- if (feeMode.feeOnInput) {
7490
- totalFee = getTotalFeeOnAmount(inAmount, tradeFeeNumerator);
7491
- actualInAmount = inAmount.sub(totalFee);
7492
- }
7493
- const nextSqrtPrice = getNextSqrtPrice(
7494
- actualInAmount,
7495
- sqrtPrice,
7496
- liquidity,
7497
- aToB
7498
- );
7499
- const outAmount = aToB ? getAmountBFromLiquidityDelta(
7500
- liquidity,
7501
- sqrtPrice,
7502
- nextSqrtPrice,
7503
- 1 /* Down */
7504
- ) : getAmountAFromLiquidityDelta(
7505
- liquidity,
7506
- sqrtPrice,
7507
- nextSqrtPrice,
7508
- 1 /* Down */
8408
+ function getIncludedFeeAmount(tradeFeeNumerator, excludedFeeAmount) {
8409
+ const denominator = new (0, _anchor.BN)(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 (0, _anchor.BN)(FEE_DENOMINATOR),
8416
+ denominator,
8417
+ 0 /* Up */
7509
8418
  );
7510
- const amountOut = feeMode.feeOnInput ? outAmount : (totalFee = getTotalFeeOnAmount(outAmount, tradeFeeNumerator), outAmount.sub(totalFee));
7511
- return { amountOut, totalFee, nextSqrtPrice };
8419
+ const feeAmount = includedFeeAmount.sub(excludedFeeAmount);
8420
+ return { includedFeeAmount, feeAmount };
7512
8421
  }
7513
- function bpsToFeeNumerator(bps) {
7514
- return new (0, _anchor.BN)(bps * FEE_DENOMINATOR).divn(BASIS_POINT_MAX);
8422
+ function getMaxFeeNumerator(poolVersion) {
8423
+ switch (poolVersion) {
8424
+ case 0 /* V0 */:
8425
+ return new (0, _anchor.BN)(MAX_FEE_NUMERATOR_V0);
8426
+ case 1 /* V1 */:
8427
+ return new (0, _anchor.BN)(MAX_FEE_NUMERATOR_V1);
8428
+ default:
8429
+ throw new Error("Invalid pool version");
8430
+ }
7515
8431
  }
7516
- function feeNumeratorToBps(feeNumerator) {
7517
- return feeNumerator.muln(BASIS_POINT_MAX).div(new (0, _anchor.BN)(FEE_DENOMINATOR)).toNumber();
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
+ }
7518
8441
  }
7519
- function getBaseFeeParams(maxBaseFeeBps, minBaseFeeBps, feeSchedulerMode, numberOfPeriod, totalDuration) {
7520
- if (maxBaseFeeBps == minBaseFeeBps) {
7521
- if (numberOfPeriod != 0 || totalDuration != 0) {
7522
- throw new Error("numberOfPeriod and totalDuration must both be zero");
7523
- }
7524
- return {
7525
- cliffFeeNumerator: bpsToFeeNumerator(maxBaseFeeBps),
7526
- numberOfPeriod: 0,
7527
- periodFrequency: new (0, _anchor.BN)(0),
7528
- reductionFactor: new (0, _anchor.BN)(0),
7529
- feeSchedulerMode: 0
7530
- };
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 (0, _bnjs2.default)(maxLimiterDuration)
8467
+ );
8468
+ if (currentPoint.gt(lastEffectiveRateLimiterPoint)) {
8469
+ return false;
7531
8470
  }
7532
- if (numberOfPeriod <= 0) {
7533
- throw new Error("Total periods must be greater than zero");
8471
+ return true;
8472
+ }
8473
+ function getMaxIndex(maxFeeBps, cliffFeeNumerator, feeIncrementBps) {
8474
+ const maxFeeNumerator = toNumerator(
8475
+ new (0, _bnjs2.default)(maxFeeBps),
8476
+ new (0, _bnjs2.default)(FEE_DENOMINATOR)
8477
+ );
8478
+ if (cliffFeeNumerator.gt(maxFeeNumerator)) {
8479
+ throw new Error("cliffFeeNumerator cannot be greater than maxFeeNumerator");
7534
8480
  }
7535
- if (maxBaseFeeBps > feeNumeratorToBps(new (0, _anchor.BN)(MAX_FEE_NUMERATOR))) {
7536
- throw new Error(
7537
- `maxBaseFeeBps (${maxBaseFeeBps} bps) exceeds maximum allowed value of ${feeNumeratorToBps(
7538
- new (0, _anchor.BN)(MAX_FEE_NUMERATOR)
7539
- )} bps`
8481
+ const deltaNumerator = maxFeeNumerator.sub(cliffFeeNumerator);
8482
+ const feeIncrementNumerator = toNumerator(
8483
+ new (0, _bnjs2.default)(feeIncrementBps),
8484
+ new (0, _bnjs2.default)(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 (0, _bnjs2.default)(maxFeeBps),
8498
+ new (0, _bnjs2.default)(FEE_DENOMINATOR)
7540
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 (0, _bnjs2.default)(feeIncrementBps), new (0, _bnjs2.default)(FEE_DENOMINATOR));
8506
+ const x0 = referenceAmount;
8507
+ const one = new (0, _bnjs2.default)(1);
8508
+ const two = new (0, _bnjs2.default)(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 (0, _bnjs2.default)(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 (0, _bnjs2.default)(U64_MAX))) {
8529
+ throw new Error("Numerator does not fit in u64");
8530
+ }
8531
+ return numerator;
7541
8532
  }
7542
- if (minBaseFeeBps > maxBaseFeeBps) {
7543
- throw new Error(
7544
- "minBaseFee bps must be less than or equal to maxBaseFee bps"
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 (0, _bnjs2.default)(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
7545
8571
  );
8572
+ return [checkedOutputAmount, checkedIncludedFeeAmount, true];
7546
8573
  }
7547
- if (numberOfPeriod == 0 || totalDuration == 0) {
7548
- throw new Error(
7549
- "numberOfPeriod and totalDuration must both greater than zero"
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
7550
8599
  );
7551
8600
  }
7552
- const maxBaseFeeNumerator = bpsToFeeNumerator(maxBaseFeeBps);
7553
- const minBaseFeeNumerator = bpsToFeeNumerator(minBaseFeeBps);
7554
- const periodFrequency = new (0, _anchor.BN)(totalDuration / numberOfPeriod);
7555
- let reductionFactor;
7556
- if (feeSchedulerMode == 0 /* Linear */) {
7557
- const totalReduction = maxBaseFeeNumerator.sub(minBaseFeeNumerator);
7558
- reductionFactor = totalReduction.divn(numberOfPeriod);
8601
+ let includedFeeAmount;
8602
+ if (excludedFeeAmount.lt(checkedExcludedFeeAmount)) {
8603
+ const TWO = new (0, _bnjs2.default)(2);
8604
+ const FOUR = new (0, _bnjs2.default)(4);
8605
+ const i = toNumerator(new (0, _bnjs2.default)(feeIncrementBps), new (0, _bnjs2.default)(FEE_DENOMINATOR));
8606
+ const x0 = referenceAmount;
8607
+ const d = new (0, _bnjs2.default)(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);
7559
8636
  } else {
7560
- const ratio = minBaseFeeNumerator.toNumber() / maxBaseFeeNumerator.toNumber();
7561
- const decayBase = Math.pow(ratio, 1 / numberOfPeriod);
7562
- reductionFactor = new (0, _anchor.BN)(BASIS_POINT_MAX * (1 - decayBase));
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 (0, _bnjs2.default)(maxFeeBps),
8645
+ new (0, _bnjs2.default)(FEE_DENOMINATOR)
8646
+ );
8647
+ const { includedFeeAmount: includedFeeRemainingAmount } = getIncludedFeeAmount(maxFeeNumerator, excludedFeeRemainingAmount);
8648
+ includedFeeAmount = includedFeeRemainingAmount.add(
8649
+ checkedIncludedFeeAmount
8650
+ );
7563
8651
  }
7564
- return {
7565
- cliffFeeNumerator: maxBaseFeeNumerator,
8652
+ const tradingFee = includedFeeAmount.sub(excludedFeeAmount);
8653
+ const feeNumerator = mulDiv(
8654
+ tradingFee,
8655
+ new (0, _bnjs2.default)(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
+
8667
+ function getMaxBaseFeeNumerator(cliffFeeNumerator) {
8668
+ return cliffFeeNumerator;
8669
+ }
8670
+ function getMinBaseFeeNumerator(cliffFeeNumerator, numberOfPeriod, periodFrequency, reductionFactor, feeSchedulerMode) {
8671
+ return getBaseFeeNumeratorByPeriod(
8672
+ cliffFeeNumerator,
7566
8673
  numberOfPeriod,
7567
8674
  periodFrequency,
7568
8675
  reductionFactor,
7569
8676
  feeSchedulerMode
7570
- };
8677
+ );
7571
8678
  }
7572
- function getDynamicFeeParams(baseFeeBps, maxPriceChangeBps = MAX_PRICE_CHANGE_BPS_DEFAULT) {
7573
- if (maxPriceChangeBps > MAX_PRICE_CHANGE_BPS_DEFAULT) {
7574
- throw new Error(
7575
- `maxPriceChangeBps (${maxPriceChangeBps} bps) must be less than or equal to ${MAX_PRICE_CHANGE_BPS_DEFAULT}`
7576
- );
8679
+ function getBaseFeeNumeratorByPeriod(cliffFeeNumerator, numberOfPeriod, period, reductionFactor, feeSchedulerMode) {
8680
+ const periodValue = _bnjs2.default.min(period, new (0, _bnjs2.default)(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");
7577
8704
  }
7578
- const priceRatio = maxPriceChangeBps / BASIS_POINT_MAX + 1;
7579
- const sqrtPriceRatioQ64 = new (0, _anchor.BN)(
7580
- _decimaljs2.default.sqrt(priceRatio.toString()).mul(_decimaljs2.default.pow(2, 64)).floor().toFixed()
8705
+ }
8706
+ function getFeeNumeratorOnLinearFeeScheduler(cliffFeeNumerator, reductionFactor, period) {
8707
+ const reduction = new (0, _bnjs2.default)(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 (0, _bnjs2.default)(BASIS_POINT_MAX);
8715
+ const bps = new (0, _bnjs2.default)(reductionFactor).shln(64).div(basisPointMax);
8716
+ const base = ONE_Q64.sub(bps);
8717
+ const result = pow(base, new (0, _bnjs2.default)(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
7581
8731
  );
7582
- const deltaBinId = sqrtPriceRatioQ64.sub(ONE).div(BIN_STEP_BPS_U128_DEFAULT).muln(2);
7583
- const maxVolatilityAccumulator = new (0, _anchor.BN)(deltaBinId.muln(BASIS_POINT_MAX));
7584
- const squareVfaBin = maxVolatilityAccumulator.mul(new (0, _anchor.BN)(BIN_STEP_BPS_DEFAULT)).pow(new (0, _anchor.BN)(2));
7585
- const baseFeeNumerator = new (0, _anchor.BN)(bpsToFeeNumerator(baseFeeBps));
7586
- const maxDynamicFeeNumerator = baseFeeNumerator.muln(20).divn(100);
7587
- const vFee = maxDynamicFeeNumerator.mul(new (0, _anchor.BN)(1e11)).sub(new (0, _anchor.BN)(99999999999));
7588
- const variableFeeControl = vFee.div(squareVfaBin);
7589
- return {
7590
- binStep: BIN_STEP_BPS_DEFAULT,
7591
- binStepU128: BIN_STEP_BPS_U128_DEFAULT,
7592
- filterPeriod: DYNAMIC_FEE_FILTER_PERIOD_DEFAULT,
7593
- decayPeriod: DYNAMIC_FEE_DECAY_PERIOD_DEFAULT,
7594
- reductionFactor: DYNAMIC_FEE_REDUCTION_FACTOR_DEFAULT,
7595
- maxVolatilityAccumulator: maxVolatilityAccumulator.toNumber(),
7596
- variableFeeControl: variableFeeControl.toNumber()
7597
- };
7598
8732
  }
7599
- function getExcludedFeeAmount(tradeFeeNumerator, includedFeeAmount) {
7600
- const tradingFee = mulDiv(
7601
- includedFeeAmount,
7602
- tradeFeeNumerator,
7603
- new (0, _anchor.BN)(FEE_DENOMINATOR),
7604
- 0 /* Up */
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 (0, _bnjs2.default)(
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
+
8887
+ function isDynamicFeeEnabled(dynamicFee) {
8888
+ return dynamicFee.initialized !== 0;
8889
+ }
8890
+ function getDynamicFeeNumerator(volatilityAccumulator, binStep, variableFeeControl) {
8891
+ if (variableFeeControl.isZero()) {
8892
+ return new (0, _bnjs2.default)(0);
8893
+ }
8894
+ const squareVfaBin = volatilityAccumulator.mul(new (0, _bnjs2.default)(binStep)).pow(new (0, _bnjs2.default)(2));
8895
+ const vFee = variableFeeControl.mul(squareVfaBin);
8896
+ return vFee.add(new (0, _bnjs2.default)(DYNAMIC_FEE_ROUNDING_OFFSET)).div(new (0, _bnjs2.default)(DYNAMIC_FEE_SCALING_FACTOR));
8897
+ }
8898
+
8899
+ // src/math/quote.ts
8900
+
8901
+
8902
+ // src/math/curve.ts
8903
+
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 (0, _bnjs2.default)(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 (0, _bnjs2.default)(0))) {
8940
+ throw new Error("sqrtPrice must be greater than 0");
8941
+ }
8942
+ if (liquidity.lte(new (0, _bnjs2.default)(0))) {
8943
+ throw new Error("liquidity must be greater than 0");
8944
+ }
8945
+ if (aForB) {
8946
+ return getNextSqrtPriceFromAmountOutBRoundingDown(
8947
+ sqrtPrice,
8948
+ liquidity,
8949
+ amountOut
8950
+ );
8951
+ } else {
8952
+ return getNextSqrtPriceFromAmountOutARoundingUp(
8953
+ sqrtPrice,
8954
+ liquidity,
8955
+ amountOut
8956
+ );
8957
+ }
8958
+ }
8959
+ function getNextSqrtPriceFromInput(sqrtPrice, liquidity, amountIn, aForB) {
8960
+ if (sqrtPrice.lte(new (0, _bnjs2.default)(0))) {
8961
+ throw new Error("sqrtPrice must be greater than 0");
8962
+ }
8963
+ if (liquidity.lte(new (0, _bnjs2.default)(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
+ );
8972
+ } else {
8973
+ return getNextSqrtPriceFromAmountInBRoundingDown(
8974
+ sqrtPrice,
8975
+ liquidity,
8976
+ amountIn
8977
+ );
8978
+ }
8979
+ }
8980
+ function getAmountBFromLiquidityDelta(lowerSqrtPrice, upperSqrtPrice, liquidity, rounding) {
8981
+ const result = getDeltaAmountBUnsignedUnchecked(
8982
+ lowerSqrtPrice,
8983
+ upperSqrtPrice,
8984
+ liquidity,
8985
+ rounding
7605
8986
  );
7606
- const excludedFeeAmount = includedFeeAmount.sub(tradingFee);
7607
- return { excludedFeeAmount, tradingFee };
8987
+ if (result.gt(U64_MAX)) {
8988
+ throw new Error("MathOverflow: result exceeds u64 max");
8989
+ }
8990
+ return result;
7608
8991
  }
7609
- function getIncludedFeeAmount(tradeFeeNumerator, excludedFeeAmount) {
7610
- const denominator = new (0, _anchor.BN)(FEE_DENOMINATOR).sub(tradeFeeNumerator);
7611
- if (denominator.isZero() || denominator.isNeg()) {
7612
- throw new Error("Invalid fee numerator");
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 (0, _bnjs2.default)(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;
7613
9003
  }
7614
- const includedFeeAmount = mulDiv(
7615
- excludedFeeAmount,
7616
- new (0, _anchor.BN)(FEE_DENOMINATOR),
7617
- denominator,
7618
- 0 /* Up */
9004
+ }
9005
+ function getAmountAFromLiquidityDelta(lowerSqrtPrice, upperSqrtPrice, liquidity, rounding) {
9006
+ const result = getDeltaAmountAUnsignedUnchecked(
9007
+ lowerSqrtPrice,
9008
+ upperSqrtPrice,
9009
+ liquidity,
9010
+ rounding
7619
9011
  );
7620
- const { excludedFeeAmount: inverseAmount } = getExcludedFeeAmount(
7621
- tradeFeeNumerator,
7622
- includedFeeAmount
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 (0, _bnjs2.default)(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 (0, _bnjs2.default)(0);
9041
+ let actualTradingFee = new (0, _bnjs2.default)(0);
9042
+ let actualReferralFee = new (0, _bnjs2.default)(0);
9043
+ let actualPartnerFee = new (0, _bnjs2.default)(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
7623
9052
  );
7624
- if (inverseAmount.lt(excludedFeeAmount)) {
7625
- throw new Error("Inverse amount is less than excluded_fee_amount");
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)
9061
+ );
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;
7626
9093
  }
7627
- return includedFeeAmount;
9094
+ return {
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
9104
+ };
7628
9105
  }
7629
- function getInAmountFromAToB(pool, outAmount) {
7630
- const nextSqrtPrice = getNextSqrtPriceFromOutput(
7631
- pool.sqrtPrice,
7632
- pool.liquidity,
7633
- outAmount,
9106
+ function calculateAtoBFromAmountIn(poolState, amountIn) {
9107
+ const nextSqrtPrice = getNextSqrtPriceFromInput(
9108
+ poolState.sqrtPrice,
9109
+ poolState.liquidity,
9110
+ amountIn,
7634
9111
  true
7635
9112
  );
7636
- if (nextSqrtPrice.lt(pool.sqrtMinPrice)) {
9113
+ if (nextSqrtPrice.lt(poolState.sqrtMinPrice)) {
7637
9114
  throw new Error("Price range is violated");
7638
9115
  }
7639
- const outputAmount = getAmountAFromLiquidityDelta(
7640
- pool.liquidity,
9116
+ const outputAmount = getAmountBFromLiquidityDelta(
7641
9117
  nextSqrtPrice,
7642
- pool.sqrtPrice,
7643
- 0 /* Up */
9118
+ poolState.sqrtPrice,
9119
+ poolState.liquidity,
9120
+ 1 /* Down */
7644
9121
  );
7645
9122
  return {
7646
9123
  outputAmount,
7647
- nextSqrtPrice
9124
+ nextSqrtPrice,
9125
+ amountLeft: new (0, _bnjs2.default)(0)
7648
9126
  };
7649
9127
  }
7650
- function getInAmountFromBToA(pool, outAmount) {
7651
- const nextSqrtPrice = getNextSqrtPriceFromOutput(
7652
- pool.sqrtPrice,
7653
- pool.liquidity,
7654
- outAmount,
9128
+ function calculateBtoAFromAmountIn(poolState, amountIn) {
9129
+ const nextSqrtPrice = getNextSqrtPriceFromInput(
9130
+ poolState.sqrtPrice,
9131
+ poolState.liquidity,
9132
+ amountIn,
7655
9133
  false
7656
9134
  );
7657
- if (nextSqrtPrice.gt(pool.sqrtMaxPrice)) {
9135
+ if (nextSqrtPrice.gt(poolState.sqrtMaxPrice)) {
7658
9136
  throw new Error("Price range is violated");
7659
9137
  }
7660
- const outputAmount = getAmountBFromLiquidityDelta(
7661
- pool.liquidity,
7662
- pool.sqrtPrice,
9138
+ const outputAmount = getAmountAFromLiquidityDelta(
9139
+ poolState.sqrtPrice,
7663
9140
  nextSqrtPrice,
7664
- 0 /* Up */
9141
+ poolState.liquidity,
9142
+ 1 /* Down */
7665
9143
  );
7666
9144
  return {
7667
9145
  outputAmount,
7668
- nextSqrtPrice
9146
+ nextSqrtPrice,
9147
+ amountLeft: new (0, _bnjs2.default)(0)
7669
9148
  };
7670
9149
  }
7671
- function getSwapResultFromOutAmount(pool, outAmount, feeMode, tradeDirection, currentPoint) {
7672
- let actualProtocolFee = new (0, _anchor.BN)(0);
7673
- let actualLpFee = new (0, _anchor.BN)(0);
7674
- let actualPartnerFee = new (0, _anchor.BN)(0);
7675
- let actualReferralFee = new (0, _anchor.BN)(0);
7676
- const tradeFeeNumerator = getFeeNumerator(
9150
+ function getSwapResultFromPartialInput(poolState, amountIn, feeMode, tradeDirection, currentPoint) {
9151
+ let actualProtocolFee = new (0, _bnjs2.default)(0);
9152
+ let actualTradingFee = new (0, _bnjs2.default)(0);
9153
+ let actualReferralFee = new (0, _bnjs2.default)(0);
9154
+ let actualPartnerFee = new (0, _bnjs2.default)(0);
9155
+ const maxFeeNumerator = getMaxFeeNumerator(poolState.version);
9156
+ const tradeFeeNumerator = getTotalTradingFeeFromIncludedFeeAmount(
9157
+ poolState.poolFees,
7677
9158
  currentPoint,
7678
- pool.activationPoint,
7679
- pool.poolFees.baseFee.numberOfPeriod,
7680
- pool.poolFees.baseFee.periodFrequency,
7681
- pool.poolFees.baseFee.feeSchedulerMode,
7682
- pool.poolFees.baseFee.cliffFeeNumerator,
7683
- pool.poolFees.baseFee.reductionFactor,
7684
- pool.poolFees.dynamicFee.initialized === 1 ? {
7685
- volatilityAccumulator: pool.poolFees.dynamicFee.volatilityAccumulator,
7686
- binStep: pool.poolFees.dynamicFee.binStep,
7687
- variableFeeControl: pool.poolFees.dynamicFee.variableFeeControl
7688
- } : void 0
9159
+ poolState.activationPoint,
9160
+ amountIn,
9161
+ tradeDirection,
9162
+ maxFeeNumerator
7689
9163
  );
7690
- let includedFeeOutAmount;
7691
- if (feeMode.feeOnInput) {
7692
- includedFeeOutAmount = outAmount;
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)
9172
+ );
9173
+ actualProtocolFee = protocolFee;
9174
+ actualTradingFee = tradingFee;
9175
+ actualReferralFee = referralFee;
9176
+ actualPartnerFee = partnerFee;
9177
+ actualAmountIn = amount;
7693
9178
  } else {
7694
- includedFeeOutAmount = getIncludedFeeAmount(tradeFeeNumerator, outAmount);
7695
- const totalFee = getTotalFeeOnAmount(outAmount, tradeFeeNumerator);
7696
- actualProtocolFee = mulDiv(
7697
- totalFee,
7698
- new (0, _anchor.BN)(pool.poolFees.protocolFeePercent),
7699
- new (0, _anchor.BN)(100),
7700
- 1 /* Down */
9179
+ actualAmountIn = amountIn;
9180
+ }
9181
+ let swapAmountFromInput;
9182
+ if (tradeDirection === 0 /* AtoB */) {
9183
+ swapAmountFromInput = calculateAtoBFromPartialAmountIn(
9184
+ poolState,
9185
+ actualAmountIn
7701
9186
  );
7702
- if (feeMode.hasReferral) {
7703
- actualReferralFee = mulDiv(
7704
- actualProtocolFee,
7705
- new (0, _anchor.BN)(pool.poolFees.referralFeePercent),
7706
- new (0, _anchor.BN)(100),
7707
- 1 /* Down */
9187
+ } else {
9188
+ swapAmountFromInput = calculateBtoAFromPartialAmountIn(
9189
+ poolState,
9190
+ actualAmountIn
9191
+ );
9192
+ }
9193
+ let { amountLeft, outputAmount, nextSqrtPrice } = swapAmountFromInput;
9194
+ let includedFeeInputAmount;
9195
+ if (amountLeft.gt(new (0, _bnjs2.default)(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
7708
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;
7709
9223
  }
7710
- const protocolFeeAfterReferral = actualProtocolFee.sub(actualReferralFee);
7711
- actualPartnerFee = mulDiv(
7712
- protocolFeeAfterReferral,
7713
- new (0, _anchor.BN)(pool.poolFees.partnerFeePercent),
7714
- new (0, _anchor.BN)(100),
7715
- 1 /* Down */
9224
+ } else {
9225
+ includedFeeInputAmount = amountIn;
9226
+ }
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)
9237
+ );
9238
+ actualProtocolFee = protocolFee;
9239
+ actualTradingFee = tradingFee;
9240
+ actualReferralFee = referralFee;
9241
+ actualPartnerFee = partnerFee;
9242
+ actualAmountOut = amount;
9243
+ }
9244
+ return {
9245
+ includedFeeInputAmount,
9246
+ excludedFeeInputAmount: actualAmountIn,
9247
+ amountLeft,
9248
+ outputAmount: actualAmountOut,
9249
+ nextSqrtPrice,
9250
+ tradingFee: actualTradingFee,
9251
+ protocolFee: actualProtocolFee,
9252
+ partnerFee: actualPartnerFee,
9253
+ referralFee: actualReferralFee
9254
+ };
9255
+ }
9256
+ function calculateAtoBFromPartialAmountIn(poolState, amountIn) {
9257
+ const maxAmountIn = getAmountAFromLiquidityDelta(
9258
+ poolState.sqrtMinPrice,
9259
+ poolState.sqrtPrice,
9260
+ poolState.liquidity,
9261
+ 0 /* Up */
9262
+ );
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;
9276
+ }
9277
+ const outputAmount = getAmountBFromLiquidityDelta(
9278
+ nextSqrtPrice,
9279
+ poolState.sqrtPrice,
9280
+ poolState.liquidity,
9281
+ 1 /* Down */
9282
+ );
9283
+ const amountLeft = amountIn.sub(consumedInAmount);
9284
+ return {
9285
+ outputAmount,
9286
+ nextSqrtPrice,
9287
+ amountLeft
9288
+ };
9289
+ }
9290
+ function calculateBtoAFromPartialAmountIn(poolState, amountIn) {
9291
+ const maxAmountIn = getAmountBFromLiquidityDelta(
9292
+ poolState.sqrtPrice,
9293
+ poolState.sqrtMaxPrice,
9294
+ poolState.liquidity,
9295
+ 0 /* Up */
9296
+ );
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
7716
9308
  );
7717
- actualLpFee = totalFee.sub(actualProtocolFee).sub(actualPartnerFee);
9309
+ consumedInAmount = amountIn;
7718
9310
  }
7719
- const { outputAmount: excludedFeeInAmount, nextSqrtPrice } = tradeDirection === 0 /* AtoB */ ? getInAmountFromAToB(pool, includedFeeOutAmount) : getInAmountFromBToA(pool, includedFeeOutAmount);
7720
- let includedFeeInAmount;
7721
- if (feeMode.feeOnInput) {
7722
- includedFeeInAmount = getIncludedFeeAmount(
9311
+ const outputAmount = getAmountAFromLiquidityDelta(
9312
+ poolState.sqrtPrice,
9313
+ nextSqrtPrice,
9314
+ poolState.liquidity,
9315
+ 1 /* Down */
9316
+ );
9317
+ const amountLeft = amountIn.sub(consumedInAmount);
9318
+ return {
9319
+ outputAmount,
9320
+ nextSqrtPrice,
9321
+ amountLeft
9322
+ };
9323
+ }
9324
+ function getSwapResultFromExactOutput(poolState, amountOut, feeMode, tradeDirection, currentPoint) {
9325
+ let actualProtocolFee = new (0, _bnjs2.default)(0);
9326
+ let actualTradingFee = new (0, _bnjs2.default)(0);
9327
+ let actualReferralFee = new (0, _bnjs2.default)(0);
9328
+ let actualPartnerFee = new (0, _bnjs2.default)(0);
9329
+ const maxFeeNumerator = getMaxFeeNumerator(poolState.version);
9330
+ let includedFeeAmountOut;
9331
+ if (feeMode.feesOnInput) {
9332
+ includedFeeAmountOut = amountOut;
9333
+ } else {
9334
+ const tradeFeeNumerator = getTotalTradingFeeFromExcludedFeeAmount(
9335
+ poolState.poolFees,
9336
+ currentPoint,
9337
+ poolState.activationPoint,
9338
+ amountOut,
9339
+ tradeDirection,
9340
+ maxFeeNumerator
9341
+ );
9342
+ const { includedFeeAmount, feeAmount } = getIncludedFeeAmount(
7723
9343
  tradeFeeNumerator,
7724
- excludedFeeInAmount
9344
+ amountOut
7725
9345
  );
7726
- const totalFee = getTotalFeeOnAmount(
7727
- includedFeeInAmount,
7728
- tradeFeeNumerator
9346
+ const split = splitFees(
9347
+ poolState.poolFees,
9348
+ feeAmount,
9349
+ feeMode.hasReferral,
9350
+ hasPartner(poolState.partner)
7729
9351
  );
7730
- actualProtocolFee = mulDiv(
7731
- totalFee,
7732
- new (0, _anchor.BN)(pool.poolFees.protocolFeePercent),
7733
- new (0, _anchor.BN)(100),
7734
- 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
7735
9363
  );
7736
- if (feeMode.hasReferral) {
7737
- actualReferralFee = mulDiv(
7738
- actualProtocolFee,
7739
- new (0, _anchor.BN)(pool.poolFees.referralFeePercent),
7740
- new (0, _anchor.BN)(100),
7741
- 1 /* Down */
7742
- );
7743
- }
7744
- const protocolFeeAfterReferral = actualProtocolFee.sub(actualReferralFee);
7745
- actualPartnerFee = mulDiv(
7746
- protocolFeeAfterReferral,
7747
- new (0, _anchor.BN)(pool.poolFees.partnerFeePercent),
7748
- new (0, _anchor.BN)(100),
7749
- 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
9380
+ );
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)
7750
9390
  );
7751
- actualLpFee = totalFee.sub(actualProtocolFee).sub(actualPartnerFee);
9391
+ actualTradingFee = split.tradingFee;
9392
+ actualProtocolFee = split.protocolFee;
9393
+ actualReferralFee = split.referralFee;
9394
+ actualPartnerFee = split.partnerFee;
9395
+ includedFeeInputAmount = includedFeeAmount;
7752
9396
  } else {
7753
- includedFeeInAmount = excludedFeeInAmount;
9397
+ includedFeeInputAmount = inputAmount;
7754
9398
  }
7755
9399
  return {
7756
- swapResult: {
7757
- outputAmount: outAmount,
7758
- nextSqrtPrice,
7759
- lpFee: actualLpFee,
7760
- protocolFee: actualProtocolFee,
7761
- referralFee: actualReferralFee,
7762
- partnerFee: actualPartnerFee
7763
- },
7764
- inputAmount: includedFeeInAmount
9400
+ amountLeft: new (0, _bnjs2.default)(0),
9401
+ includedFeeInputAmount,
9402
+ excludedFeeInputAmount: inputAmount,
9403
+ outputAmount: amountOut,
9404
+ nextSqrtPrice,
9405
+ tradingFee: actualTradingFee,
9406
+ protocolFee: actualProtocolFee,
9407
+ partnerFee: actualPartnerFee,
9408
+ referralFee: actualReferralFee
7765
9409
  };
7766
9410
  }
7767
-
7768
- // src/helpers/computeUnits.ts
7769
-
7770
-
7771
-
7772
-
7773
-
7774
-
7775
- var getSimulationComputeUnits = (connection, instructions, payer, lookupTables, commitment = "confirmed") => __async(void 0, null, function* () {
7776
- var _a, _b, _c;
7777
- const testInstructions = [
7778
- // Set an arbitrarily high number in simulation
7779
- // so we can be sure the transaction will succeed
7780
- // and get the real compute units used
7781
- _web3js.ComputeBudgetProgram.setComputeUnitLimit({ units: 14e5 }),
7782
- ...instructions
7783
- ];
7784
- const testTransaction = new (0, _web3js.VersionedTransaction)(
7785
- new (0, _web3js.TransactionMessage)({
7786
- instructions: testInstructions,
7787
- payerKey: payer,
7788
- // RecentBlockhash can by any public key during simulation
7789
- // since 'replaceRecentBlockhash' is set to 'true' below
7790
- recentBlockhash: _web3js.PublicKey.default.toString()
7791
- }).compileToV0Message(lookupTables)
9411
+ function calculateAtoBFromAmountOut(poolState, amountOut) {
9412
+ const nextSqrtPrice = getNextSqrtPriceFromOutput(
9413
+ poolState.sqrtPrice,
9414
+ poolState.liquidity,
9415
+ amountOut,
9416
+ true
7792
9417
  );
7793
- const rpcResponse = yield connection.simulateTransaction(testTransaction, {
7794
- replaceRecentBlockhash: true,
7795
- sigVerify: false,
7796
- commitment
7797
- });
7798
- if ((_a = rpcResponse == null ? void 0 : rpcResponse.value) == null ? void 0 : _a.err) {
7799
- const logs = ((_b = rpcResponse.value.logs) == null ? void 0 : _b.join("\n \u2022 ")) || "No logs available";
7800
- throw new Error(
7801
- `Transaction simulation failed:
7802
- \u2022${logs}` + JSON.stringify((_c = rpcResponse == null ? void 0 : rpcResponse.value) == null ? void 0 : _c.err)
7803
- );
7804
- }
7805
- return rpcResponse.value.unitsConsumed || null;
7806
- });
7807
- var getEstimatedComputeUnitUsageWithBuffer = (connection, instructions, feePayer, buffer) => __async(void 0, null, function* () {
7808
- if (!buffer) {
7809
- buffer = 0.1;
9418
+ if (nextSqrtPrice.lt(poolState.sqrtMinPrice)) {
9419
+ throw new Error("Price Range Violation");
7810
9420
  }
7811
- buffer = Math.max(0, buffer);
7812
- buffer = Math.min(1, buffer);
7813
- const estimatedComputeUnitUsage = yield getSimulationComputeUnits(
7814
- connection,
7815
- instructions,
7816
- feePayer,
7817
- []
9421
+ const inputAmount = getAmountAFromLiquidityDelta(
9422
+ nextSqrtPrice,
9423
+ poolState.sqrtPrice,
9424
+ poolState.liquidity,
9425
+ 0 /* Up */
7818
9426
  );
7819
- if (!estimatedComputeUnitUsage) {
7820
- return 0;
7821
- }
7822
- let extraComputeUnitBuffer = estimatedComputeUnitUsage * buffer;
7823
- if (extraComputeUnitBuffer > MAX_CU_BUFFER) {
7824
- extraComputeUnitBuffer = MAX_CU_BUFFER;
7825
- } else if (extraComputeUnitBuffer < MIN_CU_BUFFER) {
7826
- extraComputeUnitBuffer = MIN_CU_BUFFER;
9427
+ return {
9428
+ inputAmount,
9429
+ nextSqrtPrice
9430
+ };
9431
+ }
9432
+ function calculateBtoAFromAmountOut(poolState, amountOut) {
9433
+ const nextSqrtPrice = getNextSqrtPriceFromOutput(
9434
+ poolState.sqrtPrice,
9435
+ poolState.liquidity,
9436
+ amountOut,
9437
+ false
9438
+ );
9439
+ if (nextSqrtPrice.gt(poolState.sqrtMaxPrice)) {
9440
+ throw new Error("Price Range Violation");
7827
9441
  }
7828
- return estimatedComputeUnitUsage + extraComputeUnitBuffer;
7829
- });
7830
- var getEstimatedComputeUnitIxWithBuffer = (connection, instructions, feePayer, buffer) => __async(void 0, null, function* () {
7831
- const units = yield getEstimatedComputeUnitUsageWithBuffer(
7832
- connection,
7833
- instructions,
7834
- feePayer,
7835
- buffer
7836
- ).catch((error) => {
7837
- console.error("Error::getEstimatedComputeUnitUsageWithBuffer", error);
7838
- return 14e5;
7839
- });
7840
- return _web3js.ComputeBudgetProgram.setComputeUnitLimit({ units });
7841
- });
7842
-
7843
- // src/helpers/utils.ts
7844
-
7845
-
7846
- var getMaxAmountWithSlippage = (amount, rate) => {
7847
- const slippage = (100 + rate) / 100 * BASIS_POINT_MAX;
7848
- return amount.mul(new (0, _anchor.BN)(slippage)).div(new (0, _anchor.BN)(BASIS_POINT_MAX));
7849
- };
7850
- var getMinAmountWithSlippage = (amount, rate) => {
7851
- const slippage = (100 - rate) / 100 * BASIS_POINT_MAX;
7852
- return amount.mul(new (0, _anchor.BN)(slippage)).div(new (0, _anchor.BN)(BASIS_POINT_MAX));
7853
- };
7854
- var getPriceImpact = (amountIn, amountOut, currentSqrtPrice, aToB, tokenADecimal, tokenBDecimal) => {
7855
- if (amountIn.eq(new (0, _anchor.BN)(0))) {
7856
- return new (0, _decimaljs2.default)(0);
9442
+ const inputAmount = getAmountBFromLiquidityDelta(
9443
+ poolState.sqrtPrice,
9444
+ nextSqrtPrice,
9445
+ poolState.liquidity,
9446
+ 0 /* Up */
9447
+ );
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 (0, _bnjs2.default)(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;
7857
9484
  }
7858
- if (amountOut.eq(new (0, _anchor.BN)(0))) {
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
9501
+ });
9502
+ }
9503
+ function swapQuoteExactOutput(pool, currentPoint, amountOut, slippage, aToB, hasReferral, tokenADecimal, tokenBDecimal, inputTokenInfo, outputTokenInfo) {
9504
+ if (amountOut.lte(new (0, _bnjs2.default)(0))) {
7859
9505
  throw new Error("Amount out must be greater than 0");
7860
9506
  }
7861
- const spotPrice = getPriceFromSqrtPrice(
7862
- 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,
7863
9545
  tokenADecimal,
7864
9546
  tokenBDecimal
7865
9547
  );
7866
- const executionPrice = new (0, _decimaljs2.default)(amountIn.toString()).div(new (0, _decimaljs2.default)(amountOut.toString())).mul(
7867
- _decimaljs2.default.pow(
7868
- 10,
7869
- aToB ? tokenBDecimal - tokenADecimal : tokenADecimal - tokenBDecimal
7870
- )
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 (0, _bnjs2.default)(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
7871
9576
  );
7872
- let priceImpact;
7873
- let actualExecutionPrice;
7874
- if (aToB) {
7875
- actualExecutionPrice = new (0, _decimaljs2.default)(1).div(executionPrice);
7876
- } else {
7877
- actualExecutionPrice = executionPrice;
9577
+ let actualAmountOut = swapResult.outputAmount;
9578
+ if (outputTokenInfo) {
9579
+ actualAmountOut = calculateTransferFeeExcludedAmount(
9580
+ swapResult.outputAmount,
9581
+ outputTokenInfo.mint,
9582
+ outputTokenInfo.currentEpoch
9583
+ ).amount;
7878
9584
  }
7879
- priceImpact = actualExecutionPrice.sub(spotPrice).abs().div(spotPrice).mul(100);
7880
- return priceImpact;
7881
- };
7882
- var getPriceChange = (nextSqrtPrice, currentSqrtPrice) => {
7883
- const diff = nextSqrtPrice.pow(new (0, _anchor.BN)(2)).sub(currentSqrtPrice.pow(new (0, _anchor.BN)(2))).abs();
7884
- return new (0, _decimaljs2.default)(diff.toString()).div(new (0, _decimaljs2.default)(currentSqrtPrice.pow(new (0, _anchor.BN)(2)).toString())).mul(100).toNumber();
7885
- };
7886
- var getPriceFromSqrtPrice = (sqrtPrice, tokenADecimal, tokenBDecimal) => {
7887
- const decimalSqrtPrice = new (0, _decimaljs2.default)(sqrtPrice.toString());
7888
- const price = decimalSqrtPrice.mul(decimalSqrtPrice).mul(new (0, _decimaljs2.default)(__pow(10, tokenADecimal - tokenBDecimal))).div(_decimaljs2.default.pow(2, 128));
7889
- return price;
7890
- };
7891
- var getSqrtPriceFromPrice = (price, tokenADecimal, tokenBDecimal) => {
7892
- const decimalPrice = new (0, _decimaljs2.default)(price);
7893
- const adjustedByDecimals = decimalPrice.div(
7894
- new (0, _decimaljs2.default)(__pow(10, tokenADecimal - tokenBDecimal))
9585
+ const minimumAmountOut = getAmountWithSlippage(
9586
+ actualAmountOut,
9587
+ slippage,
9588
+ 1 /* PartialFill */
7895
9589
  );
7896
- const sqrtValue = _decimaljs2.default.sqrt(adjustedByDecimals);
7897
- const sqrtValueQ64 = sqrtValue.mul(_decimaljs2.default.pow(2, 64));
7898
- return new (0, _anchor.BN)(sqrtValueQ64.floor().toFixed());
7899
- };
7900
- var getUnClaimReward = (poolState, positionState) => {
7901
- const totalPositionLiquidity = positionState.unlockedLiquidity.add(positionState.vestedLiquidity).add(positionState.permanentLockedLiquidity);
7902
- const feeAPerTokenStored = new (0, _anchor.BN)(
7903
- Buffer.from(poolState.feeAPerLiquidity).reverse()
7904
- ).sub(new (0, _anchor.BN)(Buffer.from(positionState.feeAPerTokenCheckpoint).reverse()));
7905
- const feeBPerTokenStored = new (0, _anchor.BN)(
7906
- Buffer.from(poolState.feeBPerLiquidity).reverse()
7907
- ).sub(new (0, _anchor.BN)(Buffer.from(positionState.feeBPerTokenCheckpoint).reverse()));
7908
- const feeA = totalPositionLiquidity.mul(feeAPerTokenStored).shrn(LIQUIDITY_SCALE);
7909
- const feeB = totalPositionLiquidity.mul(feeBPerTokenStored).shrn(LIQUIDITY_SCALE);
7910
- return {
7911
- feeTokenA: positionState.feeAPending.add(feeA),
7912
- feeTokenB: positionState.feeBPending.add(feeB),
7913
- rewards: positionState.rewardInfos.length > 0 ? positionState.rewardInfos.map((item) => item.rewardPendings) : []
7914
- };
7915
- };
7916
-
7917
- // src/helpers/accountFilters.ts
7918
- var positionByPoolFilter = (pool) => {
7919
- return {
7920
- memcmp: {
7921
- bytes: pool.toBase58(),
7922
- offset: 8
7923
- }
7924
- };
7925
- };
7926
- var vestingByPositionFilter = (position) => {
7927
- return {
7928
- memcmp: {
7929
- bytes: position.toBase58(),
7930
- offset: 8
7931
- }
7932
- };
7933
- };
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
+ }
7934
9603
 
7935
- // src/helpers/priceMath.ts
9604
+ // src/math/priceMath.ts
7936
9605
 
7937
9606
 
7938
9607
  function calculateInitSqrtPrice(tokenAAmount, tokenBAmount, minSqrtPrice, maxSqrtPrice) {
@@ -7959,127 +9628,330 @@ function calculateInitSqrtPrice(tokenAAmount, tokenBAmount, minSqrtPrice, maxSqr
7959
9628
  return new (0, _anchor.BN)(result.floor().toFixed());
7960
9629
  }
7961
9630
 
7962
- // src/helpers/token2022.ts
7963
-
7964
-
7965
-
7966
-
7967
-
7968
-
7969
-
7970
- function calculatePreFeeAmount(transferFee, postFeeAmount) {
7971
- if (postFeeAmount.isZero()) {
7972
- return new (0, _anchor.BN)(0);
9631
+ // src/helpers/validation.ts
9632
+ function validateFeeScheduler(numberOfPeriod, periodFrequency, reductionFactor, cliffFeeNumerator, baseFeeMode, poolVersion) {
9633
+ if (!periodFrequency.eq(new (0, _bnjs2.default)(0)) || numberOfPeriod !== 0 || !reductionFactor.eq(new (0, _bnjs2.default)(0))) {
9634
+ if (numberOfPeriod === 0 || periodFrequency.eq(new (0, _bnjs2.default)(0)) || reductionFactor.eq(new (0, _bnjs2.default)(0))) {
9635
+ return false;
9636
+ }
7973
9637
  }
7974
- if (transferFee.transferFeeBasisPoints === 0) {
7975
- 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 (0, _bnjs2.default)(FEE_DENOMINATOR));
9647
+ validateFeeFraction(maxFeeNumerator, new (0, _bnjs2.default)(FEE_DENOMINATOR));
9648
+ if (minFeeNumerator.lt(new (0, _bnjs2.default)(MIN_FEE_NUMERATOR)) || maxFeeNumerator.gt(getMaxFeeNumerator(poolVersion))) {
9649
+ throw new Error("PoolError::ExceedMaxFeeBps");
7976
9650
  }
7977
- const maximumFee = new (0, _anchor.BN)(transferFee.maximumFee.toString());
7978
- if (transferFee.transferFeeBasisPoints === _spltoken.MAX_FEE_BASIS_POINTS) {
7979
- 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;
7980
9656
  }
7981
- const ONE_IN_BASIS_POINTS = new (0, _anchor.BN)(_spltoken.MAX_FEE_BASIS_POINTS);
7982
- const numerator = postFeeAmount.mul(ONE_IN_BASIS_POINTS);
7983
- const denominator = ONE_IN_BASIS_POINTS.sub(
7984
- new (0, _anchor.BN)(transferFee.transferFeeBasisPoints)
9657
+ const maxFeeNumeratorFromBps = toNumerator(
9658
+ new (0, _bnjs2.default)(maxFeeBps),
9659
+ new (0, _bnjs2.default)(FEE_DENOMINATOR)
7985
9660
  );
7986
- const rawPreFeeAmount = numerator.add(denominator).sub(new (0, _anchor.BN)(1)).div(denominator);
7987
- if (rawPreFeeAmount.sub(postFeeAmount).gte(maximumFee)) {
7988
- return postFeeAmount.add(maximumFee);
9661
+ if (cliffFeeNumerator.lt(new (0, _bnjs2.default)(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 (0, _bnjs2.default)(MAX_RATE_LIMITER_DURATION_IN_SLOTS) : new (0, _bnjs2.default)(MAX_RATE_LIMITER_DURATION_IN_SECONDS);
9681
+ if (new (0, _bnjs2.default)(maxLimiterDuration).gt(maxLimiterDurationLimit)) {
9682
+ return false;
9683
+ }
9684
+ const feeIncrementNumerator = toNumerator(
9685
+ new (0, _bnjs2.default)(feeIncrementBps),
9686
+ new (0, _bnjs2.default)(FEE_DENOMINATOR)
9687
+ );
9688
+ if (feeIncrementNumerator.gte(new (0, _bnjs2.default)(FEE_DENOMINATOR))) {
9689
+ return false;
9690
+ }
9691
+ if (maxFeeBps > getMaxFeeBps(poolVersion)) {
9692
+ return false;
9693
+ }
9694
+ const minFeeNumerator = getFeeNumeratorFromIncludedFeeAmount(
9695
+ new (0, _bnjs2.default)(0),
9696
+ cliffFeeNumerator,
9697
+ referenceAmount,
9698
+ maxFeeBps,
9699
+ feeIncrementBps
9700
+ );
9701
+ const maxFeeNumeratorFromAmount = getFeeNumeratorFromIncludedFeeAmount(
9702
+ new (0, _bnjs2.default)(Number.MAX_SAFE_INTEGER),
9703
+ cliffFeeNumerator,
9704
+ referenceAmount,
9705
+ maxFeeBps,
9706
+ feeIncrementBps
9707
+ );
9708
+ if (minFeeNumerator.lt(new (0, _bnjs2.default)(MIN_FEE_NUMERATOR)) || maxFeeNumeratorFromAmount.gt(getMaxFeeNumerator(poolVersion))) {
9709
+ return false;
7989
9710
  }
7990
- return rawPreFeeAmount;
9711
+ return true;
7991
9712
  }
7992
- function calculateInverseFee(transferFee, postFeeAmount) {
7993
- const preFeeAmount = calculatePreFeeAmount(transferFee, postFeeAmount);
7994
- return new (0, _anchor.BN)(
7995
- _spltoken.calculateFee.call(void 0, 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
+
9723
+
9724
+
9725
+ function hasPartner(partner) {
9726
+ return !partner.equals(_web3js.PublicKey.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 (0, _bnjs2.default)(currentSlot);
9733
+ } else {
9734
+ const currentTime = yield connection.getBlockTime(currentSlot);
9735
+ return new (0, _bnjs2.default)(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 (0, _bnjs2.default)(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 (0, _bnjs2.default)(bps * FEE_DENOMINATOR).divn(BASIS_POINT_MAX);
9766
+ }
9767
+ function feeNumeratorToBps(feeNumerator) {
9768
+ return feeNumerator.muln(BASIS_POINT_MAX).div(new (0, _bnjs2.default)(FEE_DENOMINATOR)).toNumber();
9769
+ }
9770
+ function convertToLamports(amount, tokenDecimal) {
9771
+ const valueInLamports = new (0, _decimaljs2.default)(amount).mul(
9772
+ _decimaljs2.default.pow(10, tokenDecimal)
7996
9773
  );
9774
+ return fromDecimalToBN(valueInLamports);
7997
9775
  }
7998
- function calculateTransferFeeIncludedAmount(transferFeeExcludedAmount, mint, currentEpoch) {
7999
- if (transferFeeExcludedAmount.isZero()) {
9776
+ function fromDecimalToBN(value) {
9777
+ return new (0, _bnjs2.default)(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
+ }
8000
9784
  return {
8001
- amount: new (0, _anchor.BN)(0),
8002
- transferFee: new (0, _anchor.BN)(0)
9785
+ cliffFeeNumerator: bpsToFeeNumerator(startingBaseFeeBps),
9786
+ firstFactor: 0,
9787
+ secondFactor: Array.from(new (0, _bnjs2.default)(0).toArrayLike(Buffer, "le", 8)),
9788
+ thirdFactor: new (0, _bnjs2.default)(0),
9789
+ baseFeeMode: 0 /* FeeSchedulerLinear */
8003
9790
  };
8004
9791
  }
8005
- const transferFeeConfig = _spltoken.getTransferFeeConfig.call(void 0, mint);
8006
- if (transferFeeConfig === null) {
8007
- return {
8008
- amount: transferFeeExcludedAmount,
8009
- transferFee: new (0, _anchor.BN)(0)
8010
- };
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 (0, _bnjs2.default)(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 (0, _bnjs2.default)(BASIS_POINT_MAX * (1 - decayBase));
8011
9823
  }
8012
- const epochFee = _spltoken.getEpochFee.call(void 0, transferFeeConfig, BigInt(currentEpoch));
8013
- const transferFee = epochFee.transferFeeBasisPoints == _spltoken.MAX_FEE_BASIS_POINTS ? new (0, _anchor.BN)(epochFee.maximumFee.toString()) : calculateInverseFee(epochFee, transferFeeExcludedAmount);
8014
- const transferFeeIncludedAmount = transferFeeExcludedAmount.add(transferFee);
8015
9824
  return {
8016
- amount: transferFeeIncludedAmount,
8017
- transferFee
9825
+ cliffFeeNumerator: maxBaseFeeNumerator,
9826
+ firstFactor: numberOfPeriod,
9827
+ secondFactor,
9828
+ thirdFactor: reductionFactor,
9829
+ baseFeeMode
8018
9830
  };
8019
9831
  }
8020
- function calculateTransferFeeExcludedAmount(transferFeeIncludedAmount, mint, currentEpoch) {
8021
- const transferFeeConfig = _spltoken.getTransferFeeConfig.call(void 0, mint);
8022
- if (transferFeeConfig === null) {
8023
- return {
8024
- amount: transferFeeIncludedAmount,
8025
- transferFee: new (0, _anchor.BN)(0)
8026
- };
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
+ );
8027
9844
  }
8028
- const transferFeeIncludedAmountN = BigInt(
8029
- transferFeeIncludedAmount.toString()
8030
- );
8031
- const transferFee = _spltoken.calculateFee.call(void 0,
8032
- _spltoken.getEpochFee.call(void 0, transferFeeConfig, BigInt(currentEpoch)),
8033
- 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 (0, _bnjs2.default)(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 (0, _bnjs2.default)(poolMaxFeeNumerator).sub(cliffFeeNumerator);
9861
+ const maxIndex = deltaNumerator.div(feeIncrementNumerator);
9862
+ if (maxIndex.lt(new (0, _bnjs2.default)(1))) {
9863
+ throw new Error("Fee increment is too large for the given base fee");
9864
+ }
9865
+ if (cliffFeeNumerator.lt(new (0, _bnjs2.default)(MIN_FEE_NUMERATOR)) || cliffFeeNumerator.gt(new (0, _bnjs2.default)(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
8034
9877
  );
8035
- const transferFeeExcludedAmount = new (0, _anchor.BN)(
8036
- (transferFeeIncludedAmountN - transferFee).toString()
9878
+ const secondFactor = convertToRateLimiterSecondFactor(
9879
+ new (0, _bnjs2.default)(maxLimiterDuration),
9880
+ new (0, _bnjs2.default)(maxFeeBps)
8037
9881
  );
8038
9882
  return {
8039
- amount: transferFeeExcludedAmount,
8040
- transferFee: new (0, _anchor.BN)(transferFee.toString())
9883
+ cliffFeeNumerator,
9884
+ firstFactor: feeIncrementBps,
9885
+ secondFactor,
9886
+ thirdFactor: new (0, _bnjs2.default)(referenceAmountInLamports),
9887
+ baseFeeMode: 2 /* RateLimiter */
8041
9888
  };
8042
- }
8043
-
8044
- // src/helpers/vestings.ts
8045
-
8046
- var _bnjs = require('bn.js');
8047
- function isVestingComplete(vestingData, currentPoint) {
8048
- const cliffPoint = vestingData.cliffPoint;
8049
- const periodFrequency = vestingData.periodFrequency;
8050
- const numberOfPeriods = vestingData.numberOfPeriod;
8051
- const endPoint = cliffPoint.add(periodFrequency.muln(numberOfPeriods));
8052
- return currentPoint.gte(endPoint);
8053
- }
8054
- function getTotalLockedLiquidity(vestingData) {
8055
- return vestingData.cliffUnlockLiquidity.add(
8056
- vestingData.liquidityPerPeriod.mul(new (0, _anchor.BN)(vestingData.numberOfPeriod))
8057
- );
8058
- }
8059
- function getAvailableVestingLiquidity(vestingData, currentPoint) {
8060
- const {
8061
- cliffPoint,
8062
- periodFrequency,
8063
- cliffUnlockLiquidity,
8064
- liquidityPerPeriod,
8065
- numberOfPeriod,
8066
- totalReleasedLiquidity
8067
- } = vestingData;
8068
- if (currentPoint.lt(cliffPoint)) {
8069
- return new (0, _anchor.BN)(0);
9889
+ }
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
+ );
8070
9927
  }
8071
- if (periodFrequency.isZero()) {
8072
- 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
+ );
8073
9934
  }
8074
- let passedPeriod = new (0, _anchor.BN)(currentPoint).sub(cliffPoint).div(periodFrequency);
8075
- passedPeriod = _bnjs.min.call(void 0, passedPeriod, new (0, _anchor.BN)(numberOfPeriod));
8076
- const unlockedLiquidity = cliffUnlockLiquidity.add(
8077
- passedPeriod.mul(liquidityPerPeriod)
8078
- );
8079
- const availableReleasingLiquidity = unlockedLiquidity.sub(
8080
- totalReleasedLiquidity
9935
+ const priceRatio = maxPriceChangeBps / BASIS_POINT_MAX + 1;
9936
+ const sqrtPriceRatioQ64 = new (0, _bnjs2.default)(
9937
+ _decimaljs2.default.sqrt(priceRatio.toString()).mul(_decimaljs2.default.pow(2, 64)).floor().toFixed()
8081
9938
  );
8082
- return availableReleasingLiquidity;
9939
+ const deltaBinId = sqrtPriceRatioQ64.sub(ONE_Q64).div(BIN_STEP_BPS_U128_DEFAULT).muln(2);
9940
+ const maxVolatilityAccumulator = new (0, _bnjs2.default)(deltaBinId.muln(BASIS_POINT_MAX));
9941
+ const squareVfaBin = maxVolatilityAccumulator.mul(new (0, _bnjs2.default)(BIN_STEP_BPS_DEFAULT)).pow(new (0, _bnjs2.default)(2));
9942
+ const baseFeeNumerator = new (0, _bnjs2.default)(bpsToFeeNumerator(baseFeeBps));
9943
+ const maxDynamicFeeNumerator = baseFeeNumerator.muln(20).divn(100);
9944
+ const vFee = maxDynamicFeeNumerator.mul(new (0, _bnjs2.default)(1e11)).sub(new (0, _bnjs2.default)(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
+ };
8083
9955
  }
8084
9956
 
8085
9957
  // src/CpAmm.ts
@@ -8798,158 +10670,101 @@ var CpAmm = class {
8798
10670
  currentTime,
8799
10671
  currentSlot,
8800
10672
  inputTokenInfo,
8801
- outputTokenInfo
10673
+ outputTokenInfo,
10674
+ tokenADecimal,
10675
+ tokenBDecimal,
10676
+ hasReferral
8802
10677
  } = params;
8803
- const {
8804
- sqrtPrice: sqrtPriceQ64,
8805
- liquidity: liquidityQ64,
8806
- activationType,
8807
- activationPoint,
8808
- collectFeeMode,
8809
- poolFees
8810
- } = poolState;
8811
- const {
8812
- feeSchedulerMode,
8813
- cliffFeeNumerator,
8814
- numberOfPeriod,
8815
- reductionFactor,
8816
- periodFrequency
8817
- } = poolFees.baseFee;
8818
- const dynamicFee = poolFees.dynamicFee;
8819
- let actualAmountIn = inAmount;
8820
- if (inputTokenInfo) {
8821
- actualAmountIn = calculateTransferFeeExcludedAmount(
8822
- inAmount,
8823
- inputTokenInfo.mint,
8824
- inputTokenInfo.currentEpoch
8825
- ).amount;
8826
- }
10678
+ const { activationType } = poolState;
8827
10679
  const aToB = poolState.tokenAMint.equals(inputTokenMint);
8828
- const currentPoint = activationType ? currentTime : currentSlot;
8829
- let dynamicFeeParams;
8830
- if (dynamicFee.initialized) {
8831
- const { volatilityAccumulator, binStep, variableFeeControl } = dynamicFee;
8832
- dynamicFeeParams = { volatilityAccumulator, binStep, variableFeeControl };
8833
- }
8834
- const tradeFeeNumerator = getFeeNumerator(
10680
+ const currentPoint = activationType ? new (0, _bnjs2.default)(currentTime) : new (0, _bnjs2.default)(currentSlot);
10681
+ const swapResult = swapQuoteExactInput(
10682
+ poolState,
8835
10683
  currentPoint,
8836
- activationPoint,
8837
- numberOfPeriod,
8838
- periodFrequency,
8839
- feeSchedulerMode,
8840
- cliffFeeNumerator,
8841
- reductionFactor,
8842
- dynamicFeeParams
8843
- );
8844
- const { amountOut, totalFee, nextSqrtPrice } = getSwapAmount(
8845
- actualAmountIn,
8846
- sqrtPriceQ64,
8847
- liquidityQ64,
8848
- tradeFeeNumerator,
10684
+ inAmount,
10685
+ slippage,
8849
10686
  aToB,
8850
- collectFeeMode
8851
- );
8852
- let actualAmountOut = amountOut;
8853
- if (outputTokenInfo) {
8854
- actualAmountOut = calculateTransferFeeExcludedAmount(
8855
- amountOut,
8856
- outputTokenInfo.mint,
8857
- outputTokenInfo.currentEpoch
8858
- ).amount;
8859
- }
8860
- const minSwapOutAmount = getMinAmountWithSlippage(
8861
- actualAmountOut,
8862
- slippage
10687
+ hasReferral,
10688
+ tokenADecimal,
10689
+ tokenBDecimal,
10690
+ inputTokenInfo,
10691
+ outputTokenInfo
8863
10692
  );
8864
10693
  return {
8865
10694
  swapInAmount: inAmount,
8866
- consumedInAmount: actualAmountIn,
8867
- swapOutAmount: actualAmountOut,
8868
- minSwapOutAmount,
8869
- totalFee,
8870
- priceImpact: getPriceImpact(
8871
- actualAmountIn,
8872
- actualAmountOut,
8873
- sqrtPriceQ64,
8874
- aToB,
8875
- params.tokenADecimal,
8876
- params.tokenBDecimal
8877
- )
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
8878
10700
  };
8879
10701
  }
8880
- /**
8881
- * Calculates swap quote based on desired output amount and pool state.
8882
- * @param params - Swap parameters including output amount, pool state, slippage, etc.
8883
- * @returns Swap quote including required input amount, fees, and price impact.
8884
- */
8885
- getQuoteExactOut(params) {
10702
+ getQuote2(params) {
8886
10703
  const {
8887
- outAmount,
8888
- outputTokenMint,
10704
+ inputTokenMint,
8889
10705
  slippage,
8890
10706
  poolState,
8891
- currentTime,
8892
- currentSlot,
10707
+ currentPoint,
8893
10708
  inputTokenInfo,
8894
- outputTokenInfo
10709
+ outputTokenInfo,
10710
+ hasReferral,
10711
+ tokenADecimal,
10712
+ tokenBDecimal,
10713
+ swapMode
8895
10714
  } = params;
8896
- const {
8897
- sqrtPrice: sqrtPriceQ64,
8898
- activationType,
8899
- collectFeeMode,
8900
- poolFees
8901
- } = poolState;
8902
- const dynamicFee = poolFees.dynamicFee;
8903
- const bToA = poolState.tokenAMint.equals(outputTokenMint);
8904
- const tradeDirection = bToA ? 1 /* BtoA */ : 0 /* AtoB */;
8905
- const currentPoint = activationType ? currentTime : currentSlot;
8906
- let dynamicFeeParams;
8907
- if (dynamicFee.initialized) {
8908
- const { volatilityAccumulator, binStep, variableFeeControl } = dynamicFee;
8909
- dynamicFeeParams = { volatilityAccumulator, binStep, variableFeeControl };
8910
- }
8911
- let actualAmountOut = outAmount;
8912
- if (outputTokenInfo) {
8913
- actualAmountOut = calculateTransferFeeIncludedAmount(
8914
- outAmount,
8915
- outputTokenInfo.mint,
8916
- outputTokenInfo.currentEpoch
8917
- ).amount;
8918
- }
8919
- const feeMode = getFeeMode(collectFeeMode, bToA);
8920
- const { swapResult, inputAmount } = getSwapResultFromOutAmount(
8921
- poolState,
8922
- actualAmountOut,
8923
- feeMode,
8924
- tradeDirection,
8925
- currentPoint
8926
- );
8927
- let actualInputAmount = inputAmount;
8928
- if (inputTokenInfo) {
8929
- actualInputAmount = calculateTransferFeeIncludedAmount(
8930
- inputAmount,
8931
- inputTokenInfo.mint,
8932
- inputTokenInfo.currentEpoch
8933
- ).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}`);
8934
10767
  }
8935
- const maxInputAmount = new (0, _anchor.BN)(
8936
- Math.ceil(actualInputAmount.toNumber() * (1 + slippage / 100))
8937
- );
8938
- const priceImpact = getPriceImpact(
8939
- actualInputAmount,
8940
- actualAmountOut,
8941
- sqrtPriceQ64,
8942
- !bToA,
8943
- // aToB is the opposite of bToA
8944
- params.tokenADecimal,
8945
- params.tokenBDecimal
8946
- ).toNumber();
8947
- return {
8948
- swapResult,
8949
- inputAmount: actualInputAmount,
8950
- maxInputAmount,
8951
- priceImpact
8952
- };
8953
10768
  }
8954
10769
  /**
8955
10770
  * Calculates the deposit quote for liquidity pool.
@@ -9001,7 +10816,7 @@ var CpAmm = class {
9001
10816
  0 /* Up */
9002
10817
  )
9003
10818
  };
9004
- const rawOutputAmount = new (0, _anchor.BN)(rawAmount(liquidityDelta));
10819
+ const rawOutputAmount = new (0, _bnjs2.default)(rawAmount(liquidityDelta));
9005
10820
  const outputAmount = outputTokenInfo ? calculateTransferFeeIncludedAmount(
9006
10821
  rawOutputAmount,
9007
10822
  outputTokenInfo.mint,
@@ -9108,7 +10923,7 @@ var CpAmm = class {
9108
10923
  tokenAInfo,
9109
10924
  tokenBInfo
9110
10925
  } = params;
9111
- if (tokenAAmount.eq(new (0, _anchor.BN)(0)) && tokenBAmount.eq(new (0, _anchor.BN)(0))) {
10926
+ if (tokenAAmount.eq(new (0, _bnjs2.default)(0)) && tokenBAmount.eq(new (0, _bnjs2.default)(0))) {
9112
10927
  throw new Error("Invalid input amount");
9113
10928
  }
9114
10929
  const actualAmountAIn = tokenAInfo ? tokenAAmount.sub(
@@ -9275,7 +11090,7 @@ var CpAmm = class {
9275
11090
  tokenAMint,
9276
11091
  tokenBMint,
9277
11092
  tokenAAmount,
9278
- tokenBAmount: tokenBMint.equals(_spltoken.NATIVE_MINT) ? _bnjs.max.call(void 0, tokenBAmount, new (0, _anchor.BN)(1)) : tokenBAmount,
11093
+ tokenBAmount: tokenBMint.equals(_spltoken.NATIVE_MINT) ? _bnjs.max.call(void 0, tokenBAmount, new (0, _bnjs2.default)(1)) : tokenBAmount,
9279
11094
  payer,
9280
11095
  positionNft,
9281
11096
  tokenAProgram,
@@ -9787,6 +11602,7 @@ var CpAmm = class {
9787
11602
  const [inputTokenProgram, outputTokenProgram] = inputTokenMint.equals(
9788
11603
  tokenAMint
9789
11604
  ) ? [tokenAProgram, tokenBProgram] : [tokenBProgram, tokenAProgram];
11605
+ const tradeDirection = inputTokenMint.equals(tokenAMint) ? 0 /* AtoB */ : 1 /* BtoA */;
9790
11606
  const {
9791
11607
  tokenAAta: inputTokenAccount,
9792
11608
  tokenBAta: outputTokenAccount,
@@ -9815,6 +11631,30 @@ var CpAmm = class {
9815
11631
  const closeWrappedSOLIx = yield unwrapSOLInstruction(payer);
9816
11632
  closeWrappedSOLIx && postInstructions.push(closeWrappedSOLIx);
9817
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: _web3js.SYSVAR_INSTRUCTIONS_PUBKEY
11656
+ }
11657
+ ] : [];
9818
11658
  return yield this._program.methods.swap({
9819
11659
  amountIn,
9820
11660
  minimumAmountOut
@@ -9831,7 +11671,109 @@ var CpAmm = class {
9831
11671
  tokenAProgram,
9832
11672
  tokenBProgram,
9833
11673
  referralTokenAccount
9834
- }).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(_spltoken.NATIVE_MINT)) {
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
+ _spltoken.NATIVE_MINT.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: _web3js.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();
9835
11777
  });
9836
11778
  }
9837
11779
  /**
@@ -10065,7 +12007,7 @@ var CpAmm = class {
10065
12007
  );
10066
12008
  return total.add(available);
10067
12009
  },
10068
- new (0, _anchor.BN)(0)
12010
+ new (0, _bnjs2.default)(0)
10069
12011
  );
10070
12012
  positionBLiquidityDelta = positionBLiquidityDelta.add(
10071
12013
  totalAvailableVestingLiquidity
@@ -10512,6 +12454,29 @@ var CpAmm = class {
10512
12454
  }).transaction();
10513
12455
  });
10514
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
+ }
10515
12480
  };
10516
12481
 
10517
12482
  // src/index.ts
@@ -10603,5 +12568,76 @@ var index_default = cp_amm_default;
10603
12568
 
10604
12569
 
10605
12570
 
10606
- exports.ActivationPoint = ActivationPoint; exports.ActivationType = ActivationType; exports.BASIS_POINT_MAX = BASIS_POINT_MAX; exports.BIN_STEP_BPS_DEFAULT = BIN_STEP_BPS_DEFAULT; exports.BIN_STEP_BPS_U128_DEFAULT = BIN_STEP_BPS_U128_DEFAULT; exports.CP_AMM_PROGRAM_ID = CP_AMM_PROGRAM_ID; exports.CollectFeeMode = CollectFeeMode; exports.CpAmm = CpAmm; exports.DYNAMIC_FEE_DECAY_PERIOD_DEFAULT = DYNAMIC_FEE_DECAY_PERIOD_DEFAULT; exports.DYNAMIC_FEE_FILTER_PERIOD_DEFAULT = DYNAMIC_FEE_FILTER_PERIOD_DEFAULT; exports.DYNAMIC_FEE_REDUCTION_FACTOR_DEFAULT = DYNAMIC_FEE_REDUCTION_FACTOR_DEFAULT; exports.FEE_DENOMINATOR = FEE_DENOMINATOR; exports.FeeSchedulerMode = FeeSchedulerMode; exports.LIQUIDITY_SCALE = LIQUIDITY_SCALE; exports.MAX_CU_BUFFER = MAX_CU_BUFFER; exports.MAX_FEE_NUMERATOR = MAX_FEE_NUMERATOR; exports.MAX_PRICE_CHANGE_BPS_DEFAULT = MAX_PRICE_CHANGE_BPS_DEFAULT; exports.MAX_SQRT_PRICE = MAX_SQRT_PRICE; exports.MIN_CU_BUFFER = MIN_CU_BUFFER; exports.MIN_SQRT_PRICE = MIN_SQRT_PRICE; exports.ONE = ONE; exports.Rounding = Rounding; exports.SCALE_OFFSET = SCALE_OFFSET; exports.TradeDirection = TradeDirection; exports.bpsToFeeNumerator = bpsToFeeNumerator; exports.calculateInitSqrtPrice = calculateInitSqrtPrice; exports.calculateTransferFeeExcludedAmount = calculateTransferFeeExcludedAmount; exports.calculateTransferFeeIncludedAmount = calculateTransferFeeIncludedAmount; exports.decimalToQ64 = decimalToQ64; exports.default = index_default; exports.deriveClaimFeeOperatorAddress = deriveClaimFeeOperatorAddress; exports.deriveConfigAddress = deriveConfigAddress; exports.deriveCustomizablePoolAddress = deriveCustomizablePoolAddress; exports.derivePoolAddress = derivePoolAddress; exports.derivePoolAuthority = derivePoolAuthority; exports.derivePositionAddress = derivePositionAddress; exports.derivePositionNftAccount = derivePositionNftAccount; exports.deriveRewardVaultAddress = deriveRewardVaultAddress; exports.deriveTokenBadgeAddress = deriveTokenBadgeAddress; exports.deriveTokenVaultAddress = deriveTokenVaultAddress; exports.feeNumeratorToBps = feeNumeratorToBps; exports.getAllPositionNftAccountByOwner = getAllPositionNftAccountByOwner; exports.getAllUserPositionNftAccount = getAllUserPositionNftAccount; exports.getAmountAFromLiquidityDelta = getAmountAFromLiquidityDelta; exports.getAmountBFromLiquidityDelta = getAmountBFromLiquidityDelta; exports.getAvailableVestingLiquidity = getAvailableVestingLiquidity; exports.getBaseFeeNumerator = getBaseFeeNumerator; exports.getBaseFeeParams = getBaseFeeParams; exports.getDynamicFeeNumerator = getDynamicFeeNumerator; exports.getDynamicFeeParams = getDynamicFeeParams; exports.getEstimatedComputeUnitIxWithBuffer = getEstimatedComputeUnitIxWithBuffer; exports.getEstimatedComputeUnitUsageWithBuffer = getEstimatedComputeUnitUsageWithBuffer; exports.getExcludedFeeAmount = getExcludedFeeAmount; exports.getFeeMode = getFeeMode; exports.getFeeNumerator = getFeeNumerator; exports.getFirstKey = getFirstKey; exports.getIncludedFeeAmount = getIncludedFeeAmount; exports.getLiquidityDeltaFromAmountA = getLiquidityDeltaFromAmountA; exports.getLiquidityDeltaFromAmountB = getLiquidityDeltaFromAmountB; exports.getMaxAmountWithSlippage = getMaxAmountWithSlippage; exports.getMinAmountWithSlippage = getMinAmountWithSlippage; exports.getNextSqrtPrice = getNextSqrtPrice; exports.getNextSqrtPriceFromAmountARoundingDown = getNextSqrtPriceFromAmountARoundingDown; exports.getNextSqrtPriceFromAmountBRoundingUp = getNextSqrtPriceFromAmountBRoundingUp; exports.getNextSqrtPriceFromOutput = getNextSqrtPriceFromOutput; exports.getOrCreateATAInstruction = getOrCreateATAInstruction; exports.getPriceChange = getPriceChange; exports.getPriceFromSqrtPrice = getPriceFromSqrtPrice; exports.getPriceImpact = getPriceImpact; exports.getSecondKey = getSecondKey; exports.getSimulationComputeUnits = getSimulationComputeUnits; exports.getSqrtPriceFromPrice = getSqrtPriceFromPrice; exports.getSwapAmount = getSwapAmount; exports.getSwapResultFromOutAmount = getSwapResultFromOutAmount; exports.getTokenDecimals = getTokenDecimals; exports.getTokenProgram = getTokenProgram; exports.getTotalLockedLiquidity = getTotalLockedLiquidity; exports.getUnClaimReward = getUnClaimReward; exports.isVestingComplete = isVestingComplete; exports.mulDiv = mulDiv; exports.positionByPoolFilter = positionByPoolFilter; exports.pow = pow; exports.q64ToDecimal = q64ToDecimal; exports.unwrapSOLInstruction = unwrapSOLInstruction; exports.vestingByPositionFilter = vestingByPositionFilter; exports.wrapSOLInstruction = wrapSOLInstruction;
12571
+
12572
+
12573
+
12574
+
12575
+
12576
+
12577
+
12578
+
12579
+
12580
+
12581
+
12582
+
12583
+
12584
+
12585
+
12586
+
12587
+
12588
+
12589
+
12590
+
12591
+
12592
+
12593
+
12594
+
12595
+
12596
+
12597
+
12598
+
12599
+
12600
+
12601
+
12602
+
12603
+
12604
+
12605
+
12606
+
12607
+
12608
+
12609
+
12610
+
12611
+
12612
+
12613
+
12614
+
12615
+
12616
+
12617
+
12618
+
12619
+
12620
+
12621
+
12622
+
12623
+
12624
+
12625
+
12626
+
12627
+
12628
+
12629
+
12630
+
12631
+
12632
+
12633
+
12634
+
12635
+
12636
+
12637
+
12638
+
12639
+
12640
+
12641
+
12642
+ exports.ActivationPoint = ActivationPoint; exports.ActivationType = ActivationType; exports.BASIS_POINT_MAX = BASIS_POINT_MAX; exports.BIN_STEP_BPS_DEFAULT = BIN_STEP_BPS_DEFAULT; exports.BIN_STEP_BPS_U128_DEFAULT = BIN_STEP_BPS_U128_DEFAULT; exports.BaseFeeMode = BaseFeeMode; exports.CP_AMM_PROGRAM_ID = CP_AMM_PROGRAM_ID; exports.CURRENT_POOL_VERSION = CURRENT_POOL_VERSION; exports.CollectFeeMode = CollectFeeMode; exports.CpAmm = CpAmm; exports.DYNAMIC_FEE_DECAY_PERIOD_DEFAULT = DYNAMIC_FEE_DECAY_PERIOD_DEFAULT; exports.DYNAMIC_FEE_FILTER_PERIOD_DEFAULT = DYNAMIC_FEE_FILTER_PERIOD_DEFAULT; exports.DYNAMIC_FEE_REDUCTION_FACTOR_DEFAULT = DYNAMIC_FEE_REDUCTION_FACTOR_DEFAULT; exports.DYNAMIC_FEE_ROUNDING_OFFSET = DYNAMIC_FEE_ROUNDING_OFFSET; exports.DYNAMIC_FEE_SCALING_FACTOR = DYNAMIC_FEE_SCALING_FACTOR; exports.FEE_DENOMINATOR = FEE_DENOMINATOR; exports.FeeRateLimiter = FeeRateLimiter; exports.FeeScheduler = FeeScheduler; exports.LIQUIDITY_SCALE = LIQUIDITY_SCALE; exports.MAX = MAX; exports.MAX_CU_BUFFER = MAX_CU_BUFFER; exports.MAX_EXPONENTIAL = MAX_EXPONENTIAL; exports.MAX_FEE_BPS_V0 = MAX_FEE_BPS_V0; exports.MAX_FEE_BPS_V1 = MAX_FEE_BPS_V1; exports.MAX_FEE_NUMERATOR_V0 = MAX_FEE_NUMERATOR_V0; exports.MAX_FEE_NUMERATOR_V1 = MAX_FEE_NUMERATOR_V1; exports.MAX_PRICE_CHANGE_BPS_DEFAULT = MAX_PRICE_CHANGE_BPS_DEFAULT; exports.MAX_RATE_LIMITER_DURATION_IN_SECONDS = MAX_RATE_LIMITER_DURATION_IN_SECONDS; exports.MAX_RATE_LIMITER_DURATION_IN_SLOTS = MAX_RATE_LIMITER_DURATION_IN_SLOTS; exports.MAX_SQRT_PRICE = MAX_SQRT_PRICE; exports.MIN_CU_BUFFER = MIN_CU_BUFFER; exports.MIN_FEE_BPS = MIN_FEE_BPS; exports.MIN_FEE_NUMERATOR = MIN_FEE_NUMERATOR; exports.MIN_SQRT_PRICE = MIN_SQRT_PRICE; exports.ONE_Q64 = ONE_Q64; exports.PoolStatus = PoolStatus; exports.PoolVersion = PoolVersion; exports.Rounding = Rounding; exports.SCALE_OFFSET = SCALE_OFFSET; exports.SPLIT_POSITION_DENOMINATOR = SPLIT_POSITION_DENOMINATOR; exports.SwapMode = SwapMode; exports.TradeDirection = TradeDirection; exports.U128_MAX = U128_MAX; exports.U16_MAX = U16_MAX; exports.U64_MAX = U64_MAX; exports.bpsToFeeNumerator = bpsToFeeNumerator; exports.calculateAtoBFromAmountIn = calculateAtoBFromAmountIn; exports.calculateAtoBFromAmountOut = calculateAtoBFromAmountOut; exports.calculateAtoBFromPartialAmountIn = calculateAtoBFromPartialAmountIn; exports.calculateBtoAFromAmountIn = calculateBtoAFromAmountIn; exports.calculateBtoAFromAmountOut = calculateBtoAFromAmountOut; exports.calculateBtoAFromPartialAmountIn = calculateBtoAFromPartialAmountIn; exports.calculateInitSqrtPrice = calculateInitSqrtPrice; exports.calculateTransferFeeExcludedAmount = calculateTransferFeeExcludedAmount; exports.calculateTransferFeeIncludedAmount = calculateTransferFeeIncludedAmount; exports.convertToFeeSchedulerSecondFactor = convertToFeeSchedulerSecondFactor; exports.convertToLamports = convertToLamports; exports.convertToRateLimiterSecondFactor = convertToRateLimiterSecondFactor; exports.decimalToQ64 = decimalToQ64; exports.default = index_default; exports.deriveClaimFeeOperatorAddress = deriveClaimFeeOperatorAddress; exports.deriveConfigAddress = deriveConfigAddress; exports.deriveCustomizablePoolAddress = deriveCustomizablePoolAddress; exports.derivePoolAddress = derivePoolAddress; exports.derivePoolAuthority = derivePoolAuthority; exports.derivePositionAddress = derivePositionAddress; exports.derivePositionNftAccount = derivePositionNftAccount; exports.deriveRewardVaultAddress = deriveRewardVaultAddress; exports.deriveTokenBadgeAddress = deriveTokenBadgeAddress; exports.deriveTokenVaultAddress = deriveTokenVaultAddress; exports.feeNumeratorToBps = feeNumeratorToBps; exports.fromDecimalToBN = fromDecimalToBN; exports.getAllPositionNftAccountByOwner = getAllPositionNftAccountByOwner; exports.getAllUserPositionNftAccount = getAllUserPositionNftAccount; exports.getAmountAFromLiquidityDelta = getAmountAFromLiquidityDelta; exports.getAmountBFromLiquidityDelta = getAmountBFromLiquidityDelta; exports.getAmountWithSlippage = getAmountWithSlippage; exports.getAvailableVestingLiquidity = getAvailableVestingLiquidity; exports.getBaseFeeHandler = getBaseFeeHandler; exports.getBaseFeeNumerator = getBaseFeeNumerator; exports.getBaseFeeNumeratorByPeriod = getBaseFeeNumeratorByPeriod; exports.getBaseFeeParams = getBaseFeeParams; exports.getCheckedAmounts = getCheckedAmounts; exports.getCurrentPoint = getCurrentPoint; exports.getDynamicFeeNumerator = getDynamicFeeNumerator; exports.getDynamicFeeParams = getDynamicFeeParams; exports.getEstimatedComputeUnitIxWithBuffer = getEstimatedComputeUnitIxWithBuffer; exports.getEstimatedComputeUnitUsageWithBuffer = getEstimatedComputeUnitUsageWithBuffer; exports.getExcludedFeeAmount = getExcludedFeeAmount; exports.getExcludedFeeAmountFromIncludedFeeAmount = getExcludedFeeAmountFromIncludedFeeAmount; exports.getFeeInPeriod = getFeeInPeriod; exports.getFeeMode = getFeeMode; exports.getFeeNumeratorFromExcludedFeeAmount = getFeeNumeratorFromExcludedFeeAmount; exports.getFeeNumeratorFromIncludedFeeAmount = getFeeNumeratorFromIncludedFeeAmount; exports.getFeeNumeratorOnExponentialFeeScheduler = getFeeNumeratorOnExponentialFeeScheduler; exports.getFeeNumeratorOnLinearFeeScheduler = getFeeNumeratorOnLinearFeeScheduler; exports.getFeeOnAmount = getFeeOnAmount; exports.getFeeSchedulerParams = getFeeSchedulerParams; exports.getFirstKey = getFirstKey; exports.getIncludedFeeAmount = getIncludedFeeAmount; exports.getLiquidityDeltaFromAmountA = getLiquidityDeltaFromAmountA; exports.getLiquidityDeltaFromAmountB = getLiquidityDeltaFromAmountB; exports.getMaxAmountWithSlippage = getMaxAmountWithSlippage; exports.getMaxBaseFeeNumerator = getMaxBaseFeeNumerator; exports.getMaxFeeBps = getMaxFeeBps; exports.getMaxFeeNumerator = getMaxFeeNumerator; exports.getMaxIndex = getMaxIndex; exports.getMinBaseFeeNumerator = getMinBaseFeeNumerator; exports.getNextSqrtPriceFromAmountInARoundingUp = getNextSqrtPriceFromAmountInARoundingUp; exports.getNextSqrtPriceFromAmountInBRoundingDown = getNextSqrtPriceFromAmountInBRoundingDown; exports.getNextSqrtPriceFromAmountOutARoundingUp = getNextSqrtPriceFromAmountOutARoundingUp; exports.getNextSqrtPriceFromAmountOutBRoundingDown = getNextSqrtPriceFromAmountOutBRoundingDown; exports.getNextSqrtPriceFromInput = getNextSqrtPriceFromInput; exports.getNextSqrtPriceFromOutput = getNextSqrtPriceFromOutput; exports.getOrCreateATAInstruction = getOrCreateATAInstruction; exports.getPriceChange = getPriceChange; exports.getPriceFromSqrtPrice = getPriceFromSqrtPrice; exports.getPriceImpact = getPriceImpact; exports.getRateLimiterParams = getRateLimiterParams; exports.getSecondKey = getSecondKey; exports.getSimulationComputeUnits = getSimulationComputeUnits; exports.getSqrtPriceFromPrice = getSqrtPriceFromPrice; exports.getSwapResultFromExactInput = getSwapResultFromExactInput; exports.getSwapResultFromExactOutput = getSwapResultFromExactOutput; exports.getSwapResultFromPartialInput = getSwapResultFromPartialInput; exports.getTokenDecimals = getTokenDecimals; exports.getTokenProgram = getTokenProgram; exports.getTotalFeeNumerator = getTotalFeeNumerator; exports.getTotalLockedLiquidity = getTotalLockedLiquidity; exports.getTotalTradingFeeFromExcludedFeeAmount = getTotalTradingFeeFromExcludedFeeAmount; exports.getTotalTradingFeeFromIncludedFeeAmount = getTotalTradingFeeFromIncludedFeeAmount; exports.getUnClaimReward = getUnClaimReward; exports.hasPartner = hasPartner; exports.isDynamicFeeEnabled = isDynamicFeeEnabled; exports.isNonZeroRateLimiter = isNonZeroRateLimiter; exports.isRateLimiterApplied = isRateLimiterApplied; exports.isSwapEnabled = isSwapEnabled; exports.isVestingComplete = isVestingComplete; exports.isZeroRateLimiter = isZeroRateLimiter; exports.mulDiv = mulDiv; exports.parseFeeSchedulerSecondFactor = parseFeeSchedulerSecondFactor; exports.parseRateLimiterSecondFactor = parseRateLimiterSecondFactor; exports.positionByPoolFilter = positionByPoolFilter; exports.pow = pow; exports.q64ToDecimal = q64ToDecimal; exports.splitFees = splitFees; exports.sqrt = sqrt; exports.swapQuoteExactInput = swapQuoteExactInput; exports.swapQuoteExactOutput = swapQuoteExactOutput; exports.swapQuotePartialInput = swapQuotePartialInput; exports.toNumerator = toNumerator; exports.unwrapSOLInstruction = unwrapSOLInstruction; exports.validateFeeFraction = validateFeeFraction; exports.validateFeeRateLimiter = validateFeeRateLimiter; exports.validateFeeScheduler = validateFeeScheduler; exports.vestingByPositionFilter = vestingByPositionFilter; exports.wrapSOLInstruction = wrapSOLInstruction;
10607
12643
  //# sourceMappingURL=index.js.map