@wuwei-labs/srsly 2.0.0-beta.37 → 2.0.0-beta.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/README.md +2 -1
  2. package/dist/cjs/codama/accounts/config.js +0 -2
  3. package/dist/cjs/codama/accounts/config.js.map +1 -1
  4. package/dist/cjs/codama/accounts/contractState.js.map +1 -1
  5. package/dist/cjs/codama/accounts/rentalState.js +1 -3
  6. package/dist/cjs/codama/accounts/rentalState.js.map +1 -1
  7. package/dist/cjs/codama/errors/srsly.js +13 -1
  8. package/dist/cjs/codama/errors/srsly.js.map +1 -1
  9. package/dist/cjs/codama/instructions/acceptRental.js +1 -28
  10. package/dist/cjs/codama/instructions/acceptRental.js.map +1 -1
  11. package/dist/cjs/codama/instructions/closeRental.js +28 -13
  12. package/dist/cjs/codama/instructions/closeRental.js.map +1 -1
  13. package/dist/cjs/codama/instructions/index.js +1 -0
  14. package/dist/cjs/codama/instructions/index.js.map +1 -1
  15. package/dist/cjs/codama/instructions/payRental.js +1 -18
  16. package/dist/cjs/codama/instructions/payRental.js.map +1 -1
  17. package/dist/cjs/codama/instructions/resetContractTemp.js +146 -0
  18. package/dist/cjs/codama/instructions/resetContractTemp.js.map +1 -0
  19. package/dist/cjs/codama/instructions/resetRental.js +6 -1
  20. package/dist/cjs/codama/instructions/resetRental.js.map +1 -1
  21. package/dist/cjs/codama/instructions/updateConfig.js +0 -2
  22. package/dist/cjs/codama/instructions/updateConfig.js.map +1 -1
  23. package/dist/cjs/codama/programs/srsly.js +6 -2
  24. package/dist/cjs/codama/programs/srsly.js.map +1 -1
  25. package/dist/cjs/codama/types/paymentFrequency.js +31 -0
  26. package/dist/cjs/codama/types/paymentFrequency.js.map +1 -1
  27. package/dist/cjs/contract/close.js +71 -11
  28. package/dist/cjs/contract/close.js.map +1 -1
  29. package/dist/cjs/contract/create.js +88 -21
  30. package/dist/cjs/contract/create.js.map +1 -1
  31. package/dist/cjs/contract/index.js +45 -0
  32. package/dist/cjs/contract/index.js.map +1 -1
  33. package/dist/cjs/index.js +110 -7
  34. package/dist/cjs/index.js.map +1 -1
  35. package/dist/cjs/package.json +4 -4
  36. package/dist/cjs/rental/accept.js +164 -45
  37. package/dist/cjs/rental/accept.js.map +1 -1
  38. package/dist/cjs/rental/cancel.js +82 -16
  39. package/dist/cjs/rental/cancel.js.map +1 -1
  40. package/dist/cjs/rental/close.js +152 -27
  41. package/dist/cjs/rental/close.js.map +1 -1
  42. package/dist/cjs/rental/index.js +85 -0
  43. package/dist/cjs/rental/index.js.map +1 -1
  44. package/dist/cjs/rental/reset-contract-temp.js +103 -0
  45. package/dist/cjs/rental/reset-contract-temp.js.map +1 -0
  46. package/dist/cjs/rental/reset.js +102 -19
  47. package/dist/cjs/rental/reset.js.map +1 -1
  48. package/dist/cjs/utils/config.js +44 -9
  49. package/dist/cjs/utils/config.js.map +1 -1
  50. package/dist/cjs/utils/constants.js +16 -6
  51. package/dist/cjs/utils/constants.js.map +1 -1
  52. package/dist/cjs/utils/index.js +1 -0
  53. package/dist/cjs/utils/index.js.map +1 -1
  54. package/dist/cjs/utils/instruction-converter.js +60 -5
  55. package/dist/cjs/utils/instruction-converter.js.map +1 -1
  56. package/dist/cjs/utils/paymentFrequency.js +7 -2
  57. package/dist/cjs/utils/paymentFrequency.js.map +1 -1
  58. package/dist/cjs/utils/pda.js +191 -0
  59. package/dist/cjs/utils/pda.js.map +1 -0
  60. package/dist/esm/codama/accounts/config.js +0 -2
  61. package/dist/esm/codama/accounts/config.js.map +1 -1
  62. package/dist/esm/codama/accounts/contractState.js.map +1 -1
  63. package/dist/esm/codama/accounts/rentalState.js +1 -3
  64. package/dist/esm/codama/accounts/rentalState.js.map +1 -1
  65. package/dist/esm/codama/errors/srsly.js +12 -0
  66. package/dist/esm/codama/errors/srsly.js.map +1 -1
  67. package/dist/esm/codama/instructions/acceptRental.js +1 -28
  68. package/dist/esm/codama/instructions/acceptRental.js.map +1 -1
  69. package/dist/esm/codama/instructions/closeRental.js +28 -13
  70. package/dist/esm/codama/instructions/closeRental.js.map +1 -1
  71. package/dist/esm/codama/instructions/index.js +1 -0
  72. package/dist/esm/codama/instructions/index.js.map +1 -1
  73. package/dist/esm/codama/instructions/payRental.js +1 -18
  74. package/dist/esm/codama/instructions/payRental.js.map +1 -1
  75. package/dist/esm/codama/instructions/resetContractTemp.js +136 -0
  76. package/dist/esm/codama/instructions/resetContractTemp.js.map +1 -0
  77. package/dist/esm/codama/instructions/resetRental.js +6 -1
  78. package/dist/esm/codama/instructions/resetRental.js.map +1 -1
  79. package/dist/esm/codama/instructions/updateConfig.js +0 -2
  80. package/dist/esm/codama/instructions/updateConfig.js.map +1 -1
  81. package/dist/esm/codama/programs/srsly.js +6 -2
  82. package/dist/esm/codama/programs/srsly.js.map +1 -1
  83. package/dist/esm/codama/types/paymentFrequency.js +31 -0
  84. package/dist/esm/codama/types/paymentFrequency.js.map +1 -1
  85. package/dist/esm/contract/close.js +72 -12
  86. package/dist/esm/contract/close.js.map +1 -1
  87. package/dist/esm/contract/create.js +89 -22
  88. package/dist/esm/contract/create.js.map +1 -1
  89. package/dist/esm/contract/index.js +45 -0
  90. package/dist/esm/contract/index.js.map +1 -1
  91. package/dist/esm/index.js +110 -6
  92. package/dist/esm/index.js.map +1 -1
  93. package/dist/esm/package.json +4 -4
  94. package/dist/esm/rental/accept.js +166 -47
  95. package/dist/esm/rental/accept.js.map +1 -1
  96. package/dist/esm/rental/cancel.js +83 -17
  97. package/dist/esm/rental/cancel.js.map +1 -1
  98. package/dist/esm/rental/close.js +152 -27
  99. package/dist/esm/rental/close.js.map +1 -1
  100. package/dist/esm/rental/index.js +85 -0
  101. package/dist/esm/rental/index.js.map +1 -1
  102. package/dist/esm/rental/reset-contract-temp.js +100 -0
  103. package/dist/esm/rental/reset-contract-temp.js.map +1 -0
  104. package/dist/esm/rental/reset.js +102 -19
  105. package/dist/esm/rental/reset.js.map +1 -1
  106. package/dist/esm/utils/config.js +44 -9
  107. package/dist/esm/utils/config.js.map +1 -1
  108. package/dist/esm/utils/constants.js +16 -6
  109. package/dist/esm/utils/constants.js.map +1 -1
  110. package/dist/esm/utils/index.js +1 -0
  111. package/dist/esm/utils/index.js.map +1 -1
  112. package/dist/esm/utils/instruction-converter.js +59 -5
  113. package/dist/esm/utils/instruction-converter.js.map +1 -1
  114. package/dist/esm/utils/paymentFrequency.js +7 -2
  115. package/dist/esm/utils/paymentFrequency.js.map +1 -1
  116. package/dist/esm/utils/pda.js +185 -0
  117. package/dist/esm/utils/pda.js.map +1 -0
  118. package/dist/types/codama/accounts/config.d.ts +24 -2
  119. package/dist/types/codama/accounts/config.d.ts.map +1 -1
  120. package/dist/types/codama/accounts/contractState.d.ts +26 -0
  121. package/dist/types/codama/accounts/contractState.d.ts.map +1 -1
  122. package/dist/types/codama/accounts/rentalState.d.ts +20 -2
  123. package/dist/types/codama/accounts/rentalState.d.ts.map +1 -1
  124. package/dist/types/codama/errors/srsly.d.ts +9 -1
  125. package/dist/types/codama/errors/srsly.d.ts.map +1 -1
  126. package/dist/types/codama/instructions/acceptRental.d.ts +13 -20
  127. package/dist/types/codama/instructions/acceptRental.d.ts.map +1 -1
  128. package/dist/types/codama/instructions/closeRental.d.ts +33 -13
  129. package/dist/types/codama/instructions/closeRental.d.ts.map +1 -1
  130. package/dist/types/codama/instructions/index.d.ts +1 -0
  131. package/dist/types/codama/instructions/index.d.ts.map +1 -1
  132. package/dist/types/codama/instructions/payRental.d.ts +11 -18
  133. package/dist/types/codama/instructions/payRental.d.ts.map +1 -1
  134. package/dist/types/codama/instructions/resetContractTemp.d.ts +71 -0
  135. package/dist/types/codama/instructions/resetContractTemp.d.ts.map +1 -0
  136. package/dist/types/codama/instructions/resetRental.d.ts +21 -17
  137. package/dist/types/codama/instructions/resetRental.d.ts.map +1 -1
  138. package/dist/types/codama/instructions/updateConfig.d.ts +20 -4
  139. package/dist/types/codama/instructions/updateConfig.d.ts.map +1 -1
  140. package/dist/types/codama/programs/srsly.d.ts +6 -3
  141. package/dist/types/codama/programs/srsly.d.ts.map +1 -1
  142. package/dist/types/codama/types/paymentFrequency.d.ts +31 -0
  143. package/dist/types/codama/types/paymentFrequency.d.ts.map +1 -1
  144. package/dist/types/contract/close.d.ts +77 -16
  145. package/dist/types/contract/close.d.ts.map +1 -1
  146. package/dist/types/contract/create.d.ts +114 -17
  147. package/dist/types/contract/create.d.ts.map +1 -1
  148. package/dist/types/contract/index.d.ts +45 -0
  149. package/dist/types/contract/index.d.ts.map +1 -1
  150. package/dist/types/index.d.ts +111 -1
  151. package/dist/types/index.d.ts.map +1 -1
  152. package/dist/types/rental/accept.d.ts +121 -50
  153. package/dist/types/rental/accept.d.ts.map +1 -1
  154. package/dist/types/rental/cancel.d.ts +80 -16
  155. package/dist/types/rental/cancel.d.ts.map +1 -1
  156. package/dist/types/rental/close.d.ts +86 -26
  157. package/dist/types/rental/close.d.ts.map +1 -1
  158. package/dist/types/rental/index.d.ts +85 -0
  159. package/dist/types/rental/index.d.ts.map +1 -1
  160. package/dist/types/rental/reset-contract-temp.d.ts +77 -0
  161. package/dist/types/rental/reset-contract-temp.d.ts.map +1 -0
  162. package/dist/types/rental/reset.d.ts +114 -24
  163. package/dist/types/rental/reset.d.ts.map +1 -1
  164. package/dist/types/utils/config.d.ts +14 -2
  165. package/dist/types/utils/config.d.ts.map +1 -1
  166. package/dist/types/utils/constants.d.ts +1 -1
  167. package/dist/types/utils/constants.d.ts.map +1 -1
  168. package/dist/types/utils/index.d.ts +1 -0
  169. package/dist/types/utils/index.d.ts.map +1 -1
  170. package/dist/types/utils/instruction-converter.d.ts +70 -20
  171. package/dist/types/utils/instruction-converter.d.ts.map +1 -1
  172. package/dist/types/utils/paymentFrequency.d.ts +3 -3
  173. package/dist/types/utils/paymentFrequency.d.ts.map +1 -1
  174. package/dist/types/utils/pda.d.ts +120 -0
  175. package/dist/types/utils/pda.d.ts.map +1 -0
  176. package/package.json +5 -5
  177. package/target/idl/srsly.json +318 -94
