-
Notifications
You must be signed in to change notification settings - Fork 244
feat(sdk): add createKitKoraClient for plugin-based gasless transactions #388
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
ecf0cd8
feat(sdk): add createKitKoraClient for plugin-based gasless transactions
amilz 1116689
chore(sdk): add TODO comments for future bundle plan/execute support
amilz 58a9b97
feat(test): add typescript_free integration tests and just test-ts ru…
amilz 4275090
fix: greptile feedback
amilz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| export * from './types/index.js'; | ||
| export { KoraClient } from './client.js'; | ||
| export { createKitKoraClient, type KoraKitClient } from './kit/index.js'; | ||
| export { koraPlugin, type KoraApi } from './plugin.js'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| import { | ||
| type Address, | ||
| appendTransactionMessageInstructions, | ||
| type Base64EncodedWireTransaction, | ||
| blockhash, | ||
| createTransactionMessage, | ||
| createTransactionPlanExecutor, | ||
| getBase64EncodedWireTransaction, | ||
| getBase64Encoder, | ||
| getSignatureFromTransaction, | ||
| getTransactionDecoder, | ||
| type Instruction, | ||
| partiallySignTransactionMessageWithSigners, | ||
| pipe, | ||
| setTransactionMessageFeePayerSigner, | ||
| setTransactionMessageLifetimeUsingBlockhash, | ||
| signature, | ||
| type TransactionMessage, | ||
| type TransactionMessageWithFeePayer, | ||
| type TransactionSigner, | ||
| } from '@solana/kit'; | ||
|
|
||
| import { KoraClient } from '../client.js'; | ||
| import type { KoraKitClientConfig } from '../types/index.js'; | ||
| import { removePaymentInstruction, updatePaymentInstructionAmount } from './payment.js'; | ||
|
|
||
| // TODO: Create a bundle-aware executor (e.g. `createKoraBundlePlanExecutor`) that collects | ||
| // multiple planned transaction messages into a single `signAndSendBundle` call instead of | ||
| // submitting each one individually via `signAndSendTransaction`. This would let users | ||
| // compose Jito bundles through the Kit plan/execute pipeline rather than manually encoding | ||
| // transactions and calling `client.kora.signAndSendBundle()`. | ||
| export function createKoraTransactionPlanExecutor( | ||
| koraClient: KoraClient, | ||
| config: KoraKitClientConfig, | ||
| payerSigner: TransactionSigner, | ||
| payment: { destinationTokenAccount: Address; sourceTokenAccount: Address } | undefined, | ||
| resolveProvisoryComputeUnitLimit: | ||
| | (<T extends TransactionMessage & TransactionMessageWithFeePayer>(transactionMessage: T) => Promise<T>) | ||
| | undefined, | ||
| ) { | ||
| return createTransactionPlanExecutor({ | ||
| async executeTransactionMessage(_context, transactionMessage) { | ||
| // Kora manages blockhash validity; set max height to avoid premature client-side expiry checks | ||
| const { blockhash: bh } = await koraClient.getBlockhash(); | ||
| const msgWithLifetime = setTransactionMessageLifetimeUsingBlockhash( | ||
| { | ||
| blockhash: blockhash(bh), | ||
| lastValidBlockHeight: BigInt(Number.MAX_SAFE_INTEGER), | ||
| }, | ||
| transactionMessage, | ||
| ); | ||
|
|
||
| const msgForEstimation = resolveProvisoryComputeUnitLimit | ||
| ? await resolveProvisoryComputeUnitLimit(msgWithLifetime) | ||
| : msgWithLifetime; | ||
|
|
||
| const prePaymentTx = getBase64EncodedWireTransaction( | ||
| await partiallySignTransactionMessageWithSigners(msgForEstimation), | ||
| ); | ||
|
|
||
| let finalTx: Base64EncodedWireTransaction; | ||
|
|
||
| if (payment) { | ||
| const { sourceTokenAccount, destinationTokenAccount } = payment; | ||
| const { fee_in_token } = await koraClient.estimateTransactionFee({ | ||
| fee_token: config.feeToken, | ||
| transaction: prePaymentTx, | ||
| }); | ||
|
|
||
| if (fee_in_token == null) { | ||
| console.warn( | ||
| '[kora] fee_in_token is undefined — defaulting to 0. ' + | ||
| 'If paid pricing is expected, check that the fee token is correctly configured on the server.', | ||
| ); | ||
| } | ||
| const feeInToken = fee_in_token ?? 0; | ||
|
|
||
| if (feeInToken < 0) { | ||
| throw new Error( | ||
| `Kora fee estimation returned a negative fee (${feeInToken}). This indicates a server-side error.`, | ||
| ); | ||
| } | ||
|
|
||
| const currentIxs = | ||
| 'instructions' in msgForEstimation | ||
| ? (msgForEstimation as { instructions: readonly Instruction[] }).instructions | ||
| : undefined; | ||
|
|
||
| if (!currentIxs) { | ||
| throw new Error( | ||
| 'Cannot extract instructions from transaction message. ' + | ||
| 'The message structure may be incompatible with this version of the Kora SDK.', | ||
| ); | ||
| } | ||
|
|
||
| // Replace placeholder with real fee amount, or strip it if fee is 0 | ||
| const finalIxs = | ||
| feeInToken > 0 | ||
| ? updatePaymentInstructionAmount( | ||
| currentIxs, | ||
| config.feePayerWallet, | ||
| sourceTokenAccount, | ||
| destinationTokenAccount, | ||
| feeInToken, | ||
| config.tokenProgramId, | ||
| ) | ||
| : removePaymentInstruction( | ||
| currentIxs, | ||
| sourceTokenAccount, | ||
| destinationTokenAccount, | ||
| config.feePayerWallet, | ||
| config.tokenProgramId, | ||
| ); | ||
|
|
||
| const resolvedMsg = pipe( | ||
| createTransactionMessage({ version: 0 }), | ||
| m => setTransactionMessageFeePayerSigner(payerSigner, m), | ||
| m => | ||
| setTransactionMessageLifetimeUsingBlockhash( | ||
| { | ||
| blockhash: blockhash(bh), | ||
| lastValidBlockHeight: BigInt(Number.MAX_SAFE_INTEGER), | ||
| }, | ||
| m, | ||
| ), | ||
| m => appendTransactionMessageInstructions(finalIxs, m), | ||
| ); | ||
|
|
||
| finalTx = getBase64EncodedWireTransaction( | ||
| await partiallySignTransactionMessageWithSigners(resolvedMsg), | ||
| ); | ||
| } else { | ||
| finalTx = prePaymentTx; | ||
| } | ||
|
|
||
| const result = await koraClient.signAndSendTransaction({ | ||
| transaction: finalTx, | ||
| user_id: config.userId, | ||
| }); | ||
|
|
||
| if (result.signature) { | ||
| return signature(result.signature); | ||
| } | ||
| const signedTxBytes = getBase64Encoder().encode(result.signed_transaction); | ||
| const decodedTx = getTransactionDecoder().decode(signedTxBytes); | ||
| return getSignatureFromTransaction(decodedTx); | ||
| }, | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| import { address, createEmptyClient, createNoopSigner, createSolanaRpc } from '@solana/kit'; | ||
| import { | ||
| planAndSendTransactions, | ||
| transactionPlanExecutor as transactionPlanExecutorPlugin, | ||
| transactionPlanner as transactionPlannerPlugin, | ||
| } from '@solana/kit-plugin-instruction-plan'; | ||
| import { payer } from '@solana/kit-plugin-payer'; | ||
| import { rpc } from '@solana/kit-plugin-rpc'; | ||
| import { | ||
| estimateAndUpdateProvisoryComputeUnitLimitFactory, | ||
| estimateComputeUnitLimitFactory, | ||
| } from '@solana-program/compute-budget'; | ||
|
|
||
| import { KoraClient } from '../client.js'; | ||
| import { koraPlugin } from '../plugin.js'; | ||
| import type { KoraKitClientConfig } from '../types/index.js'; | ||
| import { createKoraTransactionPlanExecutor } from './executor.js'; | ||
| import { buildPlaceholderPaymentInstruction, koraPaymentAddress } from './payment.js'; | ||
| import { buildComputeBudgetInstructions, createKoraTransactionPlanner } from './planner.js'; | ||
|
|
||
| /** The type returned by {@link createKitKoraClient}. */ | ||
| export type KoraKitClient = Awaited<ReturnType<typeof createKitKoraClient>>; | ||
|
|
||
| /** | ||
| * Creates a Kora Kit client composed from Kit plugins. | ||
| * | ||
| * The returned client satisfies `ClientWithPayer`, `ClientWithTransactionPlanning`, | ||
| * and `ClientWithTransactionSending`, making it composable with Kit program plugins. | ||
| * | ||
| * @beta This API is experimental and may change in future releases. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * import { createKitKoraClient } from '@solana/kora'; | ||
| * import { address } from '@solana/kit'; | ||
| * | ||
| * const client = await createKitKoraClient({ | ||
| * endpoint: 'https://kora.example.com', | ||
| * rpcUrl: 'https://api.mainnet-beta.solana.com', | ||
| * feeToken: address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), | ||
| * feePayerWallet: userSigner, | ||
| * }); | ||
| * | ||
| * const result = await client.sendTransaction([myInstruction]); | ||
| * ``` | ||
| */ | ||
| // TODO: Bundle support — the plan/execute pipeline currently handles single transactions only. | ||
| // For Jito bundles, users must manually encode transactions and call `client.kora.signAndSendBundle()`. | ||
| // A future `createKitKoraBundleClient` (or a bundle-aware executor plugin) could extend this to | ||
| // plan multiple transaction messages and submit them as a single bundle. | ||
| export async function createKitKoraClient(config: KoraKitClientConfig) { | ||
| const koraClient = new KoraClient({ | ||
| apiKey: config.apiKey, | ||
| getRecaptchaToken: config.getRecaptchaToken, | ||
| hmacSecret: config.hmacSecret, | ||
| rpcUrl: config.endpoint, | ||
| }); | ||
|
|
||
| const { signer_address, payment_address } = await koraClient.getPayerSigner(); | ||
| const paymentAddr = payment_address ? address(payment_address) : undefined; | ||
| const payerSigner = createNoopSigner(address(signer_address)); | ||
|
|
||
| const computeBudgetIxs = buildComputeBudgetInstructions(config); | ||
| const solanaRpc = createSolanaRpc(config.rpcUrl); | ||
|
|
||
| const hasCuEstimation = config.computeUnitLimit === undefined; | ||
| const resolveProvisoryComputeUnitLimit = hasCuEstimation | ||
| ? estimateAndUpdateProvisoryComputeUnitLimitFactory(estimateComputeUnitLimitFactory({ rpc: solanaRpc })) | ||
| : undefined; | ||
|
|
||
| const payment = paymentAddr | ||
| ? await buildPlaceholderPaymentInstruction( | ||
| config.feePayerWallet, | ||
| paymentAddr, | ||
| config.feeToken, | ||
| config.tokenProgramId, | ||
| ) | ||
| : undefined; | ||
|
|
||
| const koraTransactionPlanner = createKoraTransactionPlanner( | ||
| payerSigner, | ||
| computeBudgetIxs, | ||
| payment?.instruction, | ||
| hasCuEstimation, | ||
| ); | ||
|
|
||
| const koraTransactionPlanExecutor = createKoraTransactionPlanExecutor( | ||
| koraClient, | ||
| config, | ||
| payerSigner, | ||
amilz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| payment | ||
| ? { | ||
| destinationTokenAccount: payment.destinationTokenAccount, | ||
| sourceTokenAccount: payment.sourceTokenAccount, | ||
| } | ||
| : undefined, | ||
| resolveProvisoryComputeUnitLimit, | ||
| ); | ||
|
|
||
| return createEmptyClient() | ||
| .use(rpc(config.rpcUrl)) | ||
| .use( | ||
| koraPlugin({ | ||
| endpoint: config.endpoint, | ||
| koraClient, | ||
| }), | ||
| ) | ||
| .use(payer(payerSigner)) | ||
| .use(koraPaymentAddress(paymentAddr)) | ||
| .use(transactionPlannerPlugin(koraTransactionPlanner)) | ||
| .use(transactionPlanExecutorPlugin(koraTransactionPlanExecutor)) | ||
| .use(planAndSendTransactions()); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.