Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ fmt:
cargo fmt --all
cd sdks/ts && pnpm format

# Format TypeScript Files
fmt-ts:
cd sdks/ts && pnpm format

# ******************************************************************************
# Testing
# ******************************************************************************
Expand All @@ -85,6 +89,15 @@ integration-test *args: build _ensure-transfer-hook
unit-test-ts: build
-cd sdks/ts && pnpm test:unit

# Run all TypeScript SDK tests (unit + integration)
[group('test')]
[no-exit-message]
test-ts: build _ensure-transfer-hook
cd sdks/ts && pnpm test:unit
cargo run -p tests --bin test_runner -- --filter typescript_basic
cargo run -p tests --bin test_runner -- --filter typescript_auth
cargo run -p tests --bin test_runner -- --filter typescript_free

# Run all tests (unit + TypeScript + integration)
[group('test')]
test: build unit-test unit-test-ts integration-test
Expand Down
744 changes: 421 additions & 323 deletions sdks/pnpm-lock.yaml

Large diffs are not rendered by default.

11 changes: 9 additions & 2 deletions sdks/ts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"test:coverage": "jest --coverage",
"test:integration": "pnpm test integration.test.ts",
"test:integration:auth": "ENABLE_AUTH=true pnpm test integration.test.ts",
"test:integration:free": "FREE_PRICING=true pnpm test integration.test.ts",
"test:integration:privy": "KORA_SIGNER_TYPE=privy pnpm test integration.test.ts",
"test:integration:turnkey": "KORA_SIGNER_TYPE=turnkey pnpm test integration.test.ts",
"test:unit": "pnpm test unit.test.ts",
Expand Down Expand Up @@ -49,15 +50,21 @@
},
"peerDependencies": {
"@solana-program/token": "^0.10.0",
"@solana/kit": "^6.0.0"
"@solana/kit": "^6.1.0",
"@solana/kit-plugin-instruction-plan": "^0.6.0",
"@solana/kit-plugin-payer": "^0.6.0",
"@solana/kit-plugin-rpc": "^0.6.0"
},
"devDependencies": {
"@eslint/js": "^9.39.3",
"@solana-program/compute-budget": "^0.13.0",
"@solana-program/system": "^0.11.0",
"@solana-program/token": "^0.10.0",
"@solana/eslint-config-solana": "6.0.0",
"@solana/kit": "^6.0.0",
"@solana/kit-plugin-instruction-plan": "^0.6.0",
"@solana/kit-plugin-payer": "^0.6.0",
"@solana/kit-plugin-rpc": "^0.6.0",
"@solana/kit": "^6.1.0",
"@solana/prettier-config-solana": "^0.0.6",
"@types/jest": "^29.5.12",
"@types/node": "^20.17.27",
Expand Down
1 change: 1 addition & 0 deletions sdks/ts/src/index.ts
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';
149 changes: 149 additions & 0 deletions sdks/ts/src/kit/executor.ts
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);
},
});
}
113 changes: 113 additions & 0 deletions sdks/ts/src/kit/index.ts
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,
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());
}
Loading
Loading