@@ -1,92 +1,211 @@
1
- import { getModule, createConfigSelector, resolveProgramAddresses } from '../utils/config';
1
+ import { getModule, createConfigSelector, resolveProgramAddresses, getConfig } from '../utils/config';
2
2
  import { ATLAS_TO_STARDUST, toAddress } from '../utils/constants';
3
3
  import { deriveGameAccounts } from '../utils';
4
- import { createFluentInstruction, createFluentConfigSelector } from '../utils/instruction-converter';
4
+ import { createFluentInstruction, createSmartFluentConfigSelector } from '../utils/instruction-converter';
5
+ import { fetchMaybeContractState } from '../codama/accounts';
6
+ import { createSolanaRpc } from '@solana/kit';
7
+ import { paymentFrequencyStringToSeconds } from '../utils/paymentFrequency';
8
+ import { deriveRentalThread, deriveRentalState, deriveRentalAuthority } from '../utils/pda';
5
9
  /**
6
- * Internal function to accept a rental instruction with configuration options
10
+ * Internal function to accept a rental instruction with configuration options.
11
+ *
12
+ * This function handles the core logic of creating a rental acceptance instruction,
13
+ * including contract state fetching, payment calculation, account derivation, and
14
+ * instruction generation. It automatically validates contract constraints and
15
+ * calculates the required payment amount.
16
+ *
17
+ * @internal
18
+ * @param params - The rental acceptance parameters
19
+ * @param config - Optional configuration for network and program settings
20
+ * @returns Promise resolving to a fluent instruction object
21
+ * @throws Error when contract is not found, duration constraints are violated, or account derivation fails
7
22
  */
