From 407c6e76152510578406a0ecfa5ad5957b3b4ec2 Mon Sep 17 00:00:00 2001 From: angadsingh Date: Fri, 17 Oct 2025 18:13:17 +0100 Subject: [PATCH 1/2] makeSwapV2Instructions fn --- sdk/idl/stabble_clmm.json | 1261 ++--------------- .../instructions/decreaseLiquidity.ts | 391 ----- .../instructions/increaseLiquidity.ts | 385 ----- sdk/src/generated/instructions/index.ts | 5 - .../generated/instructions/openPosition.ts | 882 ------------ .../generated/instructions/openPositionV2.ts | 982 ------------- sdk/src/generated/instructions/swap.ts | 363 ----- sdk/src/generated/programs/ammV3.ts | 80 -- .../types/createPersonalPositionEvent.ts | 12 + sdk/src/generated/types/poolCreatedEvent.ts | 6 + sdk/src/swap.ts | 687 ++++----- tsconfig.json | 1 - 12 files changed, 437 insertions(+), 4618 deletions(-) delete mode 100644 sdk/src/generated/instructions/decreaseLiquidity.ts delete mode 100644 sdk/src/generated/instructions/increaseLiquidity.ts delete mode 100644 sdk/src/generated/instructions/openPosition.ts delete mode 100644 sdk/src/generated/instructions/openPositionV2.ts delete mode 100644 sdk/src/generated/instructions/swap.ts diff --git a/sdk/idl/stabble_clmm.json b/sdk/idl/stabble_clmm.json index c0dc45e..7428383 100644 --- a/sdk/idl/stabble_clmm.json +++ b/sdk/idl/stabble_clmm.json @@ -911,123 +911,6 @@ ], "args": [] }, - { - "name": "decrease_liquidity", - "docs": [ - "#[deprecated(note = \"Use `decrease_liquidity_v2` instead.\")]", - "Decreases liquidity for an existing position", - "", - "# Arguments", - "", - "* `ctx` - The context of accounts", - "* `liquidity` - The amount by which liquidity will be decreased", - "* `amount_0_min` - The minimum amount of token_0 that should be accounted for the burned liquidity", - "* `amount_1_min` - The minimum amount of token_1 that should be accounted for the burned liquidity", - "" - ], - "discriminator": [ - 160, - 38, - 208, - 111, - 104, - 91, - 44, - 1 - ], - "accounts": [ - { - "name": "nft_owner", - "docs": [ - "The position owner or delegated authority" - ], - "signer": true - }, - { - "name": "nft_account", - "docs": [ - "The token account for the tokenized position" - ] - }, - { - "name": "personal_position", - "docs": [ - "Decrease liquidity for this position" - ], - "writable": true - }, - { - "name": "pool_state", - "writable": true - }, - { - "name": "protocol_position" - }, - { - "name": "token_vault_0", - "docs": [ - "Token_0 vault" - ], - "writable": true - }, - { - "name": "token_vault_1", - "docs": [ - "Token_1 vault" - ], - "writable": true - }, - { - "name": "tick_array_lower", - "docs": [ - "Stores init state for the lower tick" - ], - "writable": true - }, - { - "name": "tick_array_upper", - "docs": [ - "Stores init state for the upper tick" - ], - "writable": true - }, - { - "name": "recipient_token_account_0", - "docs": [ - "The destination token account for receive amount_0" - ], - "writable": true - }, - { - "name": "recipient_token_account_1", - "docs": [ - "The destination token account for receive amount_1" - ], - "writable": true - }, - { - "name": "token_program", - "docs": [ - "SPL program to transfer out tokens" - ], - "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" - } - ], - "args": [ - { - "name": "liquidity", - "type": "u128" - }, - { - "name": "amount_0_min", - "type": "u64" - }, - { - "name": "amount_1_min", - "type": "u64" - } - ] - }, { "name": "decrease_liquidity_v2", "docs": [ @@ -1170,123 +1053,6 @@ } ] }, - { - "name": "increase_liquidity", - "docs": [ - "#[deprecated(note = \"Use `increase_liquidity_v2` instead.\")]", - "Increases liquidity for an existing position, with amount paid by `payer`", - "", - "# Arguments", - "", - "* `ctx` - The context of accounts", - "* `liquidity` - The desired liquidity to be added, can't be zero", - "* `amount_0_max` - The max amount of token_0 to spend, which serves as a slippage check", - "* `amount_1_max` - The max amount of token_1 to spend, which serves as a slippage check", - "" - ], - "discriminator": [ - 46, - 156, - 243, - 118, - 13, - 205, - 251, - 178 - ], - "accounts": [ - { - "name": "nft_owner", - "docs": [ - "Pays to mint the position" - ], - "signer": true - }, - { - "name": "nft_account", - "docs": [ - "The token account for nft" - ] - }, - { - "name": "pool_state", - "writable": true - }, - { - "name": "protocol_position" - }, - { - "name": "personal_position", - "docs": [ - "Increase liquidity for this position" - ], - "writable": true - }, - { - "name": "tick_array_lower", - "docs": [ - "Stores init state for the lower tick" - ], - "writable": true - }, - { - "name": "tick_array_upper", - "docs": [ - "Stores init state for the upper tick" - ], - "writable": true - }, - { - "name": "token_account_0", - "docs": [ - "The payer's token account for token_0" - ], - "writable": true - }, - { - "name": "token_account_1", - "docs": [ - "The token account spending token_1 to mint the position" - ], - "writable": true - }, - { - "name": "token_vault_0", - "docs": [ - "The address that holds pool tokens for token_0" - ], - "writable": true - }, - { - "name": "token_vault_1", - "docs": [ - "The address that holds pool tokens for token_1" - ], - "writable": true - }, - { - "name": "token_program", - "docs": [ - "Program to create mint account and mint tokens" - ], - "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" - } - ], - "args": [ - { - "name": "liquidity", - "type": "u128" - }, - { - "name": "amount_0_max", - "type": "u64" - }, - { - "name": "amount_1_max", - "type": "u64" - } - ] - }, { "name": "increase_liquidity_v2", "docs": [ @@ -1450,840 +1216,122 @@ 196, 242, 129, - 230, - 68 - ], - "accounts": [ - { - "name": "reward_funder", - "docs": [ - "The founder deposit reward token to vault" - ], - "writable": true, - "signer": true - }, - { - "name": "funder_token_account", - "writable": true - }, - { - "name": "amm_config", - "docs": [ - "For check the reward_funder authority" - ] - }, - { - "name": "pool_state", - "docs": [ - "Set reward for this pool" - ], - "writable": true - }, - { - "name": "operation_state", - "docs": [ - "load info from the account to judge reward permission" - ], - "pda": { - "seeds": [ - { - "kind": "const", - "value": [ - 111, - 112, - 101, - 114, - 97, - 116, - 105, - 111, - 110 - ] - } - ] - } - }, - { - "name": "reward_token_mint", - "docs": [ - "Reward mint" - ] - }, - { - "name": "reward_token_vault", - "writable": true, - "pda": { - "seeds": [ - { - "kind": "const", - "value": [ - 112, - 111, - 111, - 108, - 95, - 114, - 101, - 119, - 97, - 114, - 100, - 95, - 118, - 97, - 117, - 108, - 116 - ] - }, - { - "kind": "account", - "path": "pool_state" - }, - { - "kind": "account", - "path": "reward_token_mint" - } - ] - } - }, - { - "name": "reward_token_program" - }, - { - "name": "system_program", - "address": "11111111111111111111111111111111" - }, - { - "name": "rent", - "address": "SysvarRent111111111111111111111111111111111" - } - ], - "args": [ - { - "name": "param", - "type": { - "defined": { - "name": "InitializeRewardParam" - } - } - } - ] - }, - { - "name": "open_position", - "docs": [ - "#[deprecated(note = \"Use `open_position_with_token22_nft` instead.\")]", - "Creates a new position wrapped in a NFT", - "", - "# Arguments", - "", - "* `ctx` - The context of accounts", - "* `tick_lower_index` - The low boundary of market", - "* `tick_upper_index` - The upper boundary of market", - "* `tick_array_lower_start_index` - The start index of tick array which include tick low", - "* `tick_array_upper_start_index` - The start index of tick array which include tick upper", - "* `liquidity` - The liquidity to be added", - "* `amount_0_max` - The max amount of token_0 to spend, which serves as a slippage check", - "* `amount_1_max` - The max amount of token_1 to spend, which serves as a slippage check", - "" - ], - "discriminator": [ - 135, - 128, - 47, - 77, - 15, - 152, - 240, - 49 - ], - "accounts": [ - { - "name": "payer", - "docs": [ - "Pays to mint the position" - ], - "writable": true, - "signer": true - }, - { - "name": "position_nft_owner" - }, - { - "name": "position_nft_mint", - "docs": [ - "Unique token mint address" - ], - "writable": true, - "signer": true - }, - { - "name": "position_nft_account", - "docs": [ - "Token account where position NFT will be minted", - "This account created in the contract by cpi to avoid large stack variables" - ], - "writable": true, - "pda": { - "seeds": [ - { - "kind": "account", - "path": "position_nft_owner" - }, - { - "kind": "const", - "value": [ - 6, - 221, - 246, - 225, - 215, - 101, - 161, - 147, - 217, - 203, - 225, - 70, - 206, - 235, - 121, - 172, - 28, - 180, - 133, - 237, - 95, - 91, - 55, - 145, - 58, - 140, - 245, - 133, - 126, - 255, - 0, - 169 - ] - }, - { - "kind": "account", - "path": "position_nft_mint" - } - ], - "program": { - "kind": "const", - "value": [ - 140, - 151, - 37, - 143, - 78, - 36, - 137, - 241, - 187, - 61, - 16, - 41, - 20, - 142, - 13, - 131, - 11, - 90, - 19, - 153, - 218, - 255, - 16, - 132, - 4, - 142, - 123, - 216, - 219, - 233, - 248, - 89 - ] - } - } - }, - { - "name": "metadata_account", - "docs": [ - "To store metaplex metadata" - ], - "writable": true - }, - { - "name": "pool_state", - "docs": [ - "Add liquidity for this pool" - ], - "writable": true - }, - { - "name": "protocol_position" - }, - { - "name": "tick_array_lower", - "writable": true, - "pda": { - "seeds": [ - { - "kind": "const", - "value": [ - 116, - 105, - 99, - 107, - 95, - 97, - 114, - 114, - 97, - 121 - ] - }, - { - "kind": "account", - "path": "pool_state" - }, - { - "kind": "arg", - "path": "tick_array_lower_start_index" - } - ] - } - }, - { - "name": "tick_array_upper", - "writable": true, - "pda": { - "seeds": [ - { - "kind": "const", - "value": [ - 116, - 105, - 99, - 107, - 95, - 97, - 114, - 114, - 97, - 121 - ] - }, - { - "kind": "account", - "path": "pool_state" - }, - { - "kind": "arg", - "path": "tick_array_upper_start_index" - } - ] - } - }, - { - "name": "personal_position", - "docs": [ - "personal position state" - ], - "writable": true, - "pda": { - "seeds": [ - { - "kind": "const", - "value": [ - 112, - 111, - 115, - 105, - 116, - 105, - 111, - 110 - ] - }, - { - "kind": "account", - "path": "position_nft_mint" - } - ] - } - }, - { - "name": "token_account_0", - "docs": [ - "The token_0 account deposit token to the pool" - ], - "writable": true - }, - { - "name": "token_account_1", - "docs": [ - "The token_1 account deposit token to the pool" - ], - "writable": true - }, - { - "name": "token_vault_0", - "docs": [ - "The address that holds pool tokens for token_0" - ], - "writable": true - }, - { - "name": "token_vault_1", - "docs": [ - "The address that holds pool tokens for token_1" - ], - "writable": true - }, - { - "name": "rent", - "docs": [ - "Sysvar for token mint and ATA creation" - ], - "address": "SysvarRent111111111111111111111111111111111" - }, - { - "name": "system_program", - "docs": [ - "Program to create the position manager state account" - ], - "address": "11111111111111111111111111111111" - }, - { - "name": "token_program", - "docs": [ - "Program to create mint account and mint tokens" - ], - "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" - }, - { - "name": "associated_token_program", - "docs": [ - "Program to create an ATA for receiving position NFT" - ], - "address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" - }, - { - "name": "metadata_program", - "docs": [ - "Program to create NFT metadata" - ], - "address": "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s" - } - ], - "args": [ - { - "name": "tick_lower_index", - "type": "i32" - }, - { - "name": "tick_upper_index", - "type": "i32" - }, - { - "name": "tick_array_lower_start_index", - "type": "i32" - }, - { - "name": "tick_array_upper_start_index", - "type": "i32" - }, - { - "name": "liquidity", - "type": "u128" - }, - { - "name": "amount_0_max", - "type": "u64" - }, - { - "name": "amount_1_max", - "type": "u64" - } - ] - }, - { - "name": "open_position_v2", - "docs": [ - "#[deprecated(note = \"Use `open_position_with_token22_nft` instead.\")]", - "Creates a new position wrapped in a NFT, support Token2022", - "", - "# Arguments", - "", - "* `ctx` - The context of accounts", - "* `tick_lower_index` - The low boundary of market", - "* `tick_upper_index` - The upper boundary of market", - "* `tick_array_lower_start_index` - The start index of tick array which include tick low", - "* `tick_array_upper_start_index` - The start index of tick array which include tick upper", - "* `liquidity` - The liquidity to be added, if zero, and the base_flag is specified, calculate liquidity base amount_0_max or amount_1_max according base_flag, otherwise open position with zero liquidity", - "* `amount_0_max` - The max amount of token_0 to spend, which serves as a slippage check", - "* `amount_1_max` - The max amount of token_1 to spend, which serves as a slippage check", - "* `with_metadata` - The flag indicating whether to create NFT mint metadata", - "* `base_flag` - if the liquidity specified as zero, true: calculate liquidity base amount_0_max otherwise base amount_1_max", - "" - ], - "discriminator": [ - 77, - 184, - 74, - 214, - 112, - 86, - 241, - 199 - ], - "accounts": [ - { - "name": "payer", - "docs": [ - "Pays to mint the position" - ], - "writable": true, - "signer": true - }, - { - "name": "position_nft_owner" - }, - { - "name": "position_nft_mint", - "docs": [ - "Unique token mint address" - ], - "writable": true, - "signer": true - }, - { - "name": "position_nft_account", - "docs": [ - "Token account where position NFT will be minted" - ], - "writable": true, - "pda": { - "seeds": [ - { - "kind": "account", - "path": "position_nft_owner" - }, - { - "kind": "const", - "value": [ - 6, - 221, - 246, - 225, - 215, - 101, - 161, - 147, - 217, - 203, - 225, - 70, - 206, - 235, - 121, - 172, - 28, - 180, - 133, - 237, - 95, - 91, - 55, - 145, - 58, - 140, - 245, - 133, - 126, - 255, - 0, - 169 - ] - }, - { - "kind": "account", - "path": "position_nft_mint" - } - ], - "program": { - "kind": "const", - "value": [ - 140, - 151, - 37, - 143, - 78, - 36, - 137, - 241, - 187, - 61, - 16, - 41, - 20, - 142, - 13, - 131, - 11, - 90, - 19, - 153, - 218, - 255, - 16, - 132, - 4, - 142, - 123, - 216, - 219, - 233, - 248, - 89 - ] - } - } - }, - { - "name": "metadata_account", - "docs": [ - "To store metaplex metadata" - ], - "writable": true - }, - { - "name": "pool_state", - "docs": [ - "Add liquidity for this pool" - ], - "writable": true - }, - { - "name": "protocol_position" - }, - { - "name": "tick_array_lower", - "writable": true, - "pda": { - "seeds": [ - { - "kind": "const", - "value": [ - 116, - 105, - 99, - 107, - 95, - 97, - 114, - 114, - 97, - 121 - ] - }, - { - "kind": "account", - "path": "pool_state" - }, - { - "kind": "arg", - "path": "tick_array_lower_start_index" - } - ] - } - }, - { - "name": "tick_array_upper", - "writable": true, - "pda": { - "seeds": [ - { - "kind": "const", - "value": [ - 116, - 105, - 99, - 107, - 95, - 97, - 114, - 114, - 97, - 121 - ] - }, - { - "kind": "account", - "path": "pool_state" - }, - { - "kind": "arg", - "path": "tick_array_upper_start_index" - } - ] - } - }, - { - "name": "personal_position", - "docs": [ - "personal position state" - ], - "writable": true, - "pda": { - "seeds": [ - { - "kind": "const", - "value": [ - 112, - 111, - 115, - 105, - 116, - 105, - 111, - 110 - ] - }, - { - "kind": "account", - "path": "position_nft_mint" - } - ] - } - }, - { - "name": "token_account_0", - "docs": [ - "The token_0 account deposit token to the pool" - ], - "writable": true - }, - { - "name": "token_account_1", - "docs": [ - "The token_1 account deposit token to the pool" - ], - "writable": true - }, - { - "name": "token_vault_0", - "docs": [ - "The address that holds pool tokens for token_0" - ], - "writable": true - }, - { - "name": "token_vault_1", - "docs": [ - "The address that holds pool tokens for token_1" - ], - "writable": true - }, - { - "name": "rent", - "docs": [ - "Sysvar for token mint and ATA creation" - ], - "address": "SysvarRent111111111111111111111111111111111" - }, - { - "name": "system_program", - "docs": [ - "Program to create the position manager state account" - ], - "address": "11111111111111111111111111111111" - }, + 230, + 68 + ], + "accounts": [ { - "name": "token_program", + "name": "reward_funder", "docs": [ - "Program to create mint account and mint tokens" + "The founder deposit reward token to vault" ], - "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" + "writable": true, + "signer": true }, { - "name": "associated_token_program", - "docs": [ - "Program to create an ATA for receiving position NFT" - ], - "address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" + "name": "funder_token_account", + "writable": true }, { - "name": "metadata_program", + "name": "amm_config", "docs": [ - "Program to create NFT metadata" - ], - "address": "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s" + "For check the reward_funder authority" + ] }, { - "name": "token_program_2022", + "name": "pool_state", "docs": [ - "Program to create mint account and mint tokens" + "Set reward for this pool" ], - "address": "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb" + "writable": true }, { - "name": "vault_0_mint", + "name": "operation_state", "docs": [ - "The mint of token vault 0" - ] + "load info from the account to judge reward permission" + ], + "pda": { + "seeds": [ + { + "kind": "const", + "value": [ + 111, + 112, + 101, + 114, + 97, + 116, + 105, + 111, + 110 + ] + } + ] + } }, { - "name": "vault_1_mint", + "name": "reward_token_mint", "docs": [ - "The mint of token vault 1" + "Reward mint" ] - } - ], - "args": [ - { - "name": "tick_lower_index", - "type": "i32" - }, - { - "name": "tick_upper_index", - "type": "i32" - }, - { - "name": "tick_array_lower_start_index", - "type": "i32" - }, - { - "name": "tick_array_upper_start_index", - "type": "i32" }, { - "name": "liquidity", - "type": "u128" + "name": "reward_token_vault", + "writable": true, + "pda": { + "seeds": [ + { + "kind": "const", + "value": [ + 112, + 111, + 111, + 108, + 95, + 114, + 101, + 119, + 97, + 114, + 100, + 95, + 118, + 97, + 117, + 108, + 116 + ] + }, + { + "kind": "account", + "path": "pool_state" + }, + { + "kind": "account", + "path": "reward_token_mint" + } + ] + } }, { - "name": "amount_0_max", - "type": "u64" + "name": "reward_token_program" }, { - "name": "amount_1_max", - "type": "u64" + "name": "system_program", + "address": "11111111111111111111111111111111" }, { - "name": "with_metadata", - "type": "bool" - }, + "name": "rent", + "address": "SysvarRent111111111111111111111111111111111" + } + ], + "args": [ { - "name": "base_flag", + "name": "param", "type": { - "option": "bool" + "defined": { + "name": "InitializeRewardParam" + } } } ] @@ -2656,118 +1704,6 @@ } ] }, - { - "name": "swap", - "docs": [ - "#[deprecated(note = \"Use `swap_v2` instead.\")]", - "Swaps one token for as much as possible of another token across a single pool", - "", - "# Arguments", - "", - "* `ctx` - The context of accounts", - "* `amount` - Arranged in pairs with other_amount_threshold. (amount_in, amount_out_minimum) or (amount_out, amount_in_maximum)", - "* `other_amount_threshold` - For slippage check", - "* `sqrt_price_limit` - The Q64.64 sqrt price √P limit. If zero for one, the price cannot", - "* `is_base_input` - swap base input or swap base output", - "" - ], - "discriminator": [ - 248, - 198, - 158, - 145, - 225, - 117, - 135, - 200 - ], - "accounts": [ - { - "name": "payer", - "docs": [ - "The user performing the swap" - ], - "signer": true - }, - { - "name": "amm_config", - "docs": [ - "The factory state to read protocol fees" - ] - }, - { - "name": "pool_state", - "docs": [ - "The program account of the pool in which the swap will be performed" - ], - "writable": true - }, - { - "name": "input_token_account", - "docs": [ - "The user token account for input token" - ], - "writable": true - }, - { - "name": "output_token_account", - "docs": [ - "The user token account for output token" - ], - "writable": true - }, - { - "name": "input_vault", - "docs": [ - "The vault token account for input token" - ], - "writable": true - }, - { - "name": "output_vault", - "docs": [ - "The vault token account for output token" - ], - "writable": true - }, - { - "name": "observation_state", - "docs": [ - "The program account for the most recent oracle observation" - ], - "writable": true - }, - { - "name": "token_program", - "docs": [ - "SPL program for token transfers" - ], - "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" - }, - { - "name": "tick_array", - "writable": true - } - ], - "args": [ - { - "name": "amount", - "type": "u64" - }, - { - "name": "other_amount_threshold", - "type": "u64" - }, - { - "name": "sqrt_price_limit_x64", - "type": "u128" - }, - { - "name": "is_base_input", - "type": "bool" - } - ] - }, { "name": "swap_router_base_in", "docs": [ @@ -3935,6 +2871,20 @@ ], "type": "pubkey" }, + { + "name": "personal_position", + "docs": [ + "The personal position" + ], + "type": "pubkey" + }, + { + "name": "nft_mint", + "docs": [ + "The nft mint address for the position" + ], + "type": "pubkey" + }, { "name": "minter", "docs": [ @@ -4614,6 +3564,13 @@ "Vault of token_1" ], "type": "pubkey" + }, + { + "name": "amm_config", + "docs": [ + "The PublicKey of the config account with fee rates etc" + ], + "type": "pubkey" } ] } @@ -5404,4 +4361,4 @@ } } ] -} +} \ No newline at end of file diff --git a/sdk/src/generated/instructions/decreaseLiquidity.ts b/sdk/src/generated/instructions/decreaseLiquidity.ts deleted file mode 100644 index 6509c9b..0000000 --- a/sdk/src/generated/instructions/decreaseLiquidity.ts +++ /dev/null @@ -1,391 +0,0 @@ -/** - * This code was AUTOGENERATED using the Codama library. - * Please DO NOT EDIT THIS FILE, instead use visitors - * to add features, then rerun Codama to update it. - * - * @see https://github.com/codama-idl/codama - */ - -import { - combineCodec, - fixDecoderSize, - fixEncoderSize, - getBytesDecoder, - getBytesEncoder, - getStructDecoder, - getStructEncoder, - getU128Decoder, - getU128Encoder, - getU64Decoder, - getU64Encoder, - transformEncoder, - type AccountMeta, - type AccountSignerMeta, - type Address, - type FixedSizeCodec, - type FixedSizeDecoder, - type FixedSizeEncoder, - type Instruction, - type InstructionWithAccounts, - type InstructionWithData, - type ReadonlyAccount, - type ReadonlySignerAccount, - type ReadonlyUint8Array, - type TransactionSigner, - type WritableAccount, -} from '@solana/kit'; -import { AMM_V3_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; - -export const DECREASE_LIQUIDITY_DISCRIMINATOR = new Uint8Array([ - 160, 38, 208, 111, 104, 91, 44, 1, -]); - -export function getDecreaseLiquidityDiscriminatorBytes() { - return fixEncoderSize(getBytesEncoder(), 8).encode( - DECREASE_LIQUIDITY_DISCRIMINATOR - ); -} - -export type DecreaseLiquidityInstruction< - TProgram extends string = typeof AMM_V3_PROGRAM_ADDRESS, - TAccountNftOwner extends string | AccountMeta = string, - TAccountNftAccount extends string | AccountMeta = string, - TAccountPersonalPosition extends string | AccountMeta = string, - TAccountPoolState extends string | AccountMeta = string, - TAccountProtocolPosition extends string | AccountMeta = string, - TAccountTokenVault0 extends string | AccountMeta = string, - TAccountTokenVault1 extends string | AccountMeta = string, - TAccountTickArrayLower extends string | AccountMeta = string, - TAccountTickArrayUpper extends string | AccountMeta = string, - TAccountRecipientTokenAccount0 extends string | AccountMeta = string, - TAccountRecipientTokenAccount1 extends string | AccountMeta = string, - TAccountTokenProgram extends - | string - | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - TRemainingAccounts extends readonly AccountMeta[] = [], -> = Instruction & - InstructionWithData & - InstructionWithAccounts< - [ - TAccountNftOwner extends string - ? ReadonlySignerAccount & - AccountSignerMeta - : TAccountNftOwner, - TAccountNftAccount extends string - ? ReadonlyAccount - : TAccountNftAccount, - TAccountPersonalPosition extends string - ? WritableAccount - : TAccountPersonalPosition, - TAccountPoolState extends string - ? WritableAccount - : TAccountPoolState, - TAccountProtocolPosition extends string - ? ReadonlyAccount - : TAccountProtocolPosition, - TAccountTokenVault0 extends string - ? WritableAccount - : TAccountTokenVault0, - TAccountTokenVault1 extends string - ? WritableAccount - : TAccountTokenVault1, - TAccountTickArrayLower extends string - ? WritableAccount - : TAccountTickArrayLower, - TAccountTickArrayUpper extends string - ? WritableAccount - : TAccountTickArrayUpper, - TAccountRecipientTokenAccount0 extends string - ? WritableAccount - : TAccountRecipientTokenAccount0, - TAccountRecipientTokenAccount1 extends string - ? WritableAccount - : TAccountRecipientTokenAccount1, - TAccountTokenProgram extends string - ? ReadonlyAccount - : TAccountTokenProgram, - ...TRemainingAccounts, - ] - >; - -export type DecreaseLiquidityInstructionData = { - discriminator: ReadonlyUint8Array; - liquidity: bigint; - amount0Min: bigint; - amount1Min: bigint; -}; - -export type DecreaseLiquidityInstructionDataArgs = { - liquidity: number | bigint; - amount0Min: number | bigint; - amount1Min: number | bigint; -}; - -export function getDecreaseLiquidityInstructionDataEncoder(): FixedSizeEncoder { - return transformEncoder( - getStructEncoder([ - ['discriminator', fixEncoderSize(getBytesEncoder(), 8)], - ['liquidity', getU128Encoder()], - ['amount0Min', getU64Encoder()], - ['amount1Min', getU64Encoder()], - ]), - (value) => ({ ...value, discriminator: DECREASE_LIQUIDITY_DISCRIMINATOR }) - ); -} - -export function getDecreaseLiquidityInstructionDataDecoder(): FixedSizeDecoder { - return getStructDecoder([ - ['discriminator', fixDecoderSize(getBytesDecoder(), 8)], - ['liquidity', getU128Decoder()], - ['amount0Min', getU64Decoder()], - ['amount1Min', getU64Decoder()], - ]); -} - -export function getDecreaseLiquidityInstructionDataCodec(): FixedSizeCodec< - DecreaseLiquidityInstructionDataArgs, - DecreaseLiquidityInstructionData -> { - return combineCodec( - getDecreaseLiquidityInstructionDataEncoder(), - getDecreaseLiquidityInstructionDataDecoder() - ); -} - -export type DecreaseLiquidityInput< - TAccountNftOwner extends string = string, - TAccountNftAccount extends string = string, - TAccountPersonalPosition extends string = string, - TAccountPoolState extends string = string, - TAccountProtocolPosition extends string = string, - TAccountTokenVault0 extends string = string, - TAccountTokenVault1 extends string = string, - TAccountTickArrayLower extends string = string, - TAccountTickArrayUpper extends string = string, - TAccountRecipientTokenAccount0 extends string = string, - TAccountRecipientTokenAccount1 extends string = string, - TAccountTokenProgram extends string = string, -> = { - /** The position owner or delegated authority */ - nftOwner: TransactionSigner; - /** The token account for the tokenized position */ - nftAccount: Address; - /** Decrease liquidity for this position */ - personalPosition: Address; - poolState: Address; - protocolPosition: Address; - /** Token_0 vault */ - tokenVault0: Address; - /** Token_1 vault */ - tokenVault1: Address; - /** Stores init state for the lower tick */ - tickArrayLower: Address; - /** Stores init state for the upper tick */ - tickArrayUpper: Address; - /** The destination token account for receive amount_0 */ - recipientTokenAccount0: Address; - /** The destination token account for receive amount_1 */ - recipientTokenAccount1: Address; - /** SPL program to transfer out tokens */ - tokenProgram?: Address; - liquidity: DecreaseLiquidityInstructionDataArgs['liquidity']; - amount0Min: DecreaseLiquidityInstructionDataArgs['amount0Min']; - amount1Min: DecreaseLiquidityInstructionDataArgs['amount1Min']; -}; - -export function getDecreaseLiquidityInstruction< - TAccountNftOwner extends string, - TAccountNftAccount extends string, - TAccountPersonalPosition extends string, - TAccountPoolState extends string, - TAccountProtocolPosition extends string, - TAccountTokenVault0 extends string, - TAccountTokenVault1 extends string, - TAccountTickArrayLower extends string, - TAccountTickArrayUpper extends string, - TAccountRecipientTokenAccount0 extends string, - TAccountRecipientTokenAccount1 extends string, - TAccountTokenProgram extends string, - TProgramAddress extends Address = typeof AMM_V3_PROGRAM_ADDRESS, ->( - input: DecreaseLiquidityInput< - TAccountNftOwner, - TAccountNftAccount, - TAccountPersonalPosition, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountRecipientTokenAccount0, - TAccountRecipientTokenAccount1, - TAccountTokenProgram - >, - config?: { programAddress?: TProgramAddress } -): DecreaseLiquidityInstruction< - TProgramAddress, - TAccountNftOwner, - TAccountNftAccount, - TAccountPersonalPosition, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountRecipientTokenAccount0, - TAccountRecipientTokenAccount1, - TAccountTokenProgram -> { - // Program address. - const programAddress = config?.programAddress ?? AMM_V3_PROGRAM_ADDRESS; - - // Original accounts. - const originalAccounts = { - nftOwner: { value: input.nftOwner ?? null, isWritable: false }, - nftAccount: { value: input.nftAccount ?? null, isWritable: false }, - personalPosition: { - value: input.personalPosition ?? null, - isWritable: true, - }, - poolState: { value: input.poolState ?? null, isWritable: true }, - protocolPosition: { - value: input.protocolPosition ?? null, - isWritable: false, - }, - tokenVault0: { value: input.tokenVault0 ?? null, isWritable: true }, - tokenVault1: { value: input.tokenVault1 ?? null, isWritable: true }, - tickArrayLower: { value: input.tickArrayLower ?? null, isWritable: true }, - tickArrayUpper: { value: input.tickArrayUpper ?? null, isWritable: true }, - recipientTokenAccount0: { - value: input.recipientTokenAccount0 ?? null, - isWritable: true, - }, - recipientTokenAccount1: { - value: input.recipientTokenAccount1 ?? null, - isWritable: true, - }, - tokenProgram: { value: input.tokenProgram ?? null, isWritable: false }, - }; - const accounts = originalAccounts as Record< - keyof typeof originalAccounts, - ResolvedAccount - >; - - // Original args. - const args = { ...input }; - - // Resolve default values. - if (!accounts.tokenProgram.value) { - accounts.tokenProgram.value = - 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>; - } - - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); - return Object.freeze({ - accounts: [ - getAccountMeta(accounts.nftOwner), - getAccountMeta(accounts.nftAccount), - getAccountMeta(accounts.personalPosition), - getAccountMeta(accounts.poolState), - getAccountMeta(accounts.protocolPosition), - getAccountMeta(accounts.tokenVault0), - getAccountMeta(accounts.tokenVault1), - getAccountMeta(accounts.tickArrayLower), - getAccountMeta(accounts.tickArrayUpper), - getAccountMeta(accounts.recipientTokenAccount0), - getAccountMeta(accounts.recipientTokenAccount1), - getAccountMeta(accounts.tokenProgram), - ], - data: getDecreaseLiquidityInstructionDataEncoder().encode( - args as DecreaseLiquidityInstructionDataArgs - ), - programAddress, - } as DecreaseLiquidityInstruction< - TProgramAddress, - TAccountNftOwner, - TAccountNftAccount, - TAccountPersonalPosition, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountRecipientTokenAccount0, - TAccountRecipientTokenAccount1, - TAccountTokenProgram - >); -} - -export type ParsedDecreaseLiquidityInstruction< - TProgram extends string = typeof AMM_V3_PROGRAM_ADDRESS, - TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[], -> = { - programAddress: Address; - accounts: { - /** The position owner or delegated authority */ - nftOwner: TAccountMetas[0]; - /** The token account for the tokenized position */ - nftAccount: TAccountMetas[1]; - /** Decrease liquidity for this position */ - personalPosition: TAccountMetas[2]; - poolState: TAccountMetas[3]; - protocolPosition: TAccountMetas[4]; - /** Token_0 vault */ - tokenVault0: TAccountMetas[5]; - /** Token_1 vault */ - tokenVault1: TAccountMetas[6]; - /** Stores init state for the lower tick */ - tickArrayLower: TAccountMetas[7]; - /** Stores init state for the upper tick */ - tickArrayUpper: TAccountMetas[8]; - /** The destination token account for receive amount_0 */ - recipientTokenAccount0: TAccountMetas[9]; - /** The destination token account for receive amount_1 */ - recipientTokenAccount1: TAccountMetas[10]; - /** SPL program to transfer out tokens */ - tokenProgram: TAccountMetas[11]; - }; - data: DecreaseLiquidityInstructionData; -}; - -export function parseDecreaseLiquidityInstruction< - TProgram extends string, - TAccountMetas extends readonly AccountMeta[], ->( - instruction: Instruction & - InstructionWithAccounts & - InstructionWithData -): ParsedDecreaseLiquidityInstruction { - if (instruction.accounts.length < 12) { - // TODO: Coded error. - throw new Error('Not enough accounts'); - } - let accountIndex = 0; - const getNextAccount = () => { - const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!; - accountIndex += 1; - return accountMeta; - }; - return { - programAddress: instruction.programAddress, - accounts: { - nftOwner: getNextAccount(), - nftAccount: getNextAccount(), - personalPosition: getNextAccount(), - poolState: getNextAccount(), - protocolPosition: getNextAccount(), - tokenVault0: getNextAccount(), - tokenVault1: getNextAccount(), - tickArrayLower: getNextAccount(), - tickArrayUpper: getNextAccount(), - recipientTokenAccount0: getNextAccount(), - recipientTokenAccount1: getNextAccount(), - tokenProgram: getNextAccount(), - }, - data: getDecreaseLiquidityInstructionDataDecoder().decode(instruction.data), - }; -} diff --git a/sdk/src/generated/instructions/increaseLiquidity.ts b/sdk/src/generated/instructions/increaseLiquidity.ts deleted file mode 100644 index 77be99f..0000000 --- a/sdk/src/generated/instructions/increaseLiquidity.ts +++ /dev/null @@ -1,385 +0,0 @@ -/** - * This code was AUTOGENERATED using the Codama library. - * Please DO NOT EDIT THIS FILE, instead use visitors - * to add features, then rerun Codama to update it. - * - * @see https://github.com/codama-idl/codama - */ - -import { - combineCodec, - fixDecoderSize, - fixEncoderSize, - getBytesDecoder, - getBytesEncoder, - getStructDecoder, - getStructEncoder, - getU128Decoder, - getU128Encoder, - getU64Decoder, - getU64Encoder, - transformEncoder, - type AccountMeta, - type AccountSignerMeta, - type Address, - type FixedSizeCodec, - type FixedSizeDecoder, - type FixedSizeEncoder, - type Instruction, - type InstructionWithAccounts, - type InstructionWithData, - type ReadonlyAccount, - type ReadonlySignerAccount, - type ReadonlyUint8Array, - type TransactionSigner, - type WritableAccount, -} from '@solana/kit'; -import { AMM_V3_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; - -export const INCREASE_LIQUIDITY_DISCRIMINATOR = new Uint8Array([ - 46, 156, 243, 118, 13, 205, 251, 178, -]); - -export function getIncreaseLiquidityDiscriminatorBytes() { - return fixEncoderSize(getBytesEncoder(), 8).encode( - INCREASE_LIQUIDITY_DISCRIMINATOR - ); -} - -export type IncreaseLiquidityInstruction< - TProgram extends string = typeof AMM_V3_PROGRAM_ADDRESS, - TAccountNftOwner extends string | AccountMeta = string, - TAccountNftAccount extends string | AccountMeta = string, - TAccountPoolState extends string | AccountMeta = string, - TAccountProtocolPosition extends string | AccountMeta = string, - TAccountPersonalPosition extends string | AccountMeta = string, - TAccountTickArrayLower extends string | AccountMeta = string, - TAccountTickArrayUpper extends string | AccountMeta = string, - TAccountTokenAccount0 extends string | AccountMeta = string, - TAccountTokenAccount1 extends string | AccountMeta = string, - TAccountTokenVault0 extends string | AccountMeta = string, - TAccountTokenVault1 extends string | AccountMeta = string, - TAccountTokenProgram extends - | string - | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - TRemainingAccounts extends readonly AccountMeta[] = [], -> = Instruction & - InstructionWithData & - InstructionWithAccounts< - [ - TAccountNftOwner extends string - ? ReadonlySignerAccount & - AccountSignerMeta - : TAccountNftOwner, - TAccountNftAccount extends string - ? ReadonlyAccount - : TAccountNftAccount, - TAccountPoolState extends string - ? WritableAccount - : TAccountPoolState, - TAccountProtocolPosition extends string - ? ReadonlyAccount - : TAccountProtocolPosition, - TAccountPersonalPosition extends string - ? WritableAccount - : TAccountPersonalPosition, - TAccountTickArrayLower extends string - ? WritableAccount - : TAccountTickArrayLower, - TAccountTickArrayUpper extends string - ? WritableAccount - : TAccountTickArrayUpper, - TAccountTokenAccount0 extends string - ? WritableAccount - : TAccountTokenAccount0, - TAccountTokenAccount1 extends string - ? WritableAccount - : TAccountTokenAccount1, - TAccountTokenVault0 extends string - ? WritableAccount - : TAccountTokenVault0, - TAccountTokenVault1 extends string - ? WritableAccount - : TAccountTokenVault1, - TAccountTokenProgram extends string - ? ReadonlyAccount - : TAccountTokenProgram, - ...TRemainingAccounts, - ] - >; - -export type IncreaseLiquidityInstructionData = { - discriminator: ReadonlyUint8Array; - liquidity: bigint; - amount0Max: bigint; - amount1Max: bigint; -}; - -export type IncreaseLiquidityInstructionDataArgs = { - liquidity: number | bigint; - amount0Max: number | bigint; - amount1Max: number | bigint; -}; - -export function getIncreaseLiquidityInstructionDataEncoder(): FixedSizeEncoder { - return transformEncoder( - getStructEncoder([ - ['discriminator', fixEncoderSize(getBytesEncoder(), 8)], - ['liquidity', getU128Encoder()], - ['amount0Max', getU64Encoder()], - ['amount1Max', getU64Encoder()], - ]), - (value) => ({ ...value, discriminator: INCREASE_LIQUIDITY_DISCRIMINATOR }) - ); -} - -export function getIncreaseLiquidityInstructionDataDecoder(): FixedSizeDecoder { - return getStructDecoder([ - ['discriminator', fixDecoderSize(getBytesDecoder(), 8)], - ['liquidity', getU128Decoder()], - ['amount0Max', getU64Decoder()], - ['amount1Max', getU64Decoder()], - ]); -} - -export function getIncreaseLiquidityInstructionDataCodec(): FixedSizeCodec< - IncreaseLiquidityInstructionDataArgs, - IncreaseLiquidityInstructionData -> { - return combineCodec( - getIncreaseLiquidityInstructionDataEncoder(), - getIncreaseLiquidityInstructionDataDecoder() - ); -} - -export type IncreaseLiquidityInput< - TAccountNftOwner extends string = string, - TAccountNftAccount extends string = string, - TAccountPoolState extends string = string, - TAccountProtocolPosition extends string = string, - TAccountPersonalPosition extends string = string, - TAccountTickArrayLower extends string = string, - TAccountTickArrayUpper extends string = string, - TAccountTokenAccount0 extends string = string, - TAccountTokenAccount1 extends string = string, - TAccountTokenVault0 extends string = string, - TAccountTokenVault1 extends string = string, - TAccountTokenProgram extends string = string, -> = { - /** Pays to mint the position */ - nftOwner: TransactionSigner; - /** The token account for nft */ - nftAccount: Address; - poolState: Address; - protocolPosition: Address; - /** Increase liquidity for this position */ - personalPosition: Address; - /** Stores init state for the lower tick */ - tickArrayLower: Address; - /** Stores init state for the upper tick */ - tickArrayUpper: Address; - /** The payer's token account for token_0 */ - tokenAccount0: Address; - /** The token account spending token_1 to mint the position */ - tokenAccount1: Address; - /** The address that holds pool tokens for token_0 */ - tokenVault0: Address; - /** The address that holds pool tokens for token_1 */ - tokenVault1: Address; - /** Program to create mint account and mint tokens */ - tokenProgram?: Address; - liquidity: IncreaseLiquidityInstructionDataArgs['liquidity']; - amount0Max: IncreaseLiquidityInstructionDataArgs['amount0Max']; - amount1Max: IncreaseLiquidityInstructionDataArgs['amount1Max']; -}; - -export function getIncreaseLiquidityInstruction< - TAccountNftOwner extends string, - TAccountNftAccount extends string, - TAccountPoolState extends string, - TAccountProtocolPosition extends string, - TAccountPersonalPosition extends string, - TAccountTickArrayLower extends string, - TAccountTickArrayUpper extends string, - TAccountTokenAccount0 extends string, - TAccountTokenAccount1 extends string, - TAccountTokenVault0 extends string, - TAccountTokenVault1 extends string, - TAccountTokenProgram extends string, - TProgramAddress extends Address = typeof AMM_V3_PROGRAM_ADDRESS, ->( - input: IncreaseLiquidityInput< - TAccountNftOwner, - TAccountNftAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountPersonalPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountTokenProgram - >, - config?: { programAddress?: TProgramAddress } -): IncreaseLiquidityInstruction< - TProgramAddress, - TAccountNftOwner, - TAccountNftAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountPersonalPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountTokenProgram -> { - // Program address. - const programAddress = config?.programAddress ?? AMM_V3_PROGRAM_ADDRESS; - - // Original accounts. - const originalAccounts = { - nftOwner: { value: input.nftOwner ?? null, isWritable: false }, - nftAccount: { value: input.nftAccount ?? null, isWritable: false }, - poolState: { value: input.poolState ?? null, isWritable: true }, - protocolPosition: { - value: input.protocolPosition ?? null, - isWritable: false, - }, - personalPosition: { - value: input.personalPosition ?? null, - isWritable: true, - }, - tickArrayLower: { value: input.tickArrayLower ?? null, isWritable: true }, - tickArrayUpper: { value: input.tickArrayUpper ?? null, isWritable: true }, - tokenAccount0: { value: input.tokenAccount0 ?? null, isWritable: true }, - tokenAccount1: { value: input.tokenAccount1 ?? null, isWritable: true }, - tokenVault0: { value: input.tokenVault0 ?? null, isWritable: true }, - tokenVault1: { value: input.tokenVault1 ?? null, isWritable: true }, - tokenProgram: { value: input.tokenProgram ?? null, isWritable: false }, - }; - const accounts = originalAccounts as Record< - keyof typeof originalAccounts, - ResolvedAccount - >; - - // Original args. - const args = { ...input }; - - // Resolve default values. - if (!accounts.tokenProgram.value) { - accounts.tokenProgram.value = - 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>; - } - - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); - return Object.freeze({ - accounts: [ - getAccountMeta(accounts.nftOwner), - getAccountMeta(accounts.nftAccount), - getAccountMeta(accounts.poolState), - getAccountMeta(accounts.protocolPosition), - getAccountMeta(accounts.personalPosition), - getAccountMeta(accounts.tickArrayLower), - getAccountMeta(accounts.tickArrayUpper), - getAccountMeta(accounts.tokenAccount0), - getAccountMeta(accounts.tokenAccount1), - getAccountMeta(accounts.tokenVault0), - getAccountMeta(accounts.tokenVault1), - getAccountMeta(accounts.tokenProgram), - ], - data: getIncreaseLiquidityInstructionDataEncoder().encode( - args as IncreaseLiquidityInstructionDataArgs - ), - programAddress, - } as IncreaseLiquidityInstruction< - TProgramAddress, - TAccountNftOwner, - TAccountNftAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountPersonalPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountTokenProgram - >); -} - -export type ParsedIncreaseLiquidityInstruction< - TProgram extends string = typeof AMM_V3_PROGRAM_ADDRESS, - TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[], -> = { - programAddress: Address; - accounts: { - /** Pays to mint the position */ - nftOwner: TAccountMetas[0]; - /** The token account for nft */ - nftAccount: TAccountMetas[1]; - poolState: TAccountMetas[2]; - protocolPosition: TAccountMetas[3]; - /** Increase liquidity for this position */ - personalPosition: TAccountMetas[4]; - /** Stores init state for the lower tick */ - tickArrayLower: TAccountMetas[5]; - /** Stores init state for the upper tick */ - tickArrayUpper: TAccountMetas[6]; - /** The payer's token account for token_0 */ - tokenAccount0: TAccountMetas[7]; - /** The token account spending token_1 to mint the position */ - tokenAccount1: TAccountMetas[8]; - /** The address that holds pool tokens for token_0 */ - tokenVault0: TAccountMetas[9]; - /** The address that holds pool tokens for token_1 */ - tokenVault1: TAccountMetas[10]; - /** Program to create mint account and mint tokens */ - tokenProgram: TAccountMetas[11]; - }; - data: IncreaseLiquidityInstructionData; -}; - -export function parseIncreaseLiquidityInstruction< - TProgram extends string, - TAccountMetas extends readonly AccountMeta[], ->( - instruction: Instruction & - InstructionWithAccounts & - InstructionWithData -): ParsedIncreaseLiquidityInstruction { - if (instruction.accounts.length < 12) { - // TODO: Coded error. - throw new Error('Not enough accounts'); - } - let accountIndex = 0; - const getNextAccount = () => { - const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!; - accountIndex += 1; - return accountMeta; - }; - return { - programAddress: instruction.programAddress, - accounts: { - nftOwner: getNextAccount(), - nftAccount: getNextAccount(), - poolState: getNextAccount(), - protocolPosition: getNextAccount(), - personalPosition: getNextAccount(), - tickArrayLower: getNextAccount(), - tickArrayUpper: getNextAccount(), - tokenAccount0: getNextAccount(), - tokenAccount1: getNextAccount(), - tokenVault0: getNextAccount(), - tokenVault1: getNextAccount(), - tokenProgram: getNextAccount(), - }, - data: getIncreaseLiquidityInstructionDataDecoder().decode(instruction.data), - }; -} diff --git a/sdk/src/generated/instructions/index.ts b/sdk/src/generated/instructions/index.ts index b9e319d..0e44e37 100644 --- a/sdk/src/generated/instructions/index.ts +++ b/sdk/src/generated/instructions/index.ts @@ -15,16 +15,11 @@ export * from './createAmmConfig'; export * from './createOperationAccount'; export * from './createPool'; export * from './createSupportMintAssociated'; -export * from './decreaseLiquidity'; export * from './decreaseLiquidityV2'; -export * from './increaseLiquidity'; export * from './increaseLiquidityV2'; export * from './initializeReward'; -export * from './openPosition'; -export * from './openPositionV2'; export * from './openPositionWithToken22Nft'; export * from './setRewardParams'; -export * from './swap'; export * from './swapRouterBaseIn'; export * from './swapV2'; export * from './transferRewardOwner'; diff --git a/sdk/src/generated/instructions/openPosition.ts b/sdk/src/generated/instructions/openPosition.ts deleted file mode 100644 index 9dd67cb..0000000 --- a/sdk/src/generated/instructions/openPosition.ts +++ /dev/null @@ -1,882 +0,0 @@ -/** - * This code was AUTOGENERATED using the Codama library. - * Please DO NOT EDIT THIS FILE, instead use visitors - * to add features, then rerun Codama to update it. - * - * @see https://github.com/codama-idl/codama - */ - -import { - combineCodec, - fixDecoderSize, - fixEncoderSize, - getAddressEncoder, - getBytesDecoder, - getBytesEncoder, - getI32Decoder, - getI32Encoder, - getProgramDerivedAddress, - getStructDecoder, - getStructEncoder, - getU128Decoder, - getU128Encoder, - getU64Decoder, - getU64Encoder, - transformEncoder, - type AccountMeta, - type AccountSignerMeta, - type Address, - type FixedSizeCodec, - type FixedSizeDecoder, - type FixedSizeEncoder, - type Instruction, - type InstructionWithAccounts, - type InstructionWithData, - type ReadonlyAccount, - type ReadonlyUint8Array, - type TransactionSigner, - type WritableAccount, - type WritableSignerAccount, -} from '@solana/kit'; -import { AMM_V3_PROGRAM_ADDRESS } from '../programs'; -import { - expectAddress, - expectSome, - getAccountMetaFactory, - type ResolvedAccount, -} from '../shared'; - -export const OPEN_POSITION_DISCRIMINATOR = new Uint8Array([ - 135, 128, 47, 77, 15, 152, 240, 49, -]); - -export function getOpenPositionDiscriminatorBytes() { - return fixEncoderSize(getBytesEncoder(), 8).encode( - OPEN_POSITION_DISCRIMINATOR - ); -} - -export type OpenPositionInstruction< - TProgram extends string = typeof AMM_V3_PROGRAM_ADDRESS, - TAccountPayer extends string | AccountMeta = string, - TAccountPositionNftOwner extends string | AccountMeta = string, - TAccountPositionNftMint extends string | AccountMeta = string, - TAccountPositionNftAccount extends string | AccountMeta = string, - TAccountMetadataAccount extends string | AccountMeta = string, - TAccountPoolState extends string | AccountMeta = string, - TAccountProtocolPosition extends string | AccountMeta = string, - TAccountTickArrayLower extends string | AccountMeta = string, - TAccountTickArrayUpper extends string | AccountMeta = string, - TAccountPersonalPosition extends string | AccountMeta = string, - TAccountTokenAccount0 extends string | AccountMeta = string, - TAccountTokenAccount1 extends string | AccountMeta = string, - TAccountTokenVault0 extends string | AccountMeta = string, - TAccountTokenVault1 extends string | AccountMeta = string, - TAccountRent extends - | string - | AccountMeta = 'SysvarRent111111111111111111111111111111111', - TAccountSystemProgram extends - | string - | AccountMeta = '11111111111111111111111111111111', - TAccountTokenProgram extends - | string - | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - TAccountAssociatedTokenProgram extends - | string - | AccountMeta = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', - TAccountMetadataProgram extends - | string - | AccountMeta = 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', - TRemainingAccounts extends readonly AccountMeta[] = [], -> = Instruction & - InstructionWithData & - InstructionWithAccounts< - [ - TAccountPayer extends string - ? WritableSignerAccount & - AccountSignerMeta - : TAccountPayer, - TAccountPositionNftOwner extends string - ? ReadonlyAccount - : TAccountPositionNftOwner, - TAccountPositionNftMint extends string - ? WritableSignerAccount & - AccountSignerMeta - : TAccountPositionNftMint, - TAccountPositionNftAccount extends string - ? WritableAccount - : TAccountPositionNftAccount, - TAccountMetadataAccount extends string - ? WritableAccount - : TAccountMetadataAccount, - TAccountPoolState extends string - ? WritableAccount - : TAccountPoolState, - TAccountProtocolPosition extends string - ? ReadonlyAccount - : TAccountProtocolPosition, - TAccountTickArrayLower extends string - ? WritableAccount - : TAccountTickArrayLower, - TAccountTickArrayUpper extends string - ? WritableAccount - : TAccountTickArrayUpper, - TAccountPersonalPosition extends string - ? WritableAccount - : TAccountPersonalPosition, - TAccountTokenAccount0 extends string - ? WritableAccount - : TAccountTokenAccount0, - TAccountTokenAccount1 extends string - ? WritableAccount - : TAccountTokenAccount1, - TAccountTokenVault0 extends string - ? WritableAccount - : TAccountTokenVault0, - TAccountTokenVault1 extends string - ? WritableAccount - : TAccountTokenVault1, - TAccountRent extends string - ? ReadonlyAccount - : TAccountRent, - TAccountSystemProgram extends string - ? ReadonlyAccount - : TAccountSystemProgram, - TAccountTokenProgram extends string - ? ReadonlyAccount - : TAccountTokenProgram, - TAccountAssociatedTokenProgram extends string - ? ReadonlyAccount - : TAccountAssociatedTokenProgram, - TAccountMetadataProgram extends string - ? ReadonlyAccount - : TAccountMetadataProgram, - ...TRemainingAccounts, - ] - >; - -export type OpenPositionInstructionData = { - discriminator: ReadonlyUint8Array; - tickLowerIndex: number; - tickUpperIndex: number; - tickArrayLowerStartIndex: number; - tickArrayUpperStartIndex: number; - liquidity: bigint; - amount0Max: bigint; - amount1Max: bigint; -}; - -export type OpenPositionInstructionDataArgs = { - tickLowerIndex: number; - tickUpperIndex: number; - tickArrayLowerStartIndex: number; - tickArrayUpperStartIndex: number; - liquidity: number | bigint; - amount0Max: number | bigint; - amount1Max: number | bigint; -}; - -export function getOpenPositionInstructionDataEncoder(): FixedSizeEncoder { - return transformEncoder( - getStructEncoder([ - ['discriminator', fixEncoderSize(getBytesEncoder(), 8)], - ['tickLowerIndex', getI32Encoder()], - ['tickUpperIndex', getI32Encoder()], - ['tickArrayLowerStartIndex', getI32Encoder()], - ['tickArrayUpperStartIndex', getI32Encoder()], - ['liquidity', getU128Encoder()], - ['amount0Max', getU64Encoder()], - ['amount1Max', getU64Encoder()], - ]), - (value) => ({ ...value, discriminator: OPEN_POSITION_DISCRIMINATOR }) - ); -} - -export function getOpenPositionInstructionDataDecoder(): FixedSizeDecoder { - return getStructDecoder([ - ['discriminator', fixDecoderSize(getBytesDecoder(), 8)], - ['tickLowerIndex', getI32Decoder()], - ['tickUpperIndex', getI32Decoder()], - ['tickArrayLowerStartIndex', getI32Decoder()], - ['tickArrayUpperStartIndex', getI32Decoder()], - ['liquidity', getU128Decoder()], - ['amount0Max', getU64Decoder()], - ['amount1Max', getU64Decoder()], - ]); -} - -export function getOpenPositionInstructionDataCodec(): FixedSizeCodec< - OpenPositionInstructionDataArgs, - OpenPositionInstructionData -> { - return combineCodec( - getOpenPositionInstructionDataEncoder(), - getOpenPositionInstructionDataDecoder() - ); -} - -export type OpenPositionAsyncInput< - TAccountPayer extends string = string, - TAccountPositionNftOwner extends string = string, - TAccountPositionNftMint extends string = string, - TAccountPositionNftAccount extends string = string, - TAccountMetadataAccount extends string = string, - TAccountPoolState extends string = string, - TAccountProtocolPosition extends string = string, - TAccountTickArrayLower extends string = string, - TAccountTickArrayUpper extends string = string, - TAccountPersonalPosition extends string = string, - TAccountTokenAccount0 extends string = string, - TAccountTokenAccount1 extends string = string, - TAccountTokenVault0 extends string = string, - TAccountTokenVault1 extends string = string, - TAccountRent extends string = string, - TAccountSystemProgram extends string = string, - TAccountTokenProgram extends string = string, - TAccountAssociatedTokenProgram extends string = string, - TAccountMetadataProgram extends string = string, -> = { - /** Pays to mint the position */ - payer: TransactionSigner; - positionNftOwner: Address; - /** Unique token mint address */ - positionNftMint: TransactionSigner; - /** - * Token account where position NFT will be minted - * This account created in the contract by cpi to avoid large stack variables - */ - positionNftAccount?: Address; - /** To store metaplex metadata */ - metadataAccount: Address; - /** Add liquidity for this pool */ - poolState: Address; - protocolPosition: Address; - tickArrayLower?: Address; - tickArrayUpper?: Address; - /** personal position state */ - personalPosition?: Address; - /** The token_0 account deposit token to the pool */ - tokenAccount0: Address; - /** The token_1 account deposit token to the pool */ - tokenAccount1: Address; - /** The address that holds pool tokens for token_0 */ - tokenVault0: Address; - /** The address that holds pool tokens for token_1 */ - tokenVault1: Address; - /** Sysvar for token mint and ATA creation */ - rent?: Address; - /** Program to create the position manager state account */ - systemProgram?: Address; - /** Program to create mint account and mint tokens */ - tokenProgram?: Address; - /** Program to create an ATA for receiving position NFT */ - associatedTokenProgram?: Address; - /** Program to create NFT metadata */ - metadataProgram?: Address; - tickLowerIndex: OpenPositionInstructionDataArgs['tickLowerIndex']; - tickUpperIndex: OpenPositionInstructionDataArgs['tickUpperIndex']; - tickArrayLowerStartIndex: OpenPositionInstructionDataArgs['tickArrayLowerStartIndex']; - tickArrayUpperStartIndex: OpenPositionInstructionDataArgs['tickArrayUpperStartIndex']; - liquidity: OpenPositionInstructionDataArgs['liquidity']; - amount0Max: OpenPositionInstructionDataArgs['amount0Max']; - amount1Max: OpenPositionInstructionDataArgs['amount1Max']; -}; - -export async function getOpenPositionInstructionAsync< - TAccountPayer extends string, - TAccountPositionNftOwner extends string, - TAccountPositionNftMint extends string, - TAccountPositionNftAccount extends string, - TAccountMetadataAccount extends string, - TAccountPoolState extends string, - TAccountProtocolPosition extends string, - TAccountTickArrayLower extends string, - TAccountTickArrayUpper extends string, - TAccountPersonalPosition extends string, - TAccountTokenAccount0 extends string, - TAccountTokenAccount1 extends string, - TAccountTokenVault0 extends string, - TAccountTokenVault1 extends string, - TAccountRent extends string, - TAccountSystemProgram extends string, - TAccountTokenProgram extends string, - TAccountAssociatedTokenProgram extends string, - TAccountMetadataProgram extends string, - TProgramAddress extends Address = typeof AMM_V3_PROGRAM_ADDRESS, ->( - input: OpenPositionAsyncInput< - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram - >, - config?: { programAddress?: TProgramAddress } -): Promise< - OpenPositionInstruction< - TProgramAddress, - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram - > -> { - // Program address. - const programAddress = config?.programAddress ?? AMM_V3_PROGRAM_ADDRESS; - - // Original accounts. - const originalAccounts = { - payer: { value: input.payer ?? null, isWritable: true }, - positionNftOwner: { - value: input.positionNftOwner ?? null, - isWritable: false, - }, - positionNftMint: { value: input.positionNftMint ?? null, isWritable: true }, - positionNftAccount: { - value: input.positionNftAccount ?? null, - isWritable: true, - }, - metadataAccount: { value: input.metadataAccount ?? null, isWritable: true }, - poolState: { value: input.poolState ?? null, isWritable: true }, - protocolPosition: { - value: input.protocolPosition ?? null, - isWritable: false, - }, - tickArrayLower: { value: input.tickArrayLower ?? null, isWritable: true }, - tickArrayUpper: { value: input.tickArrayUpper ?? null, isWritable: true }, - personalPosition: { - value: input.personalPosition ?? null, - isWritable: true, - }, - tokenAccount0: { value: input.tokenAccount0 ?? null, isWritable: true }, - tokenAccount1: { value: input.tokenAccount1 ?? null, isWritable: true }, - tokenVault0: { value: input.tokenVault0 ?? null, isWritable: true }, - tokenVault1: { value: input.tokenVault1 ?? null, isWritable: true }, - rent: { value: input.rent ?? null, isWritable: false }, - systemProgram: { value: input.systemProgram ?? null, isWritable: false }, - tokenProgram: { value: input.tokenProgram ?? null, isWritable: false }, - associatedTokenProgram: { - value: input.associatedTokenProgram ?? null, - isWritable: false, - }, - metadataProgram: { - value: input.metadataProgram ?? null, - isWritable: false, - }, - }; - const accounts = originalAccounts as Record< - keyof typeof originalAccounts, - ResolvedAccount - >; - - // Original args. - const args = { ...input }; - - // Resolve default values. - if (!accounts.positionNftAccount.value) { - accounts.positionNftAccount.value = await getProgramDerivedAddress({ - programAddress: - 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>, - seeds: [ - getAddressEncoder().encode( - expectAddress(accounts.positionNftOwner.value) - ), - getBytesEncoder().encode( - new Uint8Array([ - 6, 221, 246, 225, 215, 101, 161, 147, 217, 203, 225, 70, 206, 235, - 121, 172, 28, 180, 133, 237, 95, 91, 55, 145, 58, 140, 245, 133, - 126, 255, 0, 169, - ]) - ), - getAddressEncoder().encode( - expectAddress(accounts.positionNftMint.value) - ), - ], - }); - } - if (!accounts.tickArrayLower.value) { - accounts.tickArrayLower.value = await getProgramDerivedAddress({ - programAddress, - seeds: [ - getBytesEncoder().encode( - new Uint8Array([116, 105, 99, 107, 95, 97, 114, 114, 97, 121]) - ), - getAddressEncoder().encode(expectAddress(accounts.poolState.value)), - getI32Encoder().encode(expectSome(args.tickArrayLowerStartIndex)), - ], - }); - } - if (!accounts.tickArrayUpper.value) { - accounts.tickArrayUpper.value = await getProgramDerivedAddress({ - programAddress, - seeds: [ - getBytesEncoder().encode( - new Uint8Array([116, 105, 99, 107, 95, 97, 114, 114, 97, 121]) - ), - getAddressEncoder().encode(expectAddress(accounts.poolState.value)), - getI32Encoder().encode(expectSome(args.tickArrayUpperStartIndex)), - ], - }); - } - if (!accounts.personalPosition.value) { - accounts.personalPosition.value = await getProgramDerivedAddress({ - programAddress, - seeds: [ - getBytesEncoder().encode( - new Uint8Array([112, 111, 115, 105, 116, 105, 111, 110]) - ), - getAddressEncoder().encode( - expectAddress(accounts.positionNftMint.value) - ), - ], - }); - } - if (!accounts.rent.value) { - accounts.rent.value = - 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>; - } - if (!accounts.systemProgram.value) { - accounts.systemProgram.value = - '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; - } - if (!accounts.tokenProgram.value) { - accounts.tokenProgram.value = - 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>; - } - if (!accounts.associatedTokenProgram.value) { - accounts.associatedTokenProgram.value = - 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>; - } - if (!accounts.metadataProgram.value) { - accounts.metadataProgram.value = - 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s' as Address<'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s'>; - } - - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); - return Object.freeze({ - accounts: [ - getAccountMeta(accounts.payer), - getAccountMeta(accounts.positionNftOwner), - getAccountMeta(accounts.positionNftMint), - getAccountMeta(accounts.positionNftAccount), - getAccountMeta(accounts.metadataAccount), - getAccountMeta(accounts.poolState), - getAccountMeta(accounts.protocolPosition), - getAccountMeta(accounts.tickArrayLower), - getAccountMeta(accounts.tickArrayUpper), - getAccountMeta(accounts.personalPosition), - getAccountMeta(accounts.tokenAccount0), - getAccountMeta(accounts.tokenAccount1), - getAccountMeta(accounts.tokenVault0), - getAccountMeta(accounts.tokenVault1), - getAccountMeta(accounts.rent), - getAccountMeta(accounts.systemProgram), - getAccountMeta(accounts.tokenProgram), - getAccountMeta(accounts.associatedTokenProgram), - getAccountMeta(accounts.metadataProgram), - ], - data: getOpenPositionInstructionDataEncoder().encode( - args as OpenPositionInstructionDataArgs - ), - programAddress, - } as OpenPositionInstruction< - TProgramAddress, - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram - >); -} - -export type OpenPositionInput< - TAccountPayer extends string = string, - TAccountPositionNftOwner extends string = string, - TAccountPositionNftMint extends string = string, - TAccountPositionNftAccount extends string = string, - TAccountMetadataAccount extends string = string, - TAccountPoolState extends string = string, - TAccountProtocolPosition extends string = string, - TAccountTickArrayLower extends string = string, - TAccountTickArrayUpper extends string = string, - TAccountPersonalPosition extends string = string, - TAccountTokenAccount0 extends string = string, - TAccountTokenAccount1 extends string = string, - TAccountTokenVault0 extends string = string, - TAccountTokenVault1 extends string = string, - TAccountRent extends string = string, - TAccountSystemProgram extends string = string, - TAccountTokenProgram extends string = string, - TAccountAssociatedTokenProgram extends string = string, - TAccountMetadataProgram extends string = string, -> = { - /** Pays to mint the position */ - payer: TransactionSigner; - positionNftOwner: Address; - /** Unique token mint address */ - positionNftMint: TransactionSigner; - /** - * Token account where position NFT will be minted - * This account created in the contract by cpi to avoid large stack variables - */ - positionNftAccount: Address; - /** To store metaplex metadata */ - metadataAccount: Address; - /** Add liquidity for this pool */ - poolState: Address; - protocolPosition: Address; - tickArrayLower: Address; - tickArrayUpper: Address; - /** personal position state */ - personalPosition: Address; - /** The token_0 account deposit token to the pool */ - tokenAccount0: Address; - /** The token_1 account deposit token to the pool */ - tokenAccount1: Address; - /** The address that holds pool tokens for token_0 */ - tokenVault0: Address; - /** The address that holds pool tokens for token_1 */ - tokenVault1: Address; - /** Sysvar for token mint and ATA creation */ - rent?: Address; - /** Program to create the position manager state account */ - systemProgram?: Address; - /** Program to create mint account and mint tokens */ - tokenProgram?: Address; - /** Program to create an ATA for receiving position NFT */ - associatedTokenProgram?: Address; - /** Program to create NFT metadata */ - metadataProgram?: Address; - tickLowerIndex: OpenPositionInstructionDataArgs['tickLowerIndex']; - tickUpperIndex: OpenPositionInstructionDataArgs['tickUpperIndex']; - tickArrayLowerStartIndex: OpenPositionInstructionDataArgs['tickArrayLowerStartIndex']; - tickArrayUpperStartIndex: OpenPositionInstructionDataArgs['tickArrayUpperStartIndex']; - liquidity: OpenPositionInstructionDataArgs['liquidity']; - amount0Max: OpenPositionInstructionDataArgs['amount0Max']; - amount1Max: OpenPositionInstructionDataArgs['amount1Max']; -}; - -export function getOpenPositionInstruction< - TAccountPayer extends string, - TAccountPositionNftOwner extends string, - TAccountPositionNftMint extends string, - TAccountPositionNftAccount extends string, - TAccountMetadataAccount extends string, - TAccountPoolState extends string, - TAccountProtocolPosition extends string, - TAccountTickArrayLower extends string, - TAccountTickArrayUpper extends string, - TAccountPersonalPosition extends string, - TAccountTokenAccount0 extends string, - TAccountTokenAccount1 extends string, - TAccountTokenVault0 extends string, - TAccountTokenVault1 extends string, - TAccountRent extends string, - TAccountSystemProgram extends string, - TAccountTokenProgram extends string, - TAccountAssociatedTokenProgram extends string, - TAccountMetadataProgram extends string, - TProgramAddress extends Address = typeof AMM_V3_PROGRAM_ADDRESS, ->( - input: OpenPositionInput< - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram - >, - config?: { programAddress?: TProgramAddress } -): OpenPositionInstruction< - TProgramAddress, - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram -> { - // Program address. - const programAddress = config?.programAddress ?? AMM_V3_PROGRAM_ADDRESS; - - // Original accounts. - const originalAccounts = { - payer: { value: input.payer ?? null, isWritable: true }, - positionNftOwner: { - value: input.positionNftOwner ?? null, - isWritable: false, - }, - positionNftMint: { value: input.positionNftMint ?? null, isWritable: true }, - positionNftAccount: { - value: input.positionNftAccount ?? null, - isWritable: true, - }, - metadataAccount: { value: input.metadataAccount ?? null, isWritable: true }, - poolState: { value: input.poolState ?? null, isWritable: true }, - protocolPosition: { - value: input.protocolPosition ?? null, - isWritable: false, - }, - tickArrayLower: { value: input.tickArrayLower ?? null, isWritable: true }, - tickArrayUpper: { value: input.tickArrayUpper ?? null, isWritable: true }, - personalPosition: { - value: input.personalPosition ?? null, - isWritable: true, - }, - tokenAccount0: { value: input.tokenAccount0 ?? null, isWritable: true }, - tokenAccount1: { value: input.tokenAccount1 ?? null, isWritable: true }, - tokenVault0: { value: input.tokenVault0 ?? null, isWritable: true }, - tokenVault1: { value: input.tokenVault1 ?? null, isWritable: true }, - rent: { value: input.rent ?? null, isWritable: false }, - systemProgram: { value: input.systemProgram ?? null, isWritable: false }, - tokenProgram: { value: input.tokenProgram ?? null, isWritable: false }, - associatedTokenProgram: { - value: input.associatedTokenProgram ?? null, - isWritable: false, - }, - metadataProgram: { - value: input.metadataProgram ?? null, - isWritable: false, - }, - }; - const accounts = originalAccounts as Record< - keyof typeof originalAccounts, - ResolvedAccount - >; - - // Original args. - const args = { ...input }; - - // Resolve default values. - if (!accounts.rent.value) { - accounts.rent.value = - 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>; - } - if (!accounts.systemProgram.value) { - accounts.systemProgram.value = - '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; - } - if (!accounts.tokenProgram.value) { - accounts.tokenProgram.value = - 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>; - } - if (!accounts.associatedTokenProgram.value) { - accounts.associatedTokenProgram.value = - 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>; - } - if (!accounts.metadataProgram.value) { - accounts.metadataProgram.value = - 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s' as Address<'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s'>; - } - - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); - return Object.freeze({ - accounts: [ - getAccountMeta(accounts.payer), - getAccountMeta(accounts.positionNftOwner), - getAccountMeta(accounts.positionNftMint), - getAccountMeta(accounts.positionNftAccount), - getAccountMeta(accounts.metadataAccount), - getAccountMeta(accounts.poolState), - getAccountMeta(accounts.protocolPosition), - getAccountMeta(accounts.tickArrayLower), - getAccountMeta(accounts.tickArrayUpper), - getAccountMeta(accounts.personalPosition), - getAccountMeta(accounts.tokenAccount0), - getAccountMeta(accounts.tokenAccount1), - getAccountMeta(accounts.tokenVault0), - getAccountMeta(accounts.tokenVault1), - getAccountMeta(accounts.rent), - getAccountMeta(accounts.systemProgram), - getAccountMeta(accounts.tokenProgram), - getAccountMeta(accounts.associatedTokenProgram), - getAccountMeta(accounts.metadataProgram), - ], - data: getOpenPositionInstructionDataEncoder().encode( - args as OpenPositionInstructionDataArgs - ), - programAddress, - } as OpenPositionInstruction< - TProgramAddress, - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram - >); -} - -export type ParsedOpenPositionInstruction< - TProgram extends string = typeof AMM_V3_PROGRAM_ADDRESS, - TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[], -> = { - programAddress: Address; - accounts: { - /** Pays to mint the position */ - payer: TAccountMetas[0]; - positionNftOwner: TAccountMetas[1]; - /** Unique token mint address */ - positionNftMint: TAccountMetas[2]; - /** - * Token account where position NFT will be minted - * This account created in the contract by cpi to avoid large stack variables - */ - positionNftAccount: TAccountMetas[3]; - /** To store metaplex metadata */ - metadataAccount: TAccountMetas[4]; - /** Add liquidity for this pool */ - poolState: TAccountMetas[5]; - protocolPosition: TAccountMetas[6]; - tickArrayLower: TAccountMetas[7]; - tickArrayUpper: TAccountMetas[8]; - /** personal position state */ - personalPosition: TAccountMetas[9]; - /** The token_0 account deposit token to the pool */ - tokenAccount0: TAccountMetas[10]; - /** The token_1 account deposit token to the pool */ - tokenAccount1: TAccountMetas[11]; - /** The address that holds pool tokens for token_0 */ - tokenVault0: TAccountMetas[12]; - /** The address that holds pool tokens for token_1 */ - tokenVault1: TAccountMetas[13]; - /** Sysvar for token mint and ATA creation */ - rent: TAccountMetas[14]; - /** Program to create the position manager state account */ - systemProgram: TAccountMetas[15]; - /** Program to create mint account and mint tokens */ - tokenProgram: TAccountMetas[16]; - /** Program to create an ATA for receiving position NFT */ - associatedTokenProgram: TAccountMetas[17]; - /** Program to create NFT metadata */ - metadataProgram: TAccountMetas[18]; - }; - data: OpenPositionInstructionData; -}; - -export function parseOpenPositionInstruction< - TProgram extends string, - TAccountMetas extends readonly AccountMeta[], ->( - instruction: Instruction & - InstructionWithAccounts & - InstructionWithData -): ParsedOpenPositionInstruction { - if (instruction.accounts.length < 19) { - // TODO: Coded error. - throw new Error('Not enough accounts'); - } - let accountIndex = 0; - const getNextAccount = () => { - const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!; - accountIndex += 1; - return accountMeta; - }; - return { - programAddress: instruction.programAddress, - accounts: { - payer: getNextAccount(), - positionNftOwner: getNextAccount(), - positionNftMint: getNextAccount(), - positionNftAccount: getNextAccount(), - metadataAccount: getNextAccount(), - poolState: getNextAccount(), - protocolPosition: getNextAccount(), - tickArrayLower: getNextAccount(), - tickArrayUpper: getNextAccount(), - personalPosition: getNextAccount(), - tokenAccount0: getNextAccount(), - tokenAccount1: getNextAccount(), - tokenVault0: getNextAccount(), - tokenVault1: getNextAccount(), - rent: getNextAccount(), - systemProgram: getNextAccount(), - tokenProgram: getNextAccount(), - associatedTokenProgram: getNextAccount(), - metadataProgram: getNextAccount(), - }, - data: getOpenPositionInstructionDataDecoder().decode(instruction.data), - }; -} diff --git a/sdk/src/generated/instructions/openPositionV2.ts b/sdk/src/generated/instructions/openPositionV2.ts deleted file mode 100644 index 1572fe4..0000000 --- a/sdk/src/generated/instructions/openPositionV2.ts +++ /dev/null @@ -1,982 +0,0 @@ -/** - * This code was AUTOGENERATED using the Codama library. - * Please DO NOT EDIT THIS FILE, instead use visitors - * to add features, then rerun Codama to update it. - * - * @see https://github.com/codama-idl/codama - */ - -import { - combineCodec, - fixDecoderSize, - fixEncoderSize, - getAddressEncoder, - getBooleanDecoder, - getBooleanEncoder, - getBytesDecoder, - getBytesEncoder, - getI32Decoder, - getI32Encoder, - getOptionDecoder, - getOptionEncoder, - getProgramDerivedAddress, - getStructDecoder, - getStructEncoder, - getU128Decoder, - getU128Encoder, - getU64Decoder, - getU64Encoder, - transformEncoder, - type AccountMeta, - type AccountSignerMeta, - type Address, - type Codec, - type Decoder, - type Encoder, - type Instruction, - type InstructionWithAccounts, - type InstructionWithData, - type Option, - type OptionOrNullable, - type ReadonlyAccount, - type ReadonlyUint8Array, - type TransactionSigner, - type WritableAccount, - type WritableSignerAccount, -} from '@solana/kit'; -import { AMM_V3_PROGRAM_ADDRESS } from '../programs'; -import { - expectAddress, - expectSome, - getAccountMetaFactory, - type ResolvedAccount, -} from '../shared'; - -export const OPEN_POSITION_V2_DISCRIMINATOR = new Uint8Array([ - 77, 184, 74, 214, 112, 86, 241, 199, -]); - -export function getOpenPositionV2DiscriminatorBytes() { - return fixEncoderSize(getBytesEncoder(), 8).encode( - OPEN_POSITION_V2_DISCRIMINATOR - ); -} - -export type OpenPositionV2Instruction< - TProgram extends string = typeof AMM_V3_PROGRAM_ADDRESS, - TAccountPayer extends string | AccountMeta = string, - TAccountPositionNftOwner extends string | AccountMeta = string, - TAccountPositionNftMint extends string | AccountMeta = string, - TAccountPositionNftAccount extends string | AccountMeta = string, - TAccountMetadataAccount extends string | AccountMeta = string, - TAccountPoolState extends string | AccountMeta = string, - TAccountProtocolPosition extends string | AccountMeta = string, - TAccountTickArrayLower extends string | AccountMeta = string, - TAccountTickArrayUpper extends string | AccountMeta = string, - TAccountPersonalPosition extends string | AccountMeta = string, - TAccountTokenAccount0 extends string | AccountMeta = string, - TAccountTokenAccount1 extends string | AccountMeta = string, - TAccountTokenVault0 extends string | AccountMeta = string, - TAccountTokenVault1 extends string | AccountMeta = string, - TAccountRent extends - | string - | AccountMeta = 'SysvarRent111111111111111111111111111111111', - TAccountSystemProgram extends - | string - | AccountMeta = '11111111111111111111111111111111', - TAccountTokenProgram extends - | string - | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - TAccountAssociatedTokenProgram extends - | string - | AccountMeta = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', - TAccountMetadataProgram extends - | string - | AccountMeta = 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', - TAccountTokenProgram2022 extends - | string - | AccountMeta = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb', - TAccountVault0Mint extends string | AccountMeta = string, - TAccountVault1Mint extends string | AccountMeta = string, - TRemainingAccounts extends readonly AccountMeta[] = [], -> = Instruction & - InstructionWithData & - InstructionWithAccounts< - [ - TAccountPayer extends string - ? WritableSignerAccount & - AccountSignerMeta - : TAccountPayer, - TAccountPositionNftOwner extends string - ? ReadonlyAccount - : TAccountPositionNftOwner, - TAccountPositionNftMint extends string - ? WritableSignerAccount & - AccountSignerMeta - : TAccountPositionNftMint, - TAccountPositionNftAccount extends string - ? WritableAccount - : TAccountPositionNftAccount, - TAccountMetadataAccount extends string - ? WritableAccount - : TAccountMetadataAccount, - TAccountPoolState extends string - ? WritableAccount - : TAccountPoolState, - TAccountProtocolPosition extends string - ? ReadonlyAccount - : TAccountProtocolPosition, - TAccountTickArrayLower extends string - ? WritableAccount - : TAccountTickArrayLower, - TAccountTickArrayUpper extends string - ? WritableAccount - : TAccountTickArrayUpper, - TAccountPersonalPosition extends string - ? WritableAccount - : TAccountPersonalPosition, - TAccountTokenAccount0 extends string - ? WritableAccount - : TAccountTokenAccount0, - TAccountTokenAccount1 extends string - ? WritableAccount - : TAccountTokenAccount1, - TAccountTokenVault0 extends string - ? WritableAccount - : TAccountTokenVault0, - TAccountTokenVault1 extends string - ? WritableAccount - : TAccountTokenVault1, - TAccountRent extends string - ? ReadonlyAccount - : TAccountRent, - TAccountSystemProgram extends string - ? ReadonlyAccount - : TAccountSystemProgram, - TAccountTokenProgram extends string - ? ReadonlyAccount - : TAccountTokenProgram, - TAccountAssociatedTokenProgram extends string - ? ReadonlyAccount - : TAccountAssociatedTokenProgram, - TAccountMetadataProgram extends string - ? ReadonlyAccount - : TAccountMetadataProgram, - TAccountTokenProgram2022 extends string - ? ReadonlyAccount - : TAccountTokenProgram2022, - TAccountVault0Mint extends string - ? ReadonlyAccount - : TAccountVault0Mint, - TAccountVault1Mint extends string - ? ReadonlyAccount - : TAccountVault1Mint, - ...TRemainingAccounts, - ] - >; - -export type OpenPositionV2InstructionData = { - discriminator: ReadonlyUint8Array; - tickLowerIndex: number; - tickUpperIndex: number; - tickArrayLowerStartIndex: number; - tickArrayUpperStartIndex: number; - liquidity: bigint; - amount0Max: bigint; - amount1Max: bigint; - withMetadata: boolean; - baseFlag: Option; -}; - -export type OpenPositionV2InstructionDataArgs = { - tickLowerIndex: number; - tickUpperIndex: number; - tickArrayLowerStartIndex: number; - tickArrayUpperStartIndex: number; - liquidity: number | bigint; - amount0Max: number | bigint; - amount1Max: number | bigint; - withMetadata: boolean; - baseFlag: OptionOrNullable; -}; - -export function getOpenPositionV2InstructionDataEncoder(): Encoder { - return transformEncoder( - getStructEncoder([ - ['discriminator', fixEncoderSize(getBytesEncoder(), 8)], - ['tickLowerIndex', getI32Encoder()], - ['tickUpperIndex', getI32Encoder()], - ['tickArrayLowerStartIndex', getI32Encoder()], - ['tickArrayUpperStartIndex', getI32Encoder()], - ['liquidity', getU128Encoder()], - ['amount0Max', getU64Encoder()], - ['amount1Max', getU64Encoder()], - ['withMetadata', getBooleanEncoder()], - ['baseFlag', getOptionEncoder(getBooleanEncoder())], - ]), - (value) => ({ ...value, discriminator: OPEN_POSITION_V2_DISCRIMINATOR }) - ); -} - -export function getOpenPositionV2InstructionDataDecoder(): Decoder { - return getStructDecoder([ - ['discriminator', fixDecoderSize(getBytesDecoder(), 8)], - ['tickLowerIndex', getI32Decoder()], - ['tickUpperIndex', getI32Decoder()], - ['tickArrayLowerStartIndex', getI32Decoder()], - ['tickArrayUpperStartIndex', getI32Decoder()], - ['liquidity', getU128Decoder()], - ['amount0Max', getU64Decoder()], - ['amount1Max', getU64Decoder()], - ['withMetadata', getBooleanDecoder()], - ['baseFlag', getOptionDecoder(getBooleanDecoder())], - ]); -} - -export function getOpenPositionV2InstructionDataCodec(): Codec< - OpenPositionV2InstructionDataArgs, - OpenPositionV2InstructionData -> { - return combineCodec( - getOpenPositionV2InstructionDataEncoder(), - getOpenPositionV2InstructionDataDecoder() - ); -} - -export type OpenPositionV2AsyncInput< - TAccountPayer extends string = string, - TAccountPositionNftOwner extends string = string, - TAccountPositionNftMint extends string = string, - TAccountPositionNftAccount extends string = string, - TAccountMetadataAccount extends string = string, - TAccountPoolState extends string = string, - TAccountProtocolPosition extends string = string, - TAccountTickArrayLower extends string = string, - TAccountTickArrayUpper extends string = string, - TAccountPersonalPosition extends string = string, - TAccountTokenAccount0 extends string = string, - TAccountTokenAccount1 extends string = string, - TAccountTokenVault0 extends string = string, - TAccountTokenVault1 extends string = string, - TAccountRent extends string = string, - TAccountSystemProgram extends string = string, - TAccountTokenProgram extends string = string, - TAccountAssociatedTokenProgram extends string = string, - TAccountMetadataProgram extends string = string, - TAccountTokenProgram2022 extends string = string, - TAccountVault0Mint extends string = string, - TAccountVault1Mint extends string = string, -> = { - /** Pays to mint the position */ - payer: TransactionSigner; - positionNftOwner: Address; - /** Unique token mint address */ - positionNftMint: TransactionSigner; - /** Token account where position NFT will be minted */ - positionNftAccount?: Address; - /** To store metaplex metadata */ - metadataAccount: Address; - /** Add liquidity for this pool */ - poolState: Address; - protocolPosition: Address; - tickArrayLower?: Address; - tickArrayUpper?: Address; - /** personal position state */ - personalPosition?: Address; - /** The token_0 account deposit token to the pool */ - tokenAccount0: Address; - /** The token_1 account deposit token to the pool */ - tokenAccount1: Address; - /** The address that holds pool tokens for token_0 */ - tokenVault0: Address; - /** The address that holds pool tokens for token_1 */ - tokenVault1: Address; - /** Sysvar for token mint and ATA creation */ - rent?: Address; - /** Program to create the position manager state account */ - systemProgram?: Address; - /** Program to create mint account and mint tokens */ - tokenProgram?: Address; - /** Program to create an ATA for receiving position NFT */ - associatedTokenProgram?: Address; - /** Program to create NFT metadata */ - metadataProgram?: Address; - /** Program to create mint account and mint tokens */ - tokenProgram2022?: Address; - /** The mint of token vault 0 */ - vault0Mint: Address; - /** The mint of token vault 1 */ - vault1Mint: Address; - tickLowerIndex: OpenPositionV2InstructionDataArgs['tickLowerIndex']; - tickUpperIndex: OpenPositionV2InstructionDataArgs['tickUpperIndex']; - tickArrayLowerStartIndex: OpenPositionV2InstructionDataArgs['tickArrayLowerStartIndex']; - tickArrayUpperStartIndex: OpenPositionV2InstructionDataArgs['tickArrayUpperStartIndex']; - liquidity: OpenPositionV2InstructionDataArgs['liquidity']; - amount0Max: OpenPositionV2InstructionDataArgs['amount0Max']; - amount1Max: OpenPositionV2InstructionDataArgs['amount1Max']; - withMetadata: OpenPositionV2InstructionDataArgs['withMetadata']; - baseFlag: OpenPositionV2InstructionDataArgs['baseFlag']; -}; - -export async function getOpenPositionV2InstructionAsync< - TAccountPayer extends string, - TAccountPositionNftOwner extends string, - TAccountPositionNftMint extends string, - TAccountPositionNftAccount extends string, - TAccountMetadataAccount extends string, - TAccountPoolState extends string, - TAccountProtocolPosition extends string, - TAccountTickArrayLower extends string, - TAccountTickArrayUpper extends string, - TAccountPersonalPosition extends string, - TAccountTokenAccount0 extends string, - TAccountTokenAccount1 extends string, - TAccountTokenVault0 extends string, - TAccountTokenVault1 extends string, - TAccountRent extends string, - TAccountSystemProgram extends string, - TAccountTokenProgram extends string, - TAccountAssociatedTokenProgram extends string, - TAccountMetadataProgram extends string, - TAccountTokenProgram2022 extends string, - TAccountVault0Mint extends string, - TAccountVault1Mint extends string, - TProgramAddress extends Address = typeof AMM_V3_PROGRAM_ADDRESS, ->( - input: OpenPositionV2AsyncInput< - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram, - TAccountTokenProgram2022, - TAccountVault0Mint, - TAccountVault1Mint - >, - config?: { programAddress?: TProgramAddress } -): Promise< - OpenPositionV2Instruction< - TProgramAddress, - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram, - TAccountTokenProgram2022, - TAccountVault0Mint, - TAccountVault1Mint - > -> { - // Program address. - const programAddress = config?.programAddress ?? AMM_V3_PROGRAM_ADDRESS; - - // Original accounts. - const originalAccounts = { - payer: { value: input.payer ?? null, isWritable: true }, - positionNftOwner: { - value: input.positionNftOwner ?? null, - isWritable: false, - }, - positionNftMint: { value: input.positionNftMint ?? null, isWritable: true }, - positionNftAccount: { - value: input.positionNftAccount ?? null, - isWritable: true, - }, - metadataAccount: { value: input.metadataAccount ?? null, isWritable: true }, - poolState: { value: input.poolState ?? null, isWritable: true }, - protocolPosition: { - value: input.protocolPosition ?? null, - isWritable: false, - }, - tickArrayLower: { value: input.tickArrayLower ?? null, isWritable: true }, - tickArrayUpper: { value: input.tickArrayUpper ?? null, isWritable: true }, - personalPosition: { - value: input.personalPosition ?? null, - isWritable: true, - }, - tokenAccount0: { value: input.tokenAccount0 ?? null, isWritable: true }, - tokenAccount1: { value: input.tokenAccount1 ?? null, isWritable: true }, - tokenVault0: { value: input.tokenVault0 ?? null, isWritable: true }, - tokenVault1: { value: input.tokenVault1 ?? null, isWritable: true }, - rent: { value: input.rent ?? null, isWritable: false }, - systemProgram: { value: input.systemProgram ?? null, isWritable: false }, - tokenProgram: { value: input.tokenProgram ?? null, isWritable: false }, - associatedTokenProgram: { - value: input.associatedTokenProgram ?? null, - isWritable: false, - }, - metadataProgram: { - value: input.metadataProgram ?? null, - isWritable: false, - }, - tokenProgram2022: { - value: input.tokenProgram2022 ?? null, - isWritable: false, - }, - vault0Mint: { value: input.vault0Mint ?? null, isWritable: false }, - vault1Mint: { value: input.vault1Mint ?? null, isWritable: false }, - }; - const accounts = originalAccounts as Record< - keyof typeof originalAccounts, - ResolvedAccount - >; - - // Original args. - const args = { ...input }; - - // Resolve default values. - if (!accounts.positionNftAccount.value) { - accounts.positionNftAccount.value = await getProgramDerivedAddress({ - programAddress: - 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>, - seeds: [ - getAddressEncoder().encode( - expectAddress(accounts.positionNftOwner.value) - ), - getBytesEncoder().encode( - new Uint8Array([ - 6, 221, 246, 225, 215, 101, 161, 147, 217, 203, 225, 70, 206, 235, - 121, 172, 28, 180, 133, 237, 95, 91, 55, 145, 58, 140, 245, 133, - 126, 255, 0, 169, - ]) - ), - getAddressEncoder().encode( - expectAddress(accounts.positionNftMint.value) - ), - ], - }); - } - if (!accounts.tickArrayLower.value) { - accounts.tickArrayLower.value = await getProgramDerivedAddress({ - programAddress, - seeds: [ - getBytesEncoder().encode( - new Uint8Array([116, 105, 99, 107, 95, 97, 114, 114, 97, 121]) - ), - getAddressEncoder().encode(expectAddress(accounts.poolState.value)), - getI32Encoder().encode(expectSome(args.tickArrayLowerStartIndex)), - ], - }); - } - if (!accounts.tickArrayUpper.value) { - accounts.tickArrayUpper.value = await getProgramDerivedAddress({ - programAddress, - seeds: [ - getBytesEncoder().encode( - new Uint8Array([116, 105, 99, 107, 95, 97, 114, 114, 97, 121]) - ), - getAddressEncoder().encode(expectAddress(accounts.poolState.value)), - getI32Encoder().encode(expectSome(args.tickArrayUpperStartIndex)), - ], - }); - } - if (!accounts.personalPosition.value) { - accounts.personalPosition.value = await getProgramDerivedAddress({ - programAddress, - seeds: [ - getBytesEncoder().encode( - new Uint8Array([112, 111, 115, 105, 116, 105, 111, 110]) - ), - getAddressEncoder().encode( - expectAddress(accounts.positionNftMint.value) - ), - ], - }); - } - if (!accounts.rent.value) { - accounts.rent.value = - 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>; - } - if (!accounts.systemProgram.value) { - accounts.systemProgram.value = - '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; - } - if (!accounts.tokenProgram.value) { - accounts.tokenProgram.value = - 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>; - } - if (!accounts.associatedTokenProgram.value) { - accounts.associatedTokenProgram.value = - 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>; - } - if (!accounts.metadataProgram.value) { - accounts.metadataProgram.value = - 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s' as Address<'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s'>; - } - if (!accounts.tokenProgram2022.value) { - accounts.tokenProgram2022.value = - 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>; - } - - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); - return Object.freeze({ - accounts: [ - getAccountMeta(accounts.payer), - getAccountMeta(accounts.positionNftOwner), - getAccountMeta(accounts.positionNftMint), - getAccountMeta(accounts.positionNftAccount), - getAccountMeta(accounts.metadataAccount), - getAccountMeta(accounts.poolState), - getAccountMeta(accounts.protocolPosition), - getAccountMeta(accounts.tickArrayLower), - getAccountMeta(accounts.tickArrayUpper), - getAccountMeta(accounts.personalPosition), - getAccountMeta(accounts.tokenAccount0), - getAccountMeta(accounts.tokenAccount1), - getAccountMeta(accounts.tokenVault0), - getAccountMeta(accounts.tokenVault1), - getAccountMeta(accounts.rent), - getAccountMeta(accounts.systemProgram), - getAccountMeta(accounts.tokenProgram), - getAccountMeta(accounts.associatedTokenProgram), - getAccountMeta(accounts.metadataProgram), - getAccountMeta(accounts.tokenProgram2022), - getAccountMeta(accounts.vault0Mint), - getAccountMeta(accounts.vault1Mint), - ], - data: getOpenPositionV2InstructionDataEncoder().encode( - args as OpenPositionV2InstructionDataArgs - ), - programAddress, - } as OpenPositionV2Instruction< - TProgramAddress, - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram, - TAccountTokenProgram2022, - TAccountVault0Mint, - TAccountVault1Mint - >); -} - -export type OpenPositionV2Input< - TAccountPayer extends string = string, - TAccountPositionNftOwner extends string = string, - TAccountPositionNftMint extends string = string, - TAccountPositionNftAccount extends string = string, - TAccountMetadataAccount extends string = string, - TAccountPoolState extends string = string, - TAccountProtocolPosition extends string = string, - TAccountTickArrayLower extends string = string, - TAccountTickArrayUpper extends string = string, - TAccountPersonalPosition extends string = string, - TAccountTokenAccount0 extends string = string, - TAccountTokenAccount1 extends string = string, - TAccountTokenVault0 extends string = string, - TAccountTokenVault1 extends string = string, - TAccountRent extends string = string, - TAccountSystemProgram extends string = string, - TAccountTokenProgram extends string = string, - TAccountAssociatedTokenProgram extends string = string, - TAccountMetadataProgram extends string = string, - TAccountTokenProgram2022 extends string = string, - TAccountVault0Mint extends string = string, - TAccountVault1Mint extends string = string, -> = { - /** Pays to mint the position */ - payer: TransactionSigner; - positionNftOwner: Address; - /** Unique token mint address */ - positionNftMint: TransactionSigner; - /** Token account where position NFT will be minted */ - positionNftAccount: Address; - /** To store metaplex metadata */ - metadataAccount: Address; - /** Add liquidity for this pool */ - poolState: Address; - protocolPosition: Address; - tickArrayLower: Address; - tickArrayUpper: Address; - /** personal position state */ - personalPosition: Address; - /** The token_0 account deposit token to the pool */ - tokenAccount0: Address; - /** The token_1 account deposit token to the pool */ - tokenAccount1: Address; - /** The address that holds pool tokens for token_0 */ - tokenVault0: Address; - /** The address that holds pool tokens for token_1 */ - tokenVault1: Address; - /** Sysvar for token mint and ATA creation */ - rent?: Address; - /** Program to create the position manager state account */ - systemProgram?: Address; - /** Program to create mint account and mint tokens */ - tokenProgram?: Address; - /** Program to create an ATA for receiving position NFT */ - associatedTokenProgram?: Address; - /** Program to create NFT metadata */ - metadataProgram?: Address; - /** Program to create mint account and mint tokens */ - tokenProgram2022?: Address; - /** The mint of token vault 0 */ - vault0Mint: Address; - /** The mint of token vault 1 */ - vault1Mint: Address; - tickLowerIndex: OpenPositionV2InstructionDataArgs['tickLowerIndex']; - tickUpperIndex: OpenPositionV2InstructionDataArgs['tickUpperIndex']; - tickArrayLowerStartIndex: OpenPositionV2InstructionDataArgs['tickArrayLowerStartIndex']; - tickArrayUpperStartIndex: OpenPositionV2InstructionDataArgs['tickArrayUpperStartIndex']; - liquidity: OpenPositionV2InstructionDataArgs['liquidity']; - amount0Max: OpenPositionV2InstructionDataArgs['amount0Max']; - amount1Max: OpenPositionV2InstructionDataArgs['amount1Max']; - withMetadata: OpenPositionV2InstructionDataArgs['withMetadata']; - baseFlag: OpenPositionV2InstructionDataArgs['baseFlag']; -}; - -export function getOpenPositionV2Instruction< - TAccountPayer extends string, - TAccountPositionNftOwner extends string, - TAccountPositionNftMint extends string, - TAccountPositionNftAccount extends string, - TAccountMetadataAccount extends string, - TAccountPoolState extends string, - TAccountProtocolPosition extends string, - TAccountTickArrayLower extends string, - TAccountTickArrayUpper extends string, - TAccountPersonalPosition extends string, - TAccountTokenAccount0 extends string, - TAccountTokenAccount1 extends string, - TAccountTokenVault0 extends string, - TAccountTokenVault1 extends string, - TAccountRent extends string, - TAccountSystemProgram extends string, - TAccountTokenProgram extends string, - TAccountAssociatedTokenProgram extends string, - TAccountMetadataProgram extends string, - TAccountTokenProgram2022 extends string, - TAccountVault0Mint extends string, - TAccountVault1Mint extends string, - TProgramAddress extends Address = typeof AMM_V3_PROGRAM_ADDRESS, ->( - input: OpenPositionV2Input< - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram, - TAccountTokenProgram2022, - TAccountVault0Mint, - TAccountVault1Mint - >, - config?: { programAddress?: TProgramAddress } -): OpenPositionV2Instruction< - TProgramAddress, - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram, - TAccountTokenProgram2022, - TAccountVault0Mint, - TAccountVault1Mint -> { - // Program address. - const programAddress = config?.programAddress ?? AMM_V3_PROGRAM_ADDRESS; - - // Original accounts. - const originalAccounts = { - payer: { value: input.payer ?? null, isWritable: true }, - positionNftOwner: { - value: input.positionNftOwner ?? null, - isWritable: false, - }, - positionNftMint: { value: input.positionNftMint ?? null, isWritable: true }, - positionNftAccount: { - value: input.positionNftAccount ?? null, - isWritable: true, - }, - metadataAccount: { value: input.metadataAccount ?? null, isWritable: true }, - poolState: { value: input.poolState ?? null, isWritable: true }, - protocolPosition: { - value: input.protocolPosition ?? null, - isWritable: false, - }, - tickArrayLower: { value: input.tickArrayLower ?? null, isWritable: true }, - tickArrayUpper: { value: input.tickArrayUpper ?? null, isWritable: true }, - personalPosition: { - value: input.personalPosition ?? null, - isWritable: true, - }, - tokenAccount0: { value: input.tokenAccount0 ?? null, isWritable: true }, - tokenAccount1: { value: input.tokenAccount1 ?? null, isWritable: true }, - tokenVault0: { value: input.tokenVault0 ?? null, isWritable: true }, - tokenVault1: { value: input.tokenVault1 ?? null, isWritable: true }, - rent: { value: input.rent ?? null, isWritable: false }, - systemProgram: { value: input.systemProgram ?? null, isWritable: false }, - tokenProgram: { value: input.tokenProgram ?? null, isWritable: false }, - associatedTokenProgram: { - value: input.associatedTokenProgram ?? null, - isWritable: false, - }, - metadataProgram: { - value: input.metadataProgram ?? null, - isWritable: false, - }, - tokenProgram2022: { - value: input.tokenProgram2022 ?? null, - isWritable: false, - }, - vault0Mint: { value: input.vault0Mint ?? null, isWritable: false }, - vault1Mint: { value: input.vault1Mint ?? null, isWritable: false }, - }; - const accounts = originalAccounts as Record< - keyof typeof originalAccounts, - ResolvedAccount - >; - - // Original args. - const args = { ...input }; - - // Resolve default values. - if (!accounts.rent.value) { - accounts.rent.value = - 'SysvarRent111111111111111111111111111111111' as Address<'SysvarRent111111111111111111111111111111111'>; - } - if (!accounts.systemProgram.value) { - accounts.systemProgram.value = - '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; - } - if (!accounts.tokenProgram.value) { - accounts.tokenProgram.value = - 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>; - } - if (!accounts.associatedTokenProgram.value) { - accounts.associatedTokenProgram.value = - 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address<'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'>; - } - if (!accounts.metadataProgram.value) { - accounts.metadataProgram.value = - 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s' as Address<'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s'>; - } - if (!accounts.tokenProgram2022.value) { - accounts.tokenProgram2022.value = - 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address<'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'>; - } - - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); - return Object.freeze({ - accounts: [ - getAccountMeta(accounts.payer), - getAccountMeta(accounts.positionNftOwner), - getAccountMeta(accounts.positionNftMint), - getAccountMeta(accounts.positionNftAccount), - getAccountMeta(accounts.metadataAccount), - getAccountMeta(accounts.poolState), - getAccountMeta(accounts.protocolPosition), - getAccountMeta(accounts.tickArrayLower), - getAccountMeta(accounts.tickArrayUpper), - getAccountMeta(accounts.personalPosition), - getAccountMeta(accounts.tokenAccount0), - getAccountMeta(accounts.tokenAccount1), - getAccountMeta(accounts.tokenVault0), - getAccountMeta(accounts.tokenVault1), - getAccountMeta(accounts.rent), - getAccountMeta(accounts.systemProgram), - getAccountMeta(accounts.tokenProgram), - getAccountMeta(accounts.associatedTokenProgram), - getAccountMeta(accounts.metadataProgram), - getAccountMeta(accounts.tokenProgram2022), - getAccountMeta(accounts.vault0Mint), - getAccountMeta(accounts.vault1Mint), - ], - data: getOpenPositionV2InstructionDataEncoder().encode( - args as OpenPositionV2InstructionDataArgs - ), - programAddress, - } as OpenPositionV2Instruction< - TProgramAddress, - TAccountPayer, - TAccountPositionNftOwner, - TAccountPositionNftMint, - TAccountPositionNftAccount, - TAccountMetadataAccount, - TAccountPoolState, - TAccountProtocolPosition, - TAccountTickArrayLower, - TAccountTickArrayUpper, - TAccountPersonalPosition, - TAccountTokenAccount0, - TAccountTokenAccount1, - TAccountTokenVault0, - TAccountTokenVault1, - TAccountRent, - TAccountSystemProgram, - TAccountTokenProgram, - TAccountAssociatedTokenProgram, - TAccountMetadataProgram, - TAccountTokenProgram2022, - TAccountVault0Mint, - TAccountVault1Mint - >); -} - -export type ParsedOpenPositionV2Instruction< - TProgram extends string = typeof AMM_V3_PROGRAM_ADDRESS, - TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[], -> = { - programAddress: Address; - accounts: { - /** Pays to mint the position */ - payer: TAccountMetas[0]; - positionNftOwner: TAccountMetas[1]; - /** Unique token mint address */ - positionNftMint: TAccountMetas[2]; - /** Token account where position NFT will be minted */ - positionNftAccount: TAccountMetas[3]; - /** To store metaplex metadata */ - metadataAccount: TAccountMetas[4]; - /** Add liquidity for this pool */ - poolState: TAccountMetas[5]; - protocolPosition: TAccountMetas[6]; - tickArrayLower: TAccountMetas[7]; - tickArrayUpper: TAccountMetas[8]; - /** personal position state */ - personalPosition: TAccountMetas[9]; - /** The token_0 account deposit token to the pool */ - tokenAccount0: TAccountMetas[10]; - /** The token_1 account deposit token to the pool */ - tokenAccount1: TAccountMetas[11]; - /** The address that holds pool tokens for token_0 */ - tokenVault0: TAccountMetas[12]; - /** The address that holds pool tokens for token_1 */ - tokenVault1: TAccountMetas[13]; - /** Sysvar for token mint and ATA creation */ - rent: TAccountMetas[14]; - /** Program to create the position manager state account */ - systemProgram: TAccountMetas[15]; - /** Program to create mint account and mint tokens */ - tokenProgram: TAccountMetas[16]; - /** Program to create an ATA for receiving position NFT */ - associatedTokenProgram: TAccountMetas[17]; - /** Program to create NFT metadata */ - metadataProgram: TAccountMetas[18]; - /** Program to create mint account and mint tokens */ - tokenProgram2022: TAccountMetas[19]; - /** The mint of token vault 0 */ - vault0Mint: TAccountMetas[20]; - /** The mint of token vault 1 */ - vault1Mint: TAccountMetas[21]; - }; - data: OpenPositionV2InstructionData; -}; - -export function parseOpenPositionV2Instruction< - TProgram extends string, - TAccountMetas extends readonly AccountMeta[], ->( - instruction: Instruction & - InstructionWithAccounts & - InstructionWithData -): ParsedOpenPositionV2Instruction { - if (instruction.accounts.length < 22) { - // TODO: Coded error. - throw new Error('Not enough accounts'); - } - let accountIndex = 0; - const getNextAccount = () => { - const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!; - accountIndex += 1; - return accountMeta; - }; - return { - programAddress: instruction.programAddress, - accounts: { - payer: getNextAccount(), - positionNftOwner: getNextAccount(), - positionNftMint: getNextAccount(), - positionNftAccount: getNextAccount(), - metadataAccount: getNextAccount(), - poolState: getNextAccount(), - protocolPosition: getNextAccount(), - tickArrayLower: getNextAccount(), - tickArrayUpper: getNextAccount(), - personalPosition: getNextAccount(), - tokenAccount0: getNextAccount(), - tokenAccount1: getNextAccount(), - tokenVault0: getNextAccount(), - tokenVault1: getNextAccount(), - rent: getNextAccount(), - systemProgram: getNextAccount(), - tokenProgram: getNextAccount(), - associatedTokenProgram: getNextAccount(), - metadataProgram: getNextAccount(), - tokenProgram2022: getNextAccount(), - vault0Mint: getNextAccount(), - vault1Mint: getNextAccount(), - }, - data: getOpenPositionV2InstructionDataDecoder().decode(instruction.data), - }; -} diff --git a/sdk/src/generated/instructions/swap.ts b/sdk/src/generated/instructions/swap.ts deleted file mode 100644 index 29605f1..0000000 --- a/sdk/src/generated/instructions/swap.ts +++ /dev/null @@ -1,363 +0,0 @@ -/** - * This code was AUTOGENERATED using the Codama library. - * Please DO NOT EDIT THIS FILE, instead use visitors - * to add features, then rerun Codama to update it. - * - * @see https://github.com/codama-idl/codama - */ - -import { - combineCodec, - fixDecoderSize, - fixEncoderSize, - getBooleanDecoder, - getBooleanEncoder, - getBytesDecoder, - getBytesEncoder, - getStructDecoder, - getStructEncoder, - getU128Decoder, - getU128Encoder, - getU64Decoder, - getU64Encoder, - transformEncoder, - type AccountMeta, - type AccountSignerMeta, - type Address, - type FixedSizeCodec, - type FixedSizeDecoder, - type FixedSizeEncoder, - type Instruction, - type InstructionWithAccounts, - type InstructionWithData, - type ReadonlyAccount, - type ReadonlySignerAccount, - type ReadonlyUint8Array, - type TransactionSigner, - type WritableAccount, -} from '@solana/kit'; -import { AMM_V3_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; - -export const SWAP_DISCRIMINATOR = new Uint8Array([ - 248, 198, 158, 145, 225, 117, 135, 200, -]); - -export function getSwapDiscriminatorBytes() { - return fixEncoderSize(getBytesEncoder(), 8).encode(SWAP_DISCRIMINATOR); -} - -export type SwapInstruction< - TProgram extends string = typeof AMM_V3_PROGRAM_ADDRESS, - TAccountPayer extends string | AccountMeta = string, - TAccountAmmConfig extends string | AccountMeta = string, - TAccountPoolState extends string | AccountMeta = string, - TAccountInputTokenAccount extends string | AccountMeta = string, - TAccountOutputTokenAccount extends string | AccountMeta = string, - TAccountInputVault extends string | AccountMeta = string, - TAccountOutputVault extends string | AccountMeta = string, - TAccountObservationState extends string | AccountMeta = string, - TAccountTokenProgram extends - | string - | AccountMeta = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - TAccountTickArray extends string | AccountMeta = string, - TRemainingAccounts extends readonly AccountMeta[] = [], -> = Instruction & - InstructionWithData & - InstructionWithAccounts< - [ - TAccountPayer extends string - ? ReadonlySignerAccount & - AccountSignerMeta - : TAccountPayer, - TAccountAmmConfig extends string - ? ReadonlyAccount - : TAccountAmmConfig, - TAccountPoolState extends string - ? WritableAccount - : TAccountPoolState, - TAccountInputTokenAccount extends string - ? WritableAccount - : TAccountInputTokenAccount, - TAccountOutputTokenAccount extends string - ? WritableAccount - : TAccountOutputTokenAccount, - TAccountInputVault extends string - ? WritableAccount - : TAccountInputVault, - TAccountOutputVault extends string - ? WritableAccount - : TAccountOutputVault, - TAccountObservationState extends string - ? WritableAccount - : TAccountObservationState, - TAccountTokenProgram extends string - ? ReadonlyAccount - : TAccountTokenProgram, - TAccountTickArray extends string - ? WritableAccount - : TAccountTickArray, - ...TRemainingAccounts, - ] - >; - -export type SwapInstructionData = { - discriminator: ReadonlyUint8Array; - amount: bigint; - otherAmountThreshold: bigint; - sqrtPriceLimitX64: bigint; - isBaseInput: boolean; -}; - -export type SwapInstructionDataArgs = { - amount: number | bigint; - otherAmountThreshold: number | bigint; - sqrtPriceLimitX64: number | bigint; - isBaseInput: boolean; -}; - -export function getSwapInstructionDataEncoder(): FixedSizeEncoder { - return transformEncoder( - getStructEncoder([ - ['discriminator', fixEncoderSize(getBytesEncoder(), 8)], - ['amount', getU64Encoder()], - ['otherAmountThreshold', getU64Encoder()], - ['sqrtPriceLimitX64', getU128Encoder()], - ['isBaseInput', getBooleanEncoder()], - ]), - (value) => ({ ...value, discriminator: SWAP_DISCRIMINATOR }) - ); -} - -export function getSwapInstructionDataDecoder(): FixedSizeDecoder { - return getStructDecoder([ - ['discriminator', fixDecoderSize(getBytesDecoder(), 8)], - ['amount', getU64Decoder()], - ['otherAmountThreshold', getU64Decoder()], - ['sqrtPriceLimitX64', getU128Decoder()], - ['isBaseInput', getBooleanDecoder()], - ]); -} - -export function getSwapInstructionDataCodec(): FixedSizeCodec< - SwapInstructionDataArgs, - SwapInstructionData -> { - return combineCodec( - getSwapInstructionDataEncoder(), - getSwapInstructionDataDecoder() - ); -} - -export type SwapInput< - TAccountPayer extends string = string, - TAccountAmmConfig extends string = string, - TAccountPoolState extends string = string, - TAccountInputTokenAccount extends string = string, - TAccountOutputTokenAccount extends string = string, - TAccountInputVault extends string = string, - TAccountOutputVault extends string = string, - TAccountObservationState extends string = string, - TAccountTokenProgram extends string = string, - TAccountTickArray extends string = string, -> = { - /** The user performing the swap */ - payer: TransactionSigner; - /** The factory state to read protocol fees */ - ammConfig: Address; - /** The program account of the pool in which the swap will be performed */ - poolState: Address; - /** The user token account for input token */ - inputTokenAccount: Address; - /** The user token account for output token */ - outputTokenAccount: Address; - /** The vault token account for input token */ - inputVault: Address; - /** The vault token account for output token */ - outputVault: Address; - /** The program account for the most recent oracle observation */ - observationState: Address; - /** SPL program for token transfers */ - tokenProgram?: Address; - tickArray: Address; - amount: SwapInstructionDataArgs['amount']; - otherAmountThreshold: SwapInstructionDataArgs['otherAmountThreshold']; - sqrtPriceLimitX64: SwapInstructionDataArgs['sqrtPriceLimitX64']; - isBaseInput: SwapInstructionDataArgs['isBaseInput']; -}; - -export function getSwapInstruction< - TAccountPayer extends string, - TAccountAmmConfig extends string, - TAccountPoolState extends string, - TAccountInputTokenAccount extends string, - TAccountOutputTokenAccount extends string, - TAccountInputVault extends string, - TAccountOutputVault extends string, - TAccountObservationState extends string, - TAccountTokenProgram extends string, - TAccountTickArray extends string, - TProgramAddress extends Address = typeof AMM_V3_PROGRAM_ADDRESS, ->( - input: SwapInput< - TAccountPayer, - TAccountAmmConfig, - TAccountPoolState, - TAccountInputTokenAccount, - TAccountOutputTokenAccount, - TAccountInputVault, - TAccountOutputVault, - TAccountObservationState, - TAccountTokenProgram, - TAccountTickArray - >, - config?: { programAddress?: TProgramAddress } -): SwapInstruction< - TProgramAddress, - TAccountPayer, - TAccountAmmConfig, - TAccountPoolState, - TAccountInputTokenAccount, - TAccountOutputTokenAccount, - TAccountInputVault, - TAccountOutputVault, - TAccountObservationState, - TAccountTokenProgram, - TAccountTickArray -> { - // Program address. - const programAddress = config?.programAddress ?? AMM_V3_PROGRAM_ADDRESS; - - // Original accounts. - const originalAccounts = { - payer: { value: input.payer ?? null, isWritable: false }, - ammConfig: { value: input.ammConfig ?? null, isWritable: false }, - poolState: { value: input.poolState ?? null, isWritable: true }, - inputTokenAccount: { - value: input.inputTokenAccount ?? null, - isWritable: true, - }, - outputTokenAccount: { - value: input.outputTokenAccount ?? null, - isWritable: true, - }, - inputVault: { value: input.inputVault ?? null, isWritable: true }, - outputVault: { value: input.outputVault ?? null, isWritable: true }, - observationState: { - value: input.observationState ?? null, - isWritable: true, - }, - tokenProgram: { value: input.tokenProgram ?? null, isWritable: false }, - tickArray: { value: input.tickArray ?? null, isWritable: true }, - }; - const accounts = originalAccounts as Record< - keyof typeof originalAccounts, - ResolvedAccount - >; - - // Original args. - const args = { ...input }; - - // Resolve default values. - if (!accounts.tokenProgram.value) { - accounts.tokenProgram.value = - 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address<'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'>; - } - - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); - return Object.freeze({ - accounts: [ - getAccountMeta(accounts.payer), - getAccountMeta(accounts.ammConfig), - getAccountMeta(accounts.poolState), - getAccountMeta(accounts.inputTokenAccount), - getAccountMeta(accounts.outputTokenAccount), - getAccountMeta(accounts.inputVault), - getAccountMeta(accounts.outputVault), - getAccountMeta(accounts.observationState), - getAccountMeta(accounts.tokenProgram), - getAccountMeta(accounts.tickArray), - ], - data: getSwapInstructionDataEncoder().encode( - args as SwapInstructionDataArgs - ), - programAddress, - } as SwapInstruction< - TProgramAddress, - TAccountPayer, - TAccountAmmConfig, - TAccountPoolState, - TAccountInputTokenAccount, - TAccountOutputTokenAccount, - TAccountInputVault, - TAccountOutputVault, - TAccountObservationState, - TAccountTokenProgram, - TAccountTickArray - >); -} - -export type ParsedSwapInstruction< - TProgram extends string = typeof AMM_V3_PROGRAM_ADDRESS, - TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[], -> = { - programAddress: Address; - accounts: { - /** The user performing the swap */ - payer: TAccountMetas[0]; - /** The factory state to read protocol fees */ - ammConfig: TAccountMetas[1]; - /** The program account of the pool in which the swap will be performed */ - poolState: TAccountMetas[2]; - /** The user token account for input token */ - inputTokenAccount: TAccountMetas[3]; - /** The user token account for output token */ - outputTokenAccount: TAccountMetas[4]; - /** The vault token account for input token */ - inputVault: TAccountMetas[5]; - /** The vault token account for output token */ - outputVault: TAccountMetas[6]; - /** The program account for the most recent oracle observation */ - observationState: TAccountMetas[7]; - /** SPL program for token transfers */ - tokenProgram: TAccountMetas[8]; - tickArray: TAccountMetas[9]; - }; - data: SwapInstructionData; -}; - -export function parseSwapInstruction< - TProgram extends string, - TAccountMetas extends readonly AccountMeta[], ->( - instruction: Instruction & - InstructionWithAccounts & - InstructionWithData -): ParsedSwapInstruction { - if (instruction.accounts.length < 10) { - // TODO: Coded error. - throw new Error('Not enough accounts'); - } - let accountIndex = 0; - const getNextAccount = () => { - const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!; - accountIndex += 1; - return accountMeta; - }; - return { - programAddress: instruction.programAddress, - accounts: { - payer: getNextAccount(), - ammConfig: getNextAccount(), - poolState: getNextAccount(), - inputTokenAccount: getNextAccount(), - outputTokenAccount: getNextAccount(), - inputVault: getNextAccount(), - outputVault: getNextAccount(), - observationState: getNextAccount(), - tokenProgram: getNextAccount(), - tickArray: getNextAccount(), - }, - data: getSwapInstructionDataDecoder().decode(instruction.data), - }; -} diff --git a/sdk/src/generated/programs/ammV3.ts b/sdk/src/generated/programs/ammV3.ts index d76ac94..6bbc184 100644 --- a/sdk/src/generated/programs/ammV3.ts +++ b/sdk/src/generated/programs/ammV3.ts @@ -23,16 +23,11 @@ import { type ParsedCreateOperationAccountInstruction, type ParsedCreatePoolInstruction, type ParsedCreateSupportMintAssociatedInstruction, - type ParsedDecreaseLiquidityInstruction, type ParsedDecreaseLiquidityV2Instruction, - type ParsedIncreaseLiquidityInstruction, type ParsedIncreaseLiquidityV2Instruction, type ParsedInitializeRewardInstruction, - type ParsedOpenPositionInstruction, - type ParsedOpenPositionV2Instruction, type ParsedOpenPositionWithToken22NftInstruction, type ParsedSetRewardParamsInstruction, - type ParsedSwapInstruction, type ParsedSwapRouterBaseInInstruction, type ParsedSwapV2Instruction, type ParsedTransferRewardOwnerInstruction, @@ -175,16 +170,11 @@ export enum AmmV3Instruction { CreateOperationAccount, CreatePool, CreateSupportMintAssociated, - DecreaseLiquidity, DecreaseLiquidityV2, - IncreaseLiquidity, IncreaseLiquidityV2, InitializeReward, - OpenPosition, - OpenPositionV2, OpenPositionWithToken22Nft, SetRewardParams, - Swap, SwapRouterBaseIn, SwapV2, TransferRewardOwner, @@ -297,17 +287,6 @@ export function identifyAmmV3Instruction( ) { return AmmV3Instruction.CreateSupportMintAssociated; } - if ( - containsBytes( - data, - fixEncoderSize(getBytesEncoder(), 8).encode( - new Uint8Array([160, 38, 208, 111, 104, 91, 44, 1]) - ), - 0 - ) - ) { - return AmmV3Instruction.DecreaseLiquidity; - } if ( containsBytes( data, @@ -319,17 +298,6 @@ export function identifyAmmV3Instruction( ) { return AmmV3Instruction.DecreaseLiquidityV2; } - if ( - containsBytes( - data, - fixEncoderSize(getBytesEncoder(), 8).encode( - new Uint8Array([46, 156, 243, 118, 13, 205, 251, 178]) - ), - 0 - ) - ) { - return AmmV3Instruction.IncreaseLiquidity; - } if ( containsBytes( data, @@ -352,28 +320,6 @@ export function identifyAmmV3Instruction( ) { return AmmV3Instruction.InitializeReward; } - if ( - containsBytes( - data, - fixEncoderSize(getBytesEncoder(), 8).encode( - new Uint8Array([135, 128, 47, 77, 15, 152, 240, 49]) - ), - 0 - ) - ) { - return AmmV3Instruction.OpenPosition; - } - if ( - containsBytes( - data, - fixEncoderSize(getBytesEncoder(), 8).encode( - new Uint8Array([77, 184, 74, 214, 112, 86, 241, 199]) - ), - 0 - ) - ) { - return AmmV3Instruction.OpenPositionV2; - } if ( containsBytes( data, @@ -396,17 +342,6 @@ export function identifyAmmV3Instruction( ) { return AmmV3Instruction.SetRewardParams; } - if ( - containsBytes( - data, - fixEncoderSize(getBytesEncoder(), 8).encode( - new Uint8Array([248, 198, 158, 145, 225, 117, 135, 200]) - ), - 0 - ) - ) { - return AmmV3Instruction.Swap; - } if ( containsBytes( data, @@ -519,36 +454,21 @@ export type ParsedAmmV3Instruction< | ({ instructionType: AmmV3Instruction.CreateSupportMintAssociated; } & ParsedCreateSupportMintAssociatedInstruction) - | ({ - instructionType: AmmV3Instruction.DecreaseLiquidity; - } & ParsedDecreaseLiquidityInstruction) | ({ instructionType: AmmV3Instruction.DecreaseLiquidityV2; } & ParsedDecreaseLiquidityV2Instruction) - | ({ - instructionType: AmmV3Instruction.IncreaseLiquidity; - } & ParsedIncreaseLiquidityInstruction) | ({ instructionType: AmmV3Instruction.IncreaseLiquidityV2; } & ParsedIncreaseLiquidityV2Instruction) | ({ instructionType: AmmV3Instruction.InitializeReward; } & ParsedInitializeRewardInstruction) - | ({ - instructionType: AmmV3Instruction.OpenPosition; - } & ParsedOpenPositionInstruction) - | ({ - instructionType: AmmV3Instruction.OpenPositionV2; - } & ParsedOpenPositionV2Instruction) | ({ instructionType: AmmV3Instruction.OpenPositionWithToken22Nft; } & ParsedOpenPositionWithToken22NftInstruction) | ({ instructionType: AmmV3Instruction.SetRewardParams; } & ParsedSetRewardParamsInstruction) - | ({ - instructionType: AmmV3Instruction.Swap; - } & ParsedSwapInstruction) | ({ instructionType: AmmV3Instruction.SwapRouterBaseIn; } & ParsedSwapRouterBaseInInstruction) diff --git a/sdk/src/generated/types/createPersonalPositionEvent.ts b/sdk/src/generated/types/createPersonalPositionEvent.ts index 5bce805..b27ec9c 100644 --- a/sdk/src/generated/types/createPersonalPositionEvent.ts +++ b/sdk/src/generated/types/createPersonalPositionEvent.ts @@ -28,6 +28,10 @@ import { export type CreatePersonalPositionEvent = { /** The pool for which liquidity was added */ poolState: Address; + /** The personal position */ + personalPosition: Address; + /** The nft mint address for the position */ + nftMint: Address; /** The address that create the position */ minter: Address; /** The owner of the position and recipient of any minted liquidity */ @@ -51,6 +55,10 @@ export type CreatePersonalPositionEvent = { export type CreatePersonalPositionEventArgs = { /** The pool for which liquidity was added */ poolState: Address; + /** The personal position */ + personalPosition: Address; + /** The nft mint address for the position */ + nftMint: Address; /** The address that create the position */ minter: Address; /** The owner of the position and recipient of any minted liquidity */ @@ -74,6 +82,8 @@ export type CreatePersonalPositionEventArgs = { export function getCreatePersonalPositionEventEncoder(): FixedSizeEncoder { return getStructEncoder([ ['poolState', getAddressEncoder()], + ['personalPosition', getAddressEncoder()], + ['nftMint', getAddressEncoder()], ['minter', getAddressEncoder()], ['nftOwner', getAddressEncoder()], ['tickLowerIndex', getI32Encoder()], @@ -89,6 +99,8 @@ export function getCreatePersonalPositionEventEncoder(): FixedSizeEncoder { return getStructDecoder([ ['poolState', getAddressDecoder()], + ['personalPosition', getAddressDecoder()], + ['nftMint', getAddressDecoder()], ['minter', getAddressDecoder()], ['nftOwner', getAddressDecoder()], ['tickLowerIndex', getI32Decoder()], diff --git a/sdk/src/generated/types/poolCreatedEvent.ts b/sdk/src/generated/types/poolCreatedEvent.ts index 85c864e..5fb5760 100644 --- a/sdk/src/generated/types/poolCreatedEvent.ts +++ b/sdk/src/generated/types/poolCreatedEvent.ts @@ -45,6 +45,8 @@ export type PoolCreatedEvent = { tokenVault0: Address; /** Vault of token_1 */ tokenVault1: Address; + /** The PublicKey of the config account with fee rates etc */ + ammConfig: Address; }; export type PoolCreatedEventArgs = { @@ -64,6 +66,8 @@ export type PoolCreatedEventArgs = { tokenVault0: Address; /** Vault of token_1 */ tokenVault1: Address; + /** The PublicKey of the config account with fee rates etc */ + ammConfig: Address; }; export function getPoolCreatedEventEncoder(): FixedSizeEncoder { @@ -76,6 +80,7 @@ export function getPoolCreatedEventEncoder(): FixedSizeEncoder ['tick', getI32Decoder()], ['tokenVault0', getAddressDecoder()], ['tokenVault1', getAddressDecoder()], + ['ammConfig', getAddressDecoder()], ]); } diff --git a/sdk/src/swap.ts b/sdk/src/swap.ts index 6e2d5c5..853550b 100644 --- a/sdk/src/swap.ts +++ b/sdk/src/swap.ts @@ -1,378 +1,311 @@ -/** - * - * NOTE: Work in progress - * -*/ +import type { + Account, + Address, + FetchAccountConfig, + fetchEncodedAccount, + Instruction, + TransactionSigner, +} from '@solana/kit'; +import { + getSwapV2Instruction, + fetchPoolState, + type SwapV2Input, + PoolState, +} from './generated'; +import type { + ClmmSdkConfig, + SwapParams, + SwapQuote, + PoolInfo, +} from './types'; -// import type { -// Account, -// Address, -// FetchAccountConfig, -// fetchEncodedAccount, -// Instruction, -// TransactionSigner, -// } from '@solana/kit'; -// import { -// getSwapV2Instruction, -// fetchPoolState, -// type SwapV2Input, -// PoolState, -// } from './generated'; -// import type { -// ClmmSdkConfig, -// SwapParams, -// SwapQuote, -// PoolInfo, -// } from './types'; -// -// import { ClmmError } from './types'; -// -// import { ClmmErrorCode, isValidSlippage } from './types'; -// import { PdaUtils } from './utils/pda'; -// import { MathUtils } from './utils/math'; -// import { PoolManager } from './pool-manager'; -// import { findAssociatedTokenPda, TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -// import { DEFAULT_SLIPPAGE_TOLERANCE } from './constants'; -// -// export class SwapManager { -// private readonly poolManager: PoolManager; -// -// constructor(private readonly config: ClmmSdkConfig) { -// this.poolManager = new PoolManager(config); -// } -// -// /** -// * TODO: description -// */ -// async fetchPool( -// rpc: Parameters[0], -// address: Address, -// config?: FetchAccountConfig -// ): Promise> { -// return fetchPoolState(rpc, address, config) -// } -// -// /** -// * INFO: Disabled -// * -// * Get a swap quote for trading between two tokens in a specific pool -// * @param poolAddress - The pool to trade in -// * @param params - Swap parameters -// * @returns Swap quote with expected output and price impact -// */ -// // async getSwapQuote( -// // poolAddress: Address, -// // params: Omit & { -// // tokenIn: Address; -// // tokenOut: Address; -// // } -// // ): Promise { -// // const { -// // tokenIn, -// // tokenOut, -// // amountIn, -// // slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, -// // } = params; -// // -// // // Validate slippage tolerance -// // if (!isValidSlippage(slippageTolerance)) { -// // throw new ClmmError( -// // ClmmErrorCode.PRICE_SLIPPAGE, -// // 'Invalid slippage tolerance. Must be between 0 and 1.' -// // ); -// // } -// // -// // // Get pool information -// // const pool = await this.poolManager.getPool(poolAddress); -// // if (!pool) { -// // throw new ClmmError( -// // ClmmErrorCode.POOL_NOT_FOUND, -// // 'Pool not found' -// // ); -// // } -// // -// // // Verify the pool contains the specified tokens -// // const hasTokens = (pool.tokenMint0 === tokenIn && pool.tokenMint1 === tokenOut) || -// // (pool.tokenMint0 === tokenOut && pool.tokenMint1 === tokenIn); -// // -// // if (!hasTokens) { -// // throw new ClmmError( -// // ClmmErrorCode.POOL_NOT_FOUND, -// // 'Pool does not contain the specified token pair' -// // ); -// // } -// // -// // // Calculate swap output -// // const { amountOut, priceImpact, fee } = await this.calculateSwapOutput( -// // pool, -// // tokenIn, -// // tokenOut, -// // amountIn -// // ); -// // -// // // Apply slippage tolerance -// // const minAmountOut = amountOut - (amountOut * BigInt(Math.floor(slippageTolerance * 10000))) / 10000n; -// // -// // return { -// // amountIn, -// // amountOut, -// // minAmountOut, -// // priceImpact, -// // route: [{ -// // poolAddress, -// // tokenIn, -// // tokenOut, -// // fee: pool.tradeFeeRate || 3000, -// // }], -// // fee, -// // }; -// // } -// -// /** -// * Execute swap with V2 instruction -// * @param poolAddress - Pool to trade in -// * @param params - Swap parameters with additional options -// * @returns Swap V2 instruction -// */ -// async executeSwap( -// poolAddress: Address, -// payer: TransactionSigner
, -// params: SwapParams & { -// remainingAccountsInfo?: any[]; -// sqrtPriceLimitX64?: bigint; -// } -// ): Promise { -// const quote = await this.getSwapQuote(poolAddress, params); -// const pool = await this.poolManager.getPool(poolAddress); -// -// if (!pool) { -// throw new ClmmError( -// ClmmErrorCode.POOL_NOT_FOUND, -// 'Pool not found for swap' -// ); -// } -// -// const zeroForOne = params.tokenIn === pool.tokenMint0; -// // const tickArrays = await this.getRequiredTickArrays( -// // poolAddress, -// // pool.tickCurrent, -// // pool.tickSpacing, -// // zeroForOne -// // ); -// -// const observationStatePda = await PdaUtils.getObservationStatePda(poolAddress); -// -// const [inputTokenAccount] = await findAssociatedTokenPda({ mint: params.tokenIn, owner: payer.address, tokenProgram: TOKEN_PROGRAM_ADDRESS }) -// const [outputTokenAccount] = await findAssociatedTokenPda({ mint: params.tokenIn, owner: payer.address, tokenProgram: TOKEN_PROGRAM_ADDRESS }) -// -// const input: SwapV2Input = { -// payer, -// ammConfig: pool.ammConfig, -// poolState: poolAddress, -// inputTokenAccount, -// outputTokenAccount, -// inputVault: zeroForOne ? pool.tokenVault0 : pool.tokenVault1, -// outputVault: zeroForOne ? pool.tokenVault1 : pool.tokenVault0, -// observationState: observationStatePda[0], -// inputVaultMint: zeroForOne ? pool.tokenMint0 : pool.tokenMint1, -// outputVaultMint: zeroForOne ? pool.tokenMint1 : pool.tokenMint0, -// amount: params.amountIn, -// otherAmountThreshold: quote.minAmountOut, -// sqrtPriceLimitX64: params.sqrtPriceLimitX64 || this.calculateSqrtPriceLimit( -// pool, -// zeroForOne, -// params.slippageTolerance || DEFAULT_SLIPPAGE_TOLERANCE -// ), -// isBaseInput: true, -// }; -// -// return getSwapV2Instruction(input); -// } -// -// /** -// * INFO: Disabled -// * -// * Calculate optimal slippage for a trade -// * @param quote - Swap quote -// * @param riskTolerance - Risk tolerance (0-1, higher = more risk) -// * @returns Recommended slippage tolerance -// */ -// // calculateOptimalSlippage( -// // quote: SwapQuote, -// // riskTolerance: number = 0.5 -// // ): number { -// // // Base slippage based on price impact -// // let baseSlippage = Math.max(quote.priceImpact * 2, 0.001); // At least 0.1% -// // -// // // Adjust based on trade size (larger trades need more slippage) -// // const tradeSize = Number(quote.amountIn); -// // const sizeMultiplier = Math.log10(Math.max(tradeSize / 1e6, 1)) * 0.001; -// // -// // // Adjust based on risk tolerance -// // const riskAdjustment = (1 - riskTolerance) * 0.005; // Up to 0.5% additional -// // -// // const recommendedSlippage = baseSlippage + sizeMultiplier + riskAdjustment; -// // -// // return Math.min(recommendedSlippage, 0.05); // Cap at 5% -// // } -// -// /** -// * Get current pool price for a token pair -// * @param poolAddress - Pool address -// * @returns Current price (token1 per token0) -// */ -// async getCurrentPrice(poolAddress: Address): Promise { -// const pool = await this.poolManager.getPool(poolAddress); -// if (!pool) { -// throw new ClmmError( -// ClmmErrorCode.POOL_NOT_FOUND, -// 'Pool not found' -// ); -// } -// -// return MathUtils.sqrtPriceX64ToPrice( -// pool.sqrtPriceX64, -// pool.mintDecimals0, -// pool.mintDecimals1 -// ); -// } -// -// /** -// * Check if a pool has sufficient liquidity for a trade -// * @param poolAddress - Pool address -// * @param amountIn - Input amount -// * @param tokenIn - Input token -// * @returns Whether liquidity is sufficient -// */ -// async hasSufficientLiquidity( -// poolAddress: Address, -// amountIn: bigint, -// tokenIn: Address -// ): Promise { -// try { -// const pool = await this.poolManager.getPool(poolAddress); -// if (!pool) return false; -// -// // Simple check - in practice would simulate the swap to check for liquidity -// return pool.liquidity > 0n && amountIn > 0n; -// } catch { -// return false; -// } -// } -// -// /** -// * Calculate swap output for a pool -// * @param pool - Pool information -// * @param tokenIn - Input token -// * @param tokenOut - Output token -// * @param amountIn - Input amount -// * @returns Swap calculation results -// */ -// private async calculateSwapOutput( -// pool: PoolInfo, -// tokenIn: Address, -// tokenOut: Address, -// amountIn: bigint -// ): Promise<{ -// amountOut: bigint; -// priceImpact: number; -// fee: bigint; -// }> { -// // Calculate fee -// const fee = (amountIn * BigInt(pool.tradeFeeRate || 3000)) / 1000000n; -// const amountInAfterFee = amountIn - fee; -// -// // Simplified CLMM calculation - real implementation would use: -// // - Tick crossing logic -// // - Concentrated liquidity math -// // - Current active liquidity in price range -// -// // For now, use a simplified constant product formula as approximation -// const zeroForOne = tokenIn === pool.tokenMint0; -// -// // This is a placeholder calculation - actual CLMM math is more complex -// const currentPrice = MathUtils.sqrtPriceX64ToPrice( -// pool.sqrtPriceX64, -// pool.mintDecimals0, -// pool.mintDecimals1 -// ); -// -// let amountOut: bigint; -// if (zeroForOne) { -// // Selling token0 for token1 -// amountOut = BigInt(Math.floor(Number(amountInAfterFee) * currentPrice)); -// } else { -// // Selling token1 for token0 -// amountOut = BigInt(Math.floor(Number(amountInAfterFee) / currentPrice)); -// } -// -// // Simplified price impact calculation -// const priceImpact = Math.min(Number(amountIn) / Number(pool.liquidity) * 0.1, 0.1); // Cap at 10% -// -// return { -// amountOut, -// priceImpact, -// fee, -// }; -// } -// -// /** -// * Get required tick arrays for a swap -// * @param poolAddress - Pool address -// * @param currentTick - Current pool tick -// * @param tickSpacing - Pool tick spacing -// * @param zeroForOne - Swap direction -// * @returns Required tick array addresses -// */ -// private async getRequiredTickArrays( -// poolAddress: Address, -// currentTick: number, -// tickSpacing: number, -// zeroForOne: boolean -// ): Promise { -// // Calculate which tick arrays might be crossed during the swap -// const currentStartIndex = PdaUtils.getTickArrayStartIndex(currentTick, tickSpacing); -// -// // Calculate adjacent array index based on swap direction -// let adjacentStartIndex: number; -// if (zeroForOne) { -// // Price going down, might need lower tick arrays -// adjacentStartIndex = currentStartIndex - (60 * tickSpacing); -// } else { -// // Price going up, might need higher tick arrays -// adjacentStartIndex = currentStartIndex + (60 * tickSpacing); -// } -// -// // Derive both tick array PDAs in parallel -// const [currentTickArrayPda, adjacentTickArrayPda] = await Promise.all([ -// PdaUtils.getTickArrayStatePda(poolAddress, currentStartIndex), -// PdaUtils.getTickArrayStatePda(poolAddress, adjacentStartIndex) -// ]); -// -// return [currentTickArrayPda[0], adjacentTickArrayPda[0]]; -// } -// -// /** -// * Calculate sqrt price limit for slippage protection -// * @param pool - Pool information -// * @param zeroForOne - Swap direction -// * @param slippageTolerance - Slippage tolerance -// * @returns Sqrt price limit -// */ -// private calculateSqrtPriceLimit( -// pool: PoolInfo, -// zeroForOne: boolean, -// slippageTolerance: number -// ): bigint { -// const currentSqrtPrice = pool.sqrtPriceX64; -// const slippageMultiplier = BigInt(Math.floor((1 + slippageTolerance) * 10000)); -// -// if (zeroForOne) { -// // Price decreasing, set lower limit -// return (currentSqrtPrice * 10000n) / slippageMultiplier; -// } else { -// // Price increasing, set upper limit -// return (currentSqrtPrice * slippageMultiplier) / 10000n; -// } -// } -// } +import { ClmmError } from './types'; + +import { ClmmErrorCode, isValidSlippage } from './types'; +import { PdaUtils } from './utils/pda'; +import { MathUtils, SqrtPriceMath } from './utils/math'; +import BN from 'bn.js'; +import { PoolManager } from './pool-manager'; +import { findAssociatedTokenPda, TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; +import { DEFAULT_SLIPPAGE_TOLERANCE } from './constants'; + +export class SwapManager { + private readonly poolManager: PoolManager; + + constructor(private readonly config: ClmmSdkConfig) { + this.poolManager = new PoolManager(config); + } + + /** + * INFO: Disabled + * + * Calculate optimal slippage for a trade + * @param quote - Swap quote + * @param riskTolerance - Risk tolerance (0-1, higher = more risk) + * @returns Recommended slippage tolerance + */ + // calculateOptimalSlippage( + // quote: SwapQuote, + // riskTolerance: number = 0.5 + // ): number { + // // Base slippage based on price impact + // let baseSlippage = Math.max(quote.priceImpact * 2, 0.001); // At least 0.1% + // + // // Adjust based on trade size (larger trades need more slippage) + // const tradeSize = Number(quote.amountIn); + // const sizeMultiplier = Math.log10(Math.max(tradeSize / 1e6, 1)) * 0.001; + // + // // Adjust based on risk tolerance + // const riskAdjustment = (1 - riskTolerance) * 0.005; // Up to 0.5% additional + // + // const recommendedSlippage = baseSlippage + sizeMultiplier + riskAdjustment; + // + // return Math.min(recommendedSlippage, 0.05); // Cap at 5% + // } + + /** + * Get current pool price for a token pair + * @param poolAddress - Pool address + * @returns Current price (token1 per token0) + */ + async getCurrentPrice(poolAddress: Address): Promise { + const pool = await this.poolManager.getPool(poolAddress); + if (!pool) { + throw new ClmmError( + ClmmErrorCode.POOL_NOT_FOUND, + 'Pool not found' + ); + } + + const price = SqrtPriceMath.sqrtPriceX64ToPrice( + new BN(pool.sqrtPriceX64.toString()), + pool.mintDecimals0, + pool.mintDecimals1 + ); + return Number(price.toString()); + } + + /** + * Check if a pool has sufficient liquidity for a trade + * @param poolAddress - Pool address + * @param amountIn - Input amount + * @param tokenIn - Input token + * @returns Whether liquidity is sufficient + */ + async hasSufficientLiquidity( + poolAddress: Address, + amountIn: bigint, + tokenIn: Address + ): Promise { + try { + const pool = await this.poolManager.getPool(poolAddress); + if (!pool) return false; + + // Simple check - in practice would simulate the swap to check for liquidity + return pool.liquidity > 0n && amountIn > 0n; + } catch { + return false; + } + } + + /** + * Calculate swap output for a pool + * @param pool - Pool information + * @param tokenIn - Input token + * @param tokenOut - Output token + * @param amountIn - Input amount + * @returns Swap calculation results + */ + private async calculateSwapOutput( + pool: PoolInfo, + tokenIn: Address, + tokenOut: Address, + amountIn: bigint + ): Promise<{ + amountOut: bigint; + priceImpact: number; + fee: bigint; + }> { + // Calculate fee (default 0.3%) + const feeRatePpm = 3000; // 0.3% in ppm + const fee = (amountIn * BigInt(feeRatePpm)) / 1000000n; + const amountInAfterFee = amountIn - fee; + + // Simplified CLMM calculation - real implementation would use: + // - Tick crossing logic + // - Concentrated liquidity math + // - Current active liquidity in price range + + // For now, use a simplified constant product formula as approximation + const zeroForOne = tokenIn === pool.tokenMint0; + + // This is a placeholder calculation - actual CLMM math is more complex + const currentPriceDec = SqrtPriceMath.sqrtPriceX64ToPrice( + new BN(pool.sqrtPriceX64.toString()), + pool.mintDecimals0, + pool.mintDecimals1 + ); + const currentPrice = Number(currentPriceDec.toString()); + + let amountOut: bigint; + if (zeroForOne) { + // Selling token0 for token1 + amountOut = BigInt(Math.floor(Number(amountInAfterFee) * currentPrice)); + } else { + // Selling token1 for token0 + amountOut = BigInt(Math.floor(Number(amountInAfterFee) / currentPrice)); + } + + // Simplified price impact calculation + const priceImpact = Math.min(Number(amountIn) / Number(pool.liquidity) * 0.1, 0.1); // Cap at 10% + + return { + amountOut, + priceImpact, + fee, + }; + } + + /** + * Calculate sqrt price limit for slippage protection + * @param pool - Pool information + * @param zeroForOne - Swap direction + * @param slippageTolerance - Slippage tolerance + * @returns Sqrt price limit + */ + private calculateSqrtPriceLimit( + pool: PoolInfo, + zeroForOne: boolean, + slippageTolerance: number + ): bigint { + const currentSqrtPrice = pool.sqrtPriceX64; + const slippageMultiplier = BigInt(Math.floor((1 + slippageTolerance) * 10000)); + + if (zeroForOne) { + // Price decreasing, set lower limit + return (currentSqrtPrice * 10000n) / slippageMultiplier; + } else { + // Price increasing, set upper limit + return (currentSqrtPrice * slippageMultiplier) / 10000n; + } + } + + /** + * Build swap_v2 instruction for a single-pool swap. + * Returns instruction result so callers can add to a transaction and send. + */ + async makeSwapV2Instructions(params: { + payer: TransactionSigner; + poolAddress: Address; + tokenIn: Address; + amount: bigint; + /** Slippage tolerance as fraction (e.g. 0.01 for 1%). Defaults to DEFAULT_SLIPPAGE_TOLERANCE. */ + slippageTolerance?: number; + /** If true, amount is input amount (base-in). If false, amount is desired output (base-out). */ + isBaseInput?: boolean; + }): Promise<{ + instructions: Instruction[]; + signers: TransactionSigner[]; + address: { + pool: Address; + ammConfig: Address; + inputVault: Address; + outputVault: Address; + observation: Address; + userInputAta: Address; + userOutputAta: Address; + inputMint: Address; + outputMint: Address; + }; + instructionTypes: string[]; + lookupTableAddress: string[]; + }> { + const { payer, poolAddress, tokenIn, amount } = params; + const isBaseInput = params.isBaseInput ?? true; + const slippage = isValidSlippage(params.slippageTolerance ?? DEFAULT_SLIPPAGE_TOLERANCE) + ? (params.slippageTolerance ?? DEFAULT_SLIPPAGE_TOLERANCE) + : DEFAULT_SLIPPAGE_TOLERANCE; + + if (amount <= 0n) { + throw new ClmmError(ClmmErrorCode.SWAP_AMOUNT_CANNOT_BE_ZERO, 'Amount must be > 0'); + } + + const pool = await this.poolManager.getPool(poolAddress); + if (!pool) { + throw new ClmmError(ClmmErrorCode.POOL_NOT_FOUND, 'Pool not found'); + } + + const zeroForOne = tokenIn === pool.tokenMint0; + const tokenOut = zeroForOne ? pool.tokenMint1 : pool.tokenMint0; + + // Resolve user ATAs + const [userInputAtaPda, userOutputAtaPda] = await Promise.all([ + findAssociatedTokenPda({ mint: tokenIn, owner: payer.address, tokenProgram: TOKEN_PROGRAM_ADDRESS }), + findAssociatedTokenPda({ mint: tokenOut, owner: payer.address, tokenProgram: TOKEN_PROGRAM_ADDRESS }), + ]); + + const inputVault = zeroForOne ? pool.tokenVault0 : pool.tokenVault1; + const outputVault = zeroForOne ? pool.tokenVault1 : pool.tokenVault0; + const inputMint = zeroForOne ? pool.tokenMint0 : pool.tokenMint1; + const outputMint = zeroForOne ? pool.tokenMint1 : pool.tokenMint0; + + // Compute sqrt price limit for slippage guard + const sqrtPriceLimitX64 = this.calculateSqrtPriceLimit(pool, zeroForOne, slippage); + + // Estimate and compute thresholds + let otherAmountThreshold: bigint; + if (isBaseInput) { + const estimate = await this.calculateSwapOutput(pool, tokenIn, tokenOut, amount); + const minOut = BigInt( + Math.floor(Number(estimate.amountOut) * (1 - slippage)) + ); + otherAmountThreshold = minOut; + } else { + // Base-out: amount is desired output; set max input with slippage buffer + const estimate = await this.calculateSwapOutput(pool, tokenOut, tokenIn, amount); + const maxIn = BigInt( + Math.ceil(Number(estimate.amountOut) * (1 + slippage)) + ); + otherAmountThreshold = maxIn; + } + + const ix = getSwapV2Instruction( + { + payer, + ammConfig: pool.ammConfig, + poolState: poolAddress, + inputTokenAccount: userInputAtaPda[0], + outputTokenAccount: userOutputAtaPda[0], + inputVault, + outputVault, + observationState: pool.observationKey, + tokenProgram: TOKEN_PROGRAM_ADDRESS, + inputVaultMint: inputMint, + outputVaultMint: outputMint, + amount, + otherAmountThreshold, + sqrtPriceLimitX64, + isBaseInput, + } as SwapV2Input, + { programAddress: this.config.programAddress } + ); + + return { + instructions: [ix], + signers: [payer], + instructionTypes: ['SwapV2'], + address: { + pool: poolAddress, + ammConfig: pool.ammConfig, + inputVault, + outputVault, + observation: pool.observationKey, + userInputAta: userInputAtaPda[0], + userOutputAta: userOutputAtaPda[0], + inputMint, + outputMint, + }, + lookupTableAddress: [], + }; + } +} diff --git a/tsconfig.json b/tsconfig.json index 1403d98..a7d2d97 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["mocha", "chai"], "typeRoots": ["./node_modules/@types"], "lib": ["es2015", "dom"], "module": "commonjs", From 87d3b0e8919909653b14ad0969a326b4eb5ce64c Mon Sep 17 00:00:00 2001 From: angadsingh Date: Sun, 19 Oct 2025 12:38:28 +0100 Subject: [PATCH 2/2] add PositionManager to SDK --- sdk/src/client.ts | 3 +++ sdk/src/index.ts | 5 ----- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/sdk/src/client.ts b/sdk/src/client.ts index 702a6ac..c6cb1ba 100644 --- a/sdk/src/client.ts +++ b/sdk/src/client.ts @@ -4,6 +4,7 @@ import { PoolManager } from "./pool-manager"; import { PositionManager } from "./position-manager"; import { ClmmApi } from "./api"; import { getApisFromEndpoint } from "./utils"; +import { SwapManager } from "./swap"; // import { SwapManager } from './swap'; // import { RewardsManager } from './rewards'; @@ -19,6 +20,7 @@ export class ClmmSdk { /** Position management functionality */ public readonly positions: PositionManager; + public readonly swapManager: SwapManager; /** Swap functionality */ // public readonly swap: SwapManager; @@ -41,6 +43,7 @@ export class ClmmSdk { this.pools = new PoolManager(config); this.positions = new PositionManager(config); + this.swapManager = new SwapManager(config); // this.swap = new SwapManager(config); // this.rewards = new RewardsManager(config); } diff --git a/sdk/src/index.ts b/sdk/src/index.ts index b9508ae..0de14b4 100644 --- a/sdk/src/index.ts +++ b/sdk/src/index.ts @@ -36,12 +36,7 @@ export { // Instruction functions (commonly used) getCreatePoolInstruction, getCreateAmmConfigInstruction, - getOpenPositionInstruction, - getOpenPositionV2Instruction, - getIncreaseLiquidityInstruction, - getDecreaseLiquidityInstruction, getClosePositionInstruction, - getSwapInstruction, getSwapV2Instruction, // Fetch functions