8
23
  async function _acceptRental(params, config) {
9
- const { borrower, borrowerProfile, borrowerFaction, fleet, contract, rate, duration, referralTokenAccount, } = params;
24
+ const { borrower, borrowerProfile, borrowerFaction, contract, duration, } = params;
10
25
  // Get the resolved addresses from config (including network-specific addresses)
11
- const resolvedAddresses = resolveProgramAddresses(config || {});
12
- // Calculate the total amount from rate and duration
13
- // Convert ATLAS to stardust (smallest unit): 1 ATLAS = 100,000,000 stardust
14
- const amount = BigInt(rate) * BigInt(duration) * BigInt(ATLAS_TO_STARDUST);
15
- // Derive the three accounts we need
26
+ // Use global config as fallback, same pattern as constants.ts
27
+ const globalConfig = getConfig();
28
+ const effectiveConfig = { ...globalConfig, ...config };
29
+ const resolvedAddresses = await resolveProgramAddresses(effectiveConfig);
30
+ // Fetch contract state to get payment frequency and validate parameters
31
+ let contractState;
32
+ try {
33
+ // Create RPC from resolved addresses
34
+ const rpc = createSolanaRpc(resolvedAddresses.rpcUrl);
35
+ contractState = await fetchMaybeContractState(rpc, toAddress(contract));
36
+ if (!contractState.exists) {
37
+ throw new Error(`Contract not found: ${contract}`);
38
+ }
39
+ }
40
+ catch (error) {
41
+ throw new Error(`Failed to fetch contract state: ${error}`);
42
+ }
43
+ // Extract data from contract state
44
+ const rate = Number(contractState.data.rate);
45
+ const fleet = contractState.data.fleet;
46
+ // Validate duration constraints
47
+ const durationMin = Number(contractState.data.durationMin);
48
+ const durationMax = Number(contractState.data.durationMax);
49
+ const durationNumber = Number(duration);
50
+ if (durationNumber < durationMin || durationNumber > durationMax) {
51
+ throw new Error(`Duration ${durationNumber} seconds is outside contract constraints (${durationMin}-${durationMax} seconds)`);
52
+ }
53
+ // Calculate amount based on payment frequency and periods (matching program logic)
54
+ const paymentFrequencySeconds = paymentFrequencyStringToSeconds(contractState.data.paymentsFeq);
55
+ const paymentPeriods = Math.floor(durationNumber / paymentFrequencySeconds);
56
+ // Use the config's stardust_to_atlas conversion factor (defaulting to ATLAS_TO_STARDUST for now)
57
+ const stardustToAtlas = ATLAS_TO_STARDUST; // TODO: Get from config account
58
+ const amount = BigInt(rate) * BigInt(paymentPeriods) * BigInt(stardustToAtlas);
59
+ // Manually derive ALL game accounts - they all use different program addresses than main SAGE program
16
60
  const { profileFaction, starbase, starbasePlayer } = await deriveGameAccounts(toAddress(borrowerProfile), borrowerFaction, resolvedAddresses.gameId, 0, // starbaseSeqId
17
61
  config);
18
- // Let codama derive the rest (rentalThread, rentalState, rentalAuthority, etc.)
62
+ // Manually derive PDAs with correct program IDs
63
+ const rentalStatePda = await deriveRentalState(toAddress(contract), borrower.address, // Extract address from signer
64
+ resolvedAddresses.srslyProgramAddress);
65
+ const rentalAuthorityPda = await deriveRentalAuthority(resolvedAddresses.srslyProgramAddress);
66
+ // 🔧 FIX: Derive rental thread PDA using Antegen program ID
67
+ const rentalThreadPda = await deriveRentalThread(rentalAuthorityPda, rentalStatePda, resolvedAddresses.antegenProgramAddress);
68
+ // Create input with ALL manually derived game accounts - they use different program addresses
19
69
  const input = {
20
- borrower, // Pass as-is (string or signer)
70
+ borrower: borrower, // Pass signer directly to Codama
21
71
  borrowerProfile: toAddress(borrowerProfile), // Ensure string
22
- borrowerProfileFaction: profileFaction, // Already string from deriveGameAccounts
72
+ borrowerProfileFaction: toAddress(profileFaction), // Manually derived (Profile program)
23
73
  fleet: toAddress(fleet), // Ensure string
24
74
  contract: toAddress(contract), // Ensure string
25
75
  gameId: resolvedAddresses.gameId, // Already Address from resolveProgramAddresses
26
- starbase, // Already string from deriveGameAccounts
27
- starbasePlayer, // Already string from deriveGameAccounts
76
+ starbase: toAddress(starbase), // Manually derived (SAGE program but different derivation)
77
+ starbasePlayer: toAddress(starbasePlayer), // Manually derived (SAGE program but different derivation)
78
+ mint: resolvedAddresses.atlasMint, // ATLAS mint from config
79
+ sageProgram: resolvedAddresses.sageProgramAddress, // SAGE program from config
80
+ antegenProgram: resolvedAddresses.antegenProgramAddress, // Antegen program from config
81
+ // Override PDAs with correctly derived addresses
82
+ rentalState: rentalStatePda,
83
+ rentalAuthority: rentalAuthorityPda,
84
+ rentalThread: rentalThreadPda, // Uses Antegen program ID!
28
85
  amount, // BigInt value
29
86
  duration, // BigInt value
30
- referralTokenAccount: referralTokenAccount ? toAddress(referralTokenAccount) : undefined,
31
87
  };
32
88
  // Get network-specific codama functions from centralized config
33
89
  const instructionsModule = getModule('instructions');
34
- const programsModule = getModule('programs');
35
90
  const { getAcceptRentalInstructionAsync } = instructionsModule;
36
- const { SRSLY_PROGRAM_ADDRESS } = programsModule;
37
- const rawInstruction = await getAcceptRentalInstructionAsync(input, { programAddress: SRSLY_PROGRAM_ADDRESS });
91
+ const rawInstruction = await getAcceptRentalInstructionAsync(input, { programAddress: resolvedAddresses.srslyProgramAddress });
38
92
  return createFluentInstruction(rawInstruction);
39
93
  }
40
94
  /**
41
- * Creates an instruction to accept a rental with fluent configuration.
95
+ * Creates an instruction to accept a rental contract with fluent configuration.
96
+ *
97
+ * This function allows a borrower to accept an existing rental contract, automatically
98
+ * calculating the required payment amount based on the contract's rate and payment frequency.
99
+ * The SDK fetches contract details, validates duration constraints, and derives all
100
+ * necessary accounts for the rental operation.
101
+ *
102
+ * ## Features
103
+ *
104
+ * - **Automatic Payment Calculation**: Fetches contract state and calculates exact payment amount
105
+ * - **Duration Validation**: Ensures rental duration meets contract constraints
106
+ * - **Account Derivation**: Automatically derives all required game accounts
107
+ * - **SAGE Integration**: Sets up fleet ownership transfer in the Star Atlas ecosystem
108
+ * - **Clockwork Integration**: Configures automated payment scheduling
109
+ * - **Universal Library Support**: Works with both @solana/kit and @solana/web3.js
110
+ *
111
+ * ## Process
112
+ *
113
+ * 1. **Fetch Contract**: Retrieves contract state from the blockchain
114
+ * 2. **Validate Duration**: Checks that rental duration meets contract constraints
115
+ * 3. **Calculate Payment**: Computes payment amount using contract rate and payment frequency
116
+ * 4. **Derive Accounts**: Generates required game accounts (starbase, faction, etc.)
117
+ * 5. **Create Instruction**: Builds the rental acceptance instruction
118
+ * 6. **Setup Threading**: Configures automated payment processing
119
+ *
120
+ * ## Payment Calculation
121
+ *
122
+ * The payment amount is calculated using the formula:
123
+ * ```text
124
+ * payment = rate × payment_periods × stardust_to_atlas_conversion
125
+ * ```
126
+ *
127
+ * Where:
128
+ * - `rate`: Contract's rental rate per payment period
129
+ * - `payment_periods`: Duration divided by payment frequency interval
130
+ * - `stardust_to_atlas_conversion`: Network-specific conversion factor
131
+ *
132
+ * ## Requirements
133
+ *
134
+ * - Contract must exist and be active
135
+ * - Duration must be within contract's min/max limits
136
+ * - Duration must be multiple of payment frequency
137
+ * - Borrower must have sufficient ATLAS tokens for payment
42
138
  *
43
139
  * @example
44
140
  * ```typescript
45
- * // Works with any library - just use strings for addresses!
141
+ * import { acceptRental, days } from '@srsly/sdk';
142
+ *
143
+ * // Basic rental acceptance
46
144
  * const instruction = await acceptRental({
47
- * borrower: wallet, // Can be signer object or string
48
- * borrowerProfile: "ProfileAddr...", // String address
49
- * borrowerFaction: 1, // 1 = mud, 2 = oni, 3 = ustur
50
- * fleet: "FleetAddress123...", // String address
51
- * contract: "ContractAddr...", // String address
52
- * rate: 1000, // ATLAS tokens
53
- * duration: 86400 // 1 day in seconds (total: 1000 * 86400 * 100M stardust)
145
+ * borrower: wallet, // Borrower's wallet
146
+ * borrowerProfile: "ProfileAddr...", // Borrower's Star Atlas profile
147
+ * borrowerFaction: 'mud', // Faction: 'mud', 'oni', or 'ustur'
148
+ * contract: "ContractAddr...", // Contract to accept
149
+ * duration: days(7) // 7 days rental duration
54
150
  * });
55
151
  *
56
- * // With referral (referrer gets 5% of platform fees)
57
- * const instruction = await acceptRental({
152
+ * // Configure for mainnet
153
+ * const mainnetInstruction = await acceptRental({
58
154
  * borrower: wallet,
59
155
  * borrowerProfile: "ProfileAddr...",
60
- * borrowerFaction: 1,
61
- * fleet: "FleetAddress123...",
156
+ * borrowerFaction: 1, // Can use numbers: 1=mud, 2=oni, 3=ustur
62
157
  * contract: "ContractAddr...",
63
- * rate: 1000,
64
- * duration: 86400,
65
- * referralTokenAccount: "ReferralAddr..."
66
- * });
158
+ * duration: days(7)
159
+ * }).set({ programs: 'mainnet' });
67
160
  *
68
- * // Use mainnet configuration
69
- * const instruction = await acceptRental(params).set({ programs: 'mainnet' });
70
- *
71
- * // Override specific constants
72
- * const instruction = await acceptRental(params).set({
161
+ * // Override specific game configuration
162
+ * const customInstruction = await acceptRental({
163
+ * borrower: wallet,
164
+ * borrowerProfile: "ProfileAddr...",
165
+ * borrowerFaction: 'mud',
166
+ * contract: "ContractAddr...",
167
+ * duration: days(7)
168
+ * }).set({
73
169
  * programs: 'mainnet',
74
- * gameId: 'custom-game-id...' // gameId configured via .set()
170
+ * gameId: 'custom-game-id...'
75
171
  * });
76
172
  *
77
- * // Use the instruction with your preferred Solana library
78
- * // instruction is compatible with both @solana/kit and @solana/web3.js
173
+ * // Convert to @solana/web3.js format
174
+ * const web3jsInstruction = await acceptRental({
175
+ * borrower: wallet,
176
+ * borrowerProfile: "ProfileAddr...",
177
+ * borrowerFaction: 'mud',
178
+ * contract: "ContractAddr...",
179
+ * duration: days(7)
180
+ * }).web3js();
181
+ *
182
+ * // Use with your preferred Solana library
183
+ * const transaction = new Transaction().add(web3jsInstruction);
184
+ * await sendAndConfirmTransaction(connection, transaction, [wallet]);
79
185
  * ```
80
186
  *
81
- * @param params The simplified parameters for accepting a rental
82
- * @returns A ConfigSelector that can be configured with .set() or awaited directly
187
+ * @param params - The rental acceptance parameters including borrower, contract, and duration
188
+ * @returns A FluentConfigSelector that can be configured with .set() or awaited directly
189
+ * @throws Error when contract is not found, duration constraints are violated, or payment calculation fails
83
190
  */
84
191
  export function acceptRental(params) {
85
192
  const baseSelector = createConfigSelector((config) => _acceptRental(params, config));
86
- return createFluentConfigSelector(baseSelector);
193
+ return createSmartFluentConfigSelector(baseSelector);
87
194
  }
195
+ /**
196
+ * Low-level function to create a rental acceptance instruction with raw input parameters.
197
+ *
198
+ * This function provides direct access to the underlying codama-generated instruction
199
+ * builder. It's primarily used internally by the SDK but can be used for advanced
200
+ * use cases where full control over instruction parameters is needed.
201
+ *
202
+ * @internal
203
+ * @param input - Raw instruction input parameters as expected by codama
204
+ * @param options - Optional instruction options including program address
205
+ * @returns A ConfigSelector for the raw instruction
206
+ */
88
207
  export function getAcceptRentalInstructionAsync(input, options) {
89
- return createConfigSelector(async (config) => {
208
+ return createConfigSelector(async () => {
90
209
  const instructionsModule = getModule('instructions');
91
210
  return instructionsModule.getAcceptRentalInstructionAsync(input, options);
92
211
  });
@@ -1 +1 @@
1
- {"version":3,"file":"accept.js","sourceRoot":"","sources":["../../../src/rental/accept.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,u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,CAAC,cAAc,CAAC,CAAC;IACrD,MAAM,EAAE,+BAA+B,EAAE,GAAG,kBAAkB,CAAC;IAE/D,MAAM,cAAc,GAAG,MAAM,+BAA+B,CAC1D,KAAY,EACZ,EAAE,cAAc,EAAE,iBAAiB,CAAC,mBAAmB,EAAE,CAC1D,CAAC;IACF,OAAO,uBAAuB,CAAC,cAAc,CAAC,CAAC;AACjD,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgGG;AACH,MAAM,UAAU,YAAY,CAC1B,MAA0B;IAE1B,MAAM,YAAY,GAAG,oBAAoB,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACrF,OAAO,+BAA+B,CAAC,YAAY,CAAC,CAAC;AACvD,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,+BAA+B,CAAC,KAAU,EAAE,OAAa;IACvE,OAAO,oBAAoB,CAAC,KAAK,IAAI,EAAE;QACrC,MAAM,kBAAkB,GAAG,SAAS,CAAC,cAAc,CAAC,CAAC;QACrD,OAAO,kBAAkB,CAAC,+BAA+B,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -1,15 +1,26 @@
1
- import { getModule, createConfigSelector, resolveProgramAddresses } from '../utils/config';
1
+ import { getModule, createConfigSelector } from '../utils/config';
2
2
  import { toAddress } from '../utils/constants';
3
3
  /**
4
- * Internal function to cancel a rental instruction with configuration options
4
+ * Internal function to cancel a rental instruction with configuration options.
5
+ *
6
+ * This function handles the core logic of creating a rental cancellation instruction,
7
+ * including address resolution and instruction generation. The cancellation stops
8
+ * automated payments and may incur penalty fees.
9
+ *
10
+ * @internal
11
+ * @param params - The rental cancellation parameters
12
+ * @param config - Optional configuration for network and program settings
13
+ * @returns Promise resolving to a cancellation instruction
14
+ * @throws Error when instruction generation fails or required parameters are missing
5
15
  */
6
16
  async function _cancelRental(params, config) {
7
17
  const { borrower, contract, } = params;
8
18
  // Get the resolved addresses from config (including network-specific addresses)
9
- const resolvedAddresses = resolveProgramAddresses(config || {});
19
+ // Note: resolvedAddresses not currently needed for this instruction but kept for consistency
20
+ // const resolvedAddresses = resolveProgramAddresses(config || {});
10
21
  // Let codama derive all the optional accounts
11
22
  const input = {
12
- borrower, // Pass as-is (string or signer)
23
+ borrower, // Pass signer directly to Codama
13
24
  contract: toAddress(contract), // Ensure string
14
25
  };
15
26
  // Get network-specific codama functions from centralized config
@@ -22,34 +33,89 @@ async function _cancelRental(params, config) {
22
33
  /**
23
34
  * Creates an instruction to cancel a rental with fluent configuration.
24
35
  *
36
+ * This function allows a borrower to cancel their active rental before the
37
+ * rental period expires. Canceling a rental stops automated payments but
38
+ * may incur penalty fees as defined in the contract terms. The fleet ownership
39
+ * is immediately returned to the original owner.
40
+ *
41
+ * ## Features
42
+ *
43
+ * - **Immediate Cancellation**: Stops the rental and automated payments immediately
44
+ * - **Fleet Transfer**: Returns fleet control to the original owner
45
+ * - **Thread Cleanup**: Cancels the automated payment thread
46
+ * - **Penalty Processing**: Handles any cancellation fees as defined in the contract
47
+ * - **Universal Library Support**: Works with both @solana/kit and @solana/web3.js
48
+ *
49
+ * ## Process
50
+ *
51
+ * 1. **Validate Authority**: Ensures only the borrower can cancel their rental
52
+ * 2. **Calculate Penalties**: Computes any cancellation fees owed
53
+ * 3. **Transfer Fleet**: Returns fleet ownership to the original owner
54
+ * 4. **Cancel Thread**: Stops automated payment processing
55
+ * 5. **Update State**: Marks rental as canceled in the rental state account
56
+ *
57
+ * ## Requirements
58
+ *
59
+ * - Rental must be active (not already canceled or completed)
60
+ * - Caller must be the original borrower
61
+ * - Borrower must have sufficient funds for any cancellation penalties
62
+ *
63
+ * ## Cancellation Effects
64
+ *
65
+ * - **Fleet Control**: Immediately returned to owner
66
+ * - **Automated Payments**: Stopped permanently
67
+ * - **Rental State**: Marked as canceled
68
+ * - **Thread Account**: Cleaned up and closed
69
+ * - **Penalties**: Charged according to contract terms
70
+ *
25
71
  * @example
26
72
  * ```typescript
27
- * // Works with any library - just use strings for addresses!
73
+ * import { cancelRental } from '@srsly/sdk';
74
+ *
75
+ * // Basic rental cancellation
28
76
  * const instruction = await cancelRental({
29
- * borrower: wallet, // Can be signer object or string
30
- * contract: "ContractAddr..." // String address
77
+ * borrower: wallet, // Borrower's wallet (must be original borrower)
78
+ * contract: "ContractAddr..." // Contract address for the active rental
31
79
  * });
32
80
  *
33
- * // Use mainnet configuration
34
- * const instruction = await cancelRental(params).set({ programs: 'mainnet' });
81
+ * // Configure for mainnet
82
+ * const mainnetInstruction = await cancelRental({
83
+ * borrower: wallet,
84
+ * contract: "ContractAddr..."
85
+ * }).set({ programs: 'mainnet' });
35
86
  *
36
- * // Override specific constants
37
- * const instruction = await cancelRental(params).set({
38
- * programs: 'mainnet'
39
- * });
87
+ * // Convert to @solana/web3.js format
88
+ * const web3jsInstruction = await cancelRental({
89
+ * borrower: wallet,
90
+ * contract: "ContractAddr..."
91
+ * }).web3js();
40
92
  *
41
- * // Use the instruction with your preferred Solana library
42
- * // instruction is compatible with both @solana/kit and @solana/web3.js
93
+ * // Use with your preferred Solana library
94
+ * const transaction = new Transaction().add(web3jsInstruction);
95
+ * await sendAndConfirmTransaction(connection, transaction, [wallet]);
43
96
  * ```
44
97
  *
45
- * @param params The simplified parameters for canceling a rental
98
+ * @param params - The rental cancellation parameters including borrower and contract
46
99
  * @returns A ConfigSelector that can be configured with .set() or awaited directly
100
+ * @throws Error when rental is not active, caller is not the borrower, or instruction generation fails
47
101
  */
48
102
  export function cancelRental(params) {
49
103
  return createConfigSelector((config) => _cancelRental(params, config));
50
104
  }
105
+ /**
106
+ * Low-level function to create a rental cancellation instruction with raw input parameters.
107
+ *
108
+ * This function provides direct access to the underlying codama-generated instruction
109
+ * builder. It's primarily used internally by the SDK but can be used for advanced
110
+ * use cases where full control over instruction parameters is needed.
111
+ *
112
+ * @internal
113
+ * @param input - Raw instruction input parameters as expected by codama
114
+ * @param options - Optional instruction options including program address
115
+ * @returns A ConfigSelector for the raw instruction
116
+ */
51
117
  export function getCancelRentalInstructionAsync(input, options) {
52
- return createConfigSelector(async (config) => {
118
+ return createConfigSelector(async () => {
53
119
  const instructionsModule = getModule('instructions');
54
120
  return instructionsModule.getCancelRentalInstructionAsync(input, options);
55
121
  });
@@ -1 +1 @@
1
- {"version":3,"file":"cancel.js","sourceRoot":"","sources":["../../../src/rental/cancel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,uBAAuB,EAA2C,MAAM,iBAAiB,CAAC;AACpI,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAsB/C;;GAEG;AACH,KAAK,UAAU,aAAa,CAC1B,MAA0B,EAC1B,MAAsB;IAEtB,MAAM,EACJ,QAAQ,EACR,QAAQ,GACT,GAAG,MAAM,CAAC;IAEX,gFAAgF;IAChF,MAAM,iBAAiB,GAAG,uBAAuB,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;IAEhE,8CAA8C;IAC9C,MAAM,KAAK,GAAG;QACZ,QAAQ,EAAqB,gCAAgC;QAC7D,QAAQ,EAAE,SAAS,CAAC,QAAQ,CAAC,EAAE,gBAAgB;KAChD,CAAC;IAEF,gEAAgE;IAChE,MAAM,kBAAkB,GAAG,SAAS,CAAC,cAAc,CAAC,CAAC;IACrD,MAAM,cAAc,GAAG,SAAS,CAAC,UAAU,CAAC,CAAC;IAC7C,MAAM,EAAE,+BAA+B,EAAE,GAAG,kBAAkB,CAAC;IAC/D,MAAM,EAAE,qBAAqB,EAAE,GAAG,cAAc,CAAC;IAEjD,OAAO,+BAA+B,CACpC,KAAK,EACL,EAAE,cAAc,EAAE,qBAAqB,EAAE,CAC1C,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;;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AAE,cAAc,EAAE,qBAAqB,EAAE,CAC1C,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AACH,MAAM,UAAU,YAAY,CAC1B,MAA0B;IAE1B,OAAO,oBAAoB,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AACzE,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,+BAA+B,CAAC,KAAU,EAAE,OAAa;IACvE,OAAO,oBAAoB,CAAC,KAAK,IAAI,EAAE;QACrC,MAAM,kBAAkB,GAAG,SAAS,CAAC,cAAc,CAAC,CAAC;QACrD,OAAO,kBAAkB,CAAC,+BAA+B,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -1,57 +1,182 @@
1
1
  import { getModule, createConfigSelector, resolveProgramAddresses } from '../utils/config';
2
2
  import { toAddress } from '../utils/constants';
3
+ import { createFluentInstruction, createSmartFluentConfigSelector } from '../utils/instruction-converter';
4
+ import { fetchMaybeRentalState, fetchMaybeContractState, fetchMaybeConfig } from '../codama/accounts';
5
+ import { createSolanaRpc, getProgramDerivedAddress, getBytesEncoder } from '@solana/kit';
6
+ import { deriveRentalThread, deriveRentalAuthority } from '../utils/pda';
3
7
  /**
4
- * Internal function to close a rental instruction with configuration options
8
+ * Internal function to close a rental instruction with configuration options.
9
+ *
10
+ * This function handles the core logic of creating a rental closure instruction,
11
+ * including address resolution and instruction generation. The closure finalizes
12
+ * the rental period and transfers any remaining funds to the owner.
13
+ *
14
+ * @internal
15
+ * @param params - The rental closure parameters
16
+ * @param config - Optional configuration for network and program settings
17
+ * @returns Promise resolving to a closure instruction
18
+ * @throws Error when instruction generation fails or required parameters are missing
5
19
  */
6
20
  async function _closeRental(params, config) {
7
- const { borrower, ownerTokenAccount, contract, } = params;
21
+ const { payer, rentalStateAddress, } = params;
8
22
  // Get the resolved addresses from config (including network-specific addresses)
9
- const resolvedAddresses = resolveProgramAddresses(config || {});
10
- // Let codama derive the optional accounts
23
+ const resolvedAddresses = await resolveProgramAddresses(config || {});
24
+ // Create RPC from resolved addresses
25
+ const rpc = createSolanaRpc(resolvedAddresses.rpcUrl);
26
+ // Fetch rental state to get contract and borrower
27
+ let rentalState;
28
+ try {
29
+ if (!rentalStateAddress) {
30
+ throw new Error(`rentalStateAddress is ${rentalStateAddress}, cannot proceed`);
31
+ }
32
+ rentalState = await fetchMaybeRentalState(rpc, toAddress(rentalStateAddress));
33
+ if (!rentalState.exists) {
34
+ throw new Error(`Rental state not found: ${rentalStateAddress}`);
35
+ }
36
+ }
37
+ catch (error) {
38
+ throw new Error(`Failed to fetch rental state: ${error}`);
39
+ }
40
+ // Extract required addresses from rental state
41
+ const contractAddress = rentalState.data.contract;
42
+ const borrower = rentalState.data.borrower;
43
+ // Derive PDAs similar to accept.ts
44
+ const rentalAuthorityPda = await deriveRentalAuthority(resolvedAddresses.srslyProgramAddress.toString());
45
+ // 🔧 FIX: Derive rental thread PDA using Antegen program ID and the passed-in rental state address
46
+ const rentalThreadPda = await deriveRentalThread(rentalAuthorityPda, toAddress(rentalStateAddress), // Use the passed-in rental state address
47
+ resolvedAddresses.antegenProgramAddress);
48
+ // Fetch contract state to get owner
49
+ let contractState;
50
+ try {
51
+ contractState = await fetchMaybeContractState(rpc, toAddress(contractAddress));
52
+ if (!contractState.exists) {
53
+ throw new Error(`Contract not found: ${contractAddress}`);
54
+ }
55
+ }
56
+ catch (error) {
57
+ throw new Error(`Failed to fetch contract state: ${error}`);
58
+ }
59
+ // Fetch config state to get the authority (we already have mint from resolved addresses)
60
+ const [configPda] = await getProgramDerivedAddress({
61
+ programAddress: resolvedAddresses.srslyProgramAddress,
62
+ seeds: [
63
+ getBytesEncoder().encode(new Uint8Array([99, 111, 110, 102, 105, 103])), // "config"
64
+ ],
65
+ });
66
+ let configState;
67
+ try {
68
+ configState = await fetchMaybeConfig(rpc, configPda);
69
+ if (!configState.exists) {
70
+ throw new Error(`Config not found: ${configPda}`);
71
+ }
72
+ }
73
+ catch (error) {
74
+ throw new Error(`Failed to fetch config state: ${error}`);
75
+ }
76
+ // Only provide required fields - let Codama auto-generate the rest except rental_thread
11
77
  const input = {
12
- borrower: toAddress(borrower), // Ensure string
13
- ownerTokenAccount: toAddress(ownerTokenAccount), // Ensure string
14
- contract: toAddress(contract), // Ensure string
78
+ payer: payer, // Pass the signer directly to Codama
79
+ mint: resolvedAddresses.atlasMint, // Use resolved ATLAS mint from config
80
+ authority: toAddress(configState.data.authority), // Config authority for fee collection
81
+ borrower: toAddress(borrower),
82
+ owner: toAddress(contractState.data.owner),
83
+ contract: toAddress(contractAddress),
84
+ // Only override rental_thread since Codama can't auto-generate this one
85
+ rentalThread: rentalThreadPda, // Uses Antegen program ID!
15
86
  };
16
87
  // Get network-specific codama functions from centralized config
17
88
  const instructionsModule = getModule('instructions');
18
- const programsModule = getModule('programs');
19
89
  const { getCloseRentalInstructionAsync } = instructionsModule;
20
- const { SRSLY_PROGRAM_ADDRESS } = programsModule;
21
- return getCloseRentalInstructionAsync(input, { programAddress: SRSLY_PROGRAM_ADDRESS });
90
+ const rawInstruction = await getCloseRentalInstructionAsync(input, { programAddress: resolvedAddresses.srslyProgramAddress });
91
+ return createFluentInstruction(rawInstruction);
22
92
  }
23
93
  /**
24
- * Creates an instruction to close a rental with fluent configuration.
94
+ * Creates an instruction to close a completed rental with fluent configuration.
95
+ *
96
+ * This function finalizes a rental that has reached its expiration or been fully paid.
97
+ * It transfers any remaining funds to the owner, returns fleet control, and cleans up
98
+ * the rental state account. This instruction can be called by anyone once the rental
99
+ * period has ended.
100
+ *
101
+ * ## Features
102
+ *
103
+ * - **Rental Finalization**: Properly closes completed or expired rentals
104
+ * - **Fund Transfer**: Moves any remaining payments or deposits to the owner
105
+ * - **Fleet Return**: Ensures fleet ownership is returned to the original owner
106
+ * - **State Cleanup**: Closes rental state account and returns lamports
107
+ * - **Thread Cleanup**: Cleans up automated payment threads
108
+ * - **Universal Library Support**: Works with both @solana/kit and @solana/web3.js
109
+ *
110
+ * ## Process
111
+ *
112
+ * 1. **Validate Completion**: Ensures rental period has ended or been fully paid
113
+ * 2. **Transfer Funds**: Moves any remaining ATLAS tokens to owner's account
114
+ * 3. **Return Fleet**: Transfers fleet ownership back to original owner
115
+ * 4. **Clean State**: Closes rental state account and returns SOL to payer
116
+ * 5. **Cancel Thread**: Cleans up any remaining automated payment threads
117
+ *
118
+ * ## Requirements
119
+ *
120
+ * - Rental must be completed or expired
121
+ * - Owner token account must be valid ATLAS token account
122
+ * - Rental state account must exist and be properly initialized
123
+ *
124
+ * ## When to Use
125
+ *
126
+ * - **Natural Expiration**: When rental period has ended
127
+ * - **Full Payment**: When all required payments have been made
128
+ * - **Account Cleanup**: To close expired rental accounts and recover SOL
129
+ * - **Fleet Recovery**: When fleet needs to be returned to owner
25
130
  *
26
131
  * @example
27
132
  * ```typescript
28
- * // Works with any library - just use strings for addresses!
133
+ * import { closeRental } from '@srsly/sdk';
134
+ *
135
+ * // Close a completed rental
29
136
  * const instruction = await closeRental({
30
- * borrower: "BorrowerAddr...", // String address
31
- * ownerTokenAccount: "TokenAcct...", // String address
32
- * contract: "ContractAddr..." // String address
137
+ * payer: wallet, // Transaction payer
138
+ * rentalStateAddress: "RentalState..." // Rental state address
33
139
  * });
34
140
  *
35
- * // Use mainnet configuration
36
- * const instruction = await closeRental(params).set({ programs: 'mainnet' });
141
+ * // Configure for mainnet
142
+ * const mainnetInstruction = await closeRental({
143
+ * payer: wallet,
144
+ * rentalStateAddress: "RentalState..."
145
+ * }).set({ programs: 'mainnet' });
37
146
  *
38
- * // Override specific constants
39
- * const instruction = await closeRental(params).set({
40
- * programs: 'mainnet'
41
- * });
147
+ * // Convert to @solana/web3.js format
148
+ * const web3jsInstruction = await closeRental({
149
+ * payer: wallet,
150
+ * rentalStateAddress: "RentalState..."
151
+ * }).web3js();
42
152
  *
43
- * // Use the instruction with your preferred Solana library
44
- * // instruction is compatible with both @solana/kit and @solana/web3.js
153
+ * // Use with your preferred Solana library
154
+ * const transaction = new Transaction().add(web3jsInstruction);
155
+ * await sendAndConfirmTransaction(connection, transaction, [wallet]);
45
156
  * ```
46
157
  *
47
- * @param params The simplified parameters for closing a rental
48
- * @returns A ConfigSelector that can be configured with .set() or awaited directly
158
+ * @param params - The rental closure parameters including payer and rental state address
159
+ * @returns A FluentConfigSelector that can be configured with .set() or awaited directly
160
+ * @throws Error when rental is not ready for closure or instruction generation fails
49
161
  */
50
162
  export function closeRental(params) {
51
- return createConfigSelector((config) => _closeRental(params, config));
163
+ const baseSelector = createConfigSelector((config) => _closeRental(params, config));
164
+ return createSmartFluentConfigSelector(baseSelector);
52
165
  }
166
+ /**
167
+ * Low-level function to create a rental closure instruction with raw input parameters.
168
+ *
169
+ * This function provides direct access to the underlying codama-generated instruction
170
+ * builder. It's primarily used internally by the SDK but can be used for advanced
171
+ * use cases where full control over instruction parameters is needed.
172
+ *
173
+ * @internal
174
+ * @param input - Raw instruction input parameters as expected by codama
175
+ * @param options - Optional instruction options including program address
176
+ * @returns A ConfigSelector for the raw instruction
177
+ */
53
178
  export function getCloseRentalInstructionAsync(input, options) {
54
- return createConfigSelector(async (config) => {
179
+ return createConfigSelector(async () => {
55
180
  const instructionsModule = getModule('instructions');
56
181
  return instructionsModule.getCloseRentalInstructionAsync(input, options);
57
182
  });