proof-of-take-sdk 1.0.0

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 (90) hide show
  1. package/FINAL_USAGE.md +342 -0
  2. package/LIBRARY_GUIDE.md +400 -0
  3. package/LICENSE +22 -0
  4. package/README.md +370 -0
  5. package/dist/client.d.ts +32 -0
  6. package/dist/client.js +47 -0
  7. package/dist/constants/season.d.ts +18 -0
  8. package/dist/constants/season.js +22 -0
  9. package/dist/getters/getMiztake.d.ts +11 -0
  10. package/dist/getters/getMiztake.js +34 -0
  11. package/dist/getters/getMiztakeStatistics.d.ts +10 -0
  12. package/dist/getters/getMiztakeStatistics.js +20 -0
  13. package/dist/getters/getTokenVault.d.ts +30 -0
  14. package/dist/getters/getTokenVault.js +56 -0
  15. package/dist/getters/getUserStats.d.ts +21 -0
  16. package/dist/getters/getUserStats.js +43 -0
  17. package/dist/getters/index.d.ts +7 -0
  18. package/dist/getters/index.js +23 -0
  19. package/dist/idl/idl.d.ts +2 -0
  20. package/dist/idl/idl.js +8 -0
  21. package/dist/idl/proof_of_take.json +3803 -0
  22. package/dist/index.d.ts +48 -0
  23. package/dist/index.js +92 -0
  24. package/dist/instructions/claimReferralPenaltyForWindow.d.ts +38 -0
  25. package/dist/instructions/claimReferralPenaltyForWindow.js +72 -0
  26. package/dist/instructions/claimWindowRewards.d.ts +48 -0
  27. package/dist/instructions/claimWindowRewards.js +94 -0
  28. package/dist/instructions/confirmedPostOnX.d.ts +51 -0
  29. package/dist/instructions/confirmedPostOnX.js +78 -0
  30. package/dist/instructions/createMiztake.d.ts +90 -0
  31. package/dist/instructions/createMiztake.js +166 -0
  32. package/dist/instructions/initializeEscrowVault.d.ts +15 -0
  33. package/dist/instructions/initializeEscrowVault.js +36 -0
  34. package/dist/instructions/initializeSeasonSettings.d.ts +20 -0
  35. package/dist/instructions/initializeSeasonSettings.js +39 -0
  36. package/dist/instructions/initializeSeasonVault.d.ts +20 -0
  37. package/dist/instructions/initializeSeasonVault.js +43 -0
  38. package/dist/instructions/initializeStatistics.d.ts +32 -0
  39. package/dist/instructions/initializeStatistics.js +73 -0
  40. package/dist/instructions/joinSeason.d.ts +50 -0
  41. package/dist/instructions/joinSeason.js +120 -0
  42. package/dist/instructions/toggleSeasonPause.d.ts +22 -0
  43. package/dist/instructions/toggleSeasonPause.js +42 -0
  44. package/dist/instructions/updateSeasonAdmin.d.ts +23 -0
  45. package/dist/instructions/updateSeasonAdmin.js +43 -0
  46. package/dist/instructions/viewCurrentSeason.d.ts +12 -0
  47. package/dist/instructions/viewCurrentSeason.js +30 -0
  48. package/dist/instructions/viewSeasonMembershipStatus.d.ts +16 -0
  49. package/dist/instructions/viewSeasonMembershipStatus.js +33 -0
  50. package/dist/instructions/viewWindowStatus.d.ts +15 -0
  51. package/dist/instructions/viewWindowStatus.js +28 -0
  52. package/dist/instructions/withdrawSeasonDeposit.d.ts +38 -0
  53. package/dist/instructions/withdrawSeasonDeposit.js +66 -0
  54. package/dist/optimistic/index.d.ts +7 -0
  55. package/dist/optimistic/index.js +33 -0
  56. package/dist/types/accountTypes.d.ts +121 -0
  57. package/dist/types/accountTypes.js +2 -0
  58. package/dist/types/instructionResults.d.ts +44 -0
  59. package/dist/types/instructionResults.js +2 -0
  60. package/dist/types/proof_of_take.d.ts +3809 -0
  61. package/dist/types/proof_of_take.js +2 -0
  62. package/dist/types.d.ts +232 -0
  63. package/dist/types.js +16 -0
  64. package/dist/utils/accountUpdates.d.ts +245 -0
  65. package/dist/utils/accountUpdates.js +611 -0
  66. package/dist/utils/anchorHelpers.d.ts +7 -0
  67. package/dist/utils/anchorHelpers.js +21 -0
  68. package/dist/utils/constants.d.ts +21 -0
  69. package/dist/utils/constants.js +31 -0
  70. package/dist/utils/conversions.d.ts +25 -0
  71. package/dist/utils/conversions.js +53 -0
  72. package/dist/utils/enumHelpers.d.ts +63 -0
  73. package/dist/utils/enumHelpers.js +110 -0
  74. package/dist/utils/index.d.ts +0 -0
  75. package/dist/utils/index.js +2 -0
  76. package/dist/utils/pdaManager.d.ts +106 -0
  77. package/dist/utils/pdaManager.js +89 -0
  78. package/dist/utils/pdas.d.ts +68 -0
  79. package/dist/utils/pdas.js +128 -0
  80. package/dist/utils/programHelpers.d.ts +9 -0
  81. package/dist/utils/programHelpers.js +18 -0
  82. package/dist/utils/signerHelpers.d.ts +17 -0
  83. package/dist/utils/signerHelpers.js +21 -0
  84. package/dist/utils/simulationHelpers.d.ts +121 -0
  85. package/dist/utils/simulationHelpers.js +183 -0
  86. package/dist/utils/tierPenalty.d.ts +9 -0
  87. package/dist/utils/tierPenalty.js +24 -0
  88. package/dist/utils/transactionBuilder.d.ts +77 -0
  89. package/dist/utils/transactionBuilder.js +147 -0
  90. package/package.json +50 -0
@@ -0,0 +1,17 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ /**
3
+ * Signer information
4
+ */
5
+ export interface SignerInfo {
6
+ publicKey: PublicKey;
7
+ role: string;
8
+ }
9
+ /**
10
+ * Build signers array with optional fee payer
11
+ * Automatically deduplicates if fee payer is already in required signers
12
+ *
13
+ * @param requiredSigners - Required signers for the instruction
14
+ * @param feePayer - Optional separate fee payer
15
+ * @returns Array of signers with deduplicated fee payer
16
+ */
17
+ export declare function buildSigners(requiredSigners: SignerInfo[], feePayer?: PublicKey): SignerInfo[];
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSigners = buildSigners;
4
+ /**
5
+ * Build signers array with optional fee payer
6
+ * Automatically deduplicates if fee payer is already in required signers
7
+ *
8
+ * @param requiredSigners - Required signers for the instruction
9
+ * @param feePayer - Optional separate fee payer
10
+ * @returns Array of signers with deduplicated fee payer
11
+ */
12
+ function buildSigners(requiredSigners, feePayer) {
13
+ const signers = [...requiredSigners];
14
+ if (feePayer) {
15
+ const alreadyIncluded = signers.some((s) => s.publicKey.equals(feePayer));
16
+ if (!alreadyIncluded) {
17
+ signers.push({ publicKey: feePayer, role: "feePayer" });
18
+ }
19
+ }
20
+ return signers;
21
+ }
@@ -0,0 +1,121 @@
1
+ import { Connection, TransactionInstruction, PublicKey, SimulatedTransactionResponse } from "@solana/web3.js";
2
+ import { SignerInfo } from "./signerHelpers";
3
+ /**
4
+ * Simulation result with detailed information
5
+ */
6
+ export interface DetailedSimulationResult {
7
+ success: boolean;
8
+ logs: string[];
9
+ unitsConsumed: number;
10
+ error?: string;
11
+ returnData?: {
12
+ programId: string;
13
+ data: [string, string];
14
+ };
15
+ accounts?: SimulatedTransactionResponse["accounts"];
16
+ }
17
+ /**
18
+ * Fee estimation result
19
+ */
20
+ export interface FeeEstimate {
21
+ baseFee: number;
22
+ estimatedComputeUnits: number;
23
+ recommendedPriorityFee?: number;
24
+ totalEstimatedCost: number;
25
+ }
26
+ /**
27
+ * Simulate an instruction without sending it
28
+ *
29
+ * @param connection - Solana connection
30
+ * @param instructions - Instructions to simulate
31
+ * @param signers - Required signers (only public keys used for simulation)
32
+ * @param feePayer - Optional fee payer (defaults to first signer)
33
+ * @returns Detailed simulation result
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * const result = await simulateInstruction(
38
+ * connection,
39
+ * [createMiztakeIx],
40
+ * signers
41
+ * );
42
+ *
43
+ * if (!result.success) {
44
+ * console.error("Simulation failed:", result.error);
45
+ * console.log("Logs:", result.logs);
46
+ * }
47
+ * ```
48
+ */
49
+ export declare function simulateInstruction(connection: Connection, instructions: TransactionInstruction[], signers: SignerInfo[], feePayer?: PublicKey): Promise<DetailedSimulationResult>;
50
+ /**
51
+ * Estimate fees for instructions
52
+ *
53
+ * @param connection - Solana connection
54
+ * @param instructions - Instructions to estimate fees for
55
+ * @param feePayer - Fee payer public key
56
+ * @returns Fee estimation with base fee and compute units
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * const estimate = await estimateFees(
61
+ * connection,
62
+ * instructions,
63
+ * wallet.publicKey
64
+ * );
65
+ *
66
+ * console.log(`Estimated cost: ${estimate.totalEstimatedCost} lamports`);
67
+ * console.log(`Compute units: ${estimate.estimatedComputeUnits}`);
68
+ * ```
69
+ */
70
+ export declare function estimateFees(connection: Connection, instructions: TransactionInstruction[], feePayer: PublicKey): Promise<FeeEstimate>;
71
+ /**
72
+ * Dry run an instruction and check if it will succeed
73
+ *
74
+ * @param connection - Solana connection
75
+ * @param instructions - Instructions to check
76
+ * @param signers - Required signers
77
+ * @returns Whether the instruction will succeed and any error message
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * const { willSucceed, error, logs } = await dryRun(
82
+ * connection,
83
+ * instructions,
84
+ * signers
85
+ * );
86
+ *
87
+ * if (!willSucceed) {
88
+ * console.error("Transaction will fail:", error);
89
+ * return;
90
+ * }
91
+ *
92
+ * // Proceed with actual transaction
93
+ * ```
94
+ */
95
+ export declare function dryRun(connection: Connection, instructions: TransactionInstruction[], signers: SignerInfo[]): Promise<{
96
+ willSucceed: boolean;
97
+ error?: string;
98
+ logs: string[];
99
+ unitsConsumed: number;
100
+ }>;
101
+ /**
102
+ * Get compute unit usage for instructions
103
+ * Useful for optimizing compute budget
104
+ *
105
+ * @param connection - Solana connection
106
+ * @param instructions - Instructions to measure
107
+ * @param signers - Required signers
108
+ * @returns Compute units consumed
109
+ */
110
+ export declare function getComputeUnits(connection: Connection, instructions: TransactionInstruction[], signers: SignerInfo[]): Promise<number>;
111
+ /**
112
+ * Add optimal compute budget to instructions
113
+ * Simulates first to determine actual usage, then adds buffer
114
+ *
115
+ * @param connection - Solana connection
116
+ * @param instructions - Base instructions
117
+ * @param signers - Required signers
118
+ * @param buffer - Buffer multiplier (default 1.2 = 20% buffer)
119
+ * @returns Instructions with compute budget prepended
120
+ */
121
+ export declare function addOptimalComputeBudget(connection: Connection, instructions: TransactionInstruction[], signers: SignerInfo[], buffer?: number): Promise<TransactionInstruction[]>;
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.simulateInstruction = simulateInstruction;
4
+ exports.estimateFees = estimateFees;
5
+ exports.dryRun = dryRun;
6
+ exports.getComputeUnits = getComputeUnits;
7
+ exports.addOptimalComputeBudget = addOptimalComputeBudget;
8
+ const web3_js_1 = require("@solana/web3.js");
9
+ /**
10
+ * Simulate an instruction without sending it
11
+ *
12
+ * @param connection - Solana connection
13
+ * @param instructions - Instructions to simulate
14
+ * @param signers - Required signers (only public keys used for simulation)
15
+ * @param feePayer - Optional fee payer (defaults to first signer)
16
+ * @returns Detailed simulation result
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * const result = await simulateInstruction(
21
+ * connection,
22
+ * [createMiztakeIx],
23
+ * signers
24
+ * );
25
+ *
26
+ * if (!result.success) {
27
+ * console.error("Simulation failed:", result.error);
28
+ * console.log("Logs:", result.logs);
29
+ * }
30
+ * ```
31
+ */
32
+ async function simulateInstruction(connection, instructions, signers, feePayer) {
33
+ const payer = feePayer || signers[0]?.publicKey;
34
+ if (!payer) {
35
+ throw new Error("At least one signer required for simulation");
36
+ }
37
+ const transaction = new web3_js_1.Transaction();
38
+ for (const ix of instructions) {
39
+ transaction.add(ix);
40
+ }
41
+ transaction.feePayer = payer;
42
+ const { blockhash } = await connection.getLatestBlockhash();
43
+ transaction.recentBlockhash = blockhash;
44
+ try {
45
+ const simulation = await connection.simulateTransaction(transaction, undefined, [...signers.map((s) => s.publicKey)]);
46
+ return {
47
+ success: simulation.value.err === null,
48
+ logs: simulation.value.logs || [],
49
+ unitsConsumed: simulation.value.unitsConsumed || 0,
50
+ error: simulation.value.err
51
+ ? JSON.stringify(simulation.value.err)
52
+ : undefined,
53
+ returnData: simulation.value.returnData || undefined,
54
+ accounts: simulation.value.accounts || undefined,
55
+ };
56
+ }
57
+ catch (error) {
58
+ return {
59
+ success: false,
60
+ logs: [],
61
+ unitsConsumed: 0,
62
+ error: error instanceof Error ? error.message : String(error),
63
+ };
64
+ }
65
+ }
66
+ /**
67
+ * Estimate fees for instructions
68
+ *
69
+ * @param connection - Solana connection
70
+ * @param instructions - Instructions to estimate fees for
71
+ * @param feePayer - Fee payer public key
72
+ * @returns Fee estimation with base fee and compute units
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * const estimate = await estimateFees(
77
+ * connection,
78
+ * instructions,
79
+ * wallet.publicKey
80
+ * );
81
+ *
82
+ * console.log(`Estimated cost: ${estimate.totalEstimatedCost} lamports`);
83
+ * console.log(`Compute units: ${estimate.estimatedComputeUnits}`);
84
+ * ```
85
+ */
86
+ async function estimateFees(connection, instructions, feePayer) {
87
+ const transaction = new web3_js_1.Transaction();
88
+ for (const ix of instructions) {
89
+ transaction.add(ix);
90
+ }
91
+ transaction.feePayer = feePayer;
92
+ const { blockhash } = await connection.getLatestBlockhash();
93
+ transaction.recentBlockhash = blockhash;
94
+ // Get base fee
95
+ const message = transaction.compileMessage();
96
+ const feeResponse = await connection.getFeeForMessage(message);
97
+ const baseFee = feeResponse.value || 5000;
98
+ // Simulate to get compute units
99
+ let estimatedComputeUnits = 200000; // Default estimate
100
+ try {
101
+ const simulation = await connection.simulateTransaction(transaction);
102
+ if (simulation.value.unitsConsumed) {
103
+ estimatedComputeUnits = simulation.value.unitsConsumed;
104
+ }
105
+ }
106
+ catch (error) {
107
+ // Use default if simulation fails
108
+ }
109
+ // Calculate recommended priority fee (optional)
110
+ const recommendedPriorityFee = Math.ceil(estimatedComputeUnits * 0.000001); // 1 micro-lamport per CU
111
+ return {
112
+ baseFee,
113
+ estimatedComputeUnits,
114
+ recommendedPriorityFee,
115
+ totalEstimatedCost: baseFee + recommendedPriorityFee,
116
+ };
117
+ }
118
+ /**
119
+ * Dry run an instruction and check if it will succeed
120
+ *
121
+ * @param connection - Solana connection
122
+ * @param instructions - Instructions to check
123
+ * @param signers - Required signers
124
+ * @returns Whether the instruction will succeed and any error message
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * const { willSucceed, error, logs } = await dryRun(
129
+ * connection,
130
+ * instructions,
131
+ * signers
132
+ * );
133
+ *
134
+ * if (!willSucceed) {
135
+ * console.error("Transaction will fail:", error);
136
+ * return;
137
+ * }
138
+ *
139
+ * // Proceed with actual transaction
140
+ * ```
141
+ */
142
+ async function dryRun(connection, instructions, signers) {
143
+ const result = await simulateInstruction(connection, instructions, signers);
144
+ return {
145
+ willSucceed: result.success,
146
+ error: result.error,
147
+ logs: result.logs,
148
+ unitsConsumed: result.unitsConsumed,
149
+ };
150
+ }
151
+ /**
152
+ * Get compute unit usage for instructions
153
+ * Useful for optimizing compute budget
154
+ *
155
+ * @param connection - Solana connection
156
+ * @param instructions - Instructions to measure
157
+ * @param signers - Required signers
158
+ * @returns Compute units consumed
159
+ */
160
+ async function getComputeUnits(connection, instructions, signers) {
161
+ const result = await simulateInstruction(connection, instructions, signers);
162
+ return result.unitsConsumed;
163
+ }
164
+ /**
165
+ * Add optimal compute budget to instructions
166
+ * Simulates first to determine actual usage, then adds buffer
167
+ *
168
+ * @param connection - Solana connection
169
+ * @param instructions - Base instructions
170
+ * @param signers - Required signers
171
+ * @param buffer - Buffer multiplier (default 1.2 = 20% buffer)
172
+ * @returns Instructions with compute budget prepended
173
+ */
174
+ async function addOptimalComputeBudget(connection, instructions, signers, buffer = 1.2) {
175
+ const computeUnits = await getComputeUnits(connection, instructions, signers);
176
+ const optimalUnits = Math.ceil(computeUnits * buffer);
177
+ return [
178
+ web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({
179
+ units: optimalUnits,
180
+ }),
181
+ ...instructions,
182
+ ];
183
+ }
@@ -0,0 +1,9 @@
1
+ import { BN } from "@coral-xyz/anchor";
2
+ import { SeasonDepositTier } from "../types";
3
+ /**
4
+ * Tier-based per-window penalty amount (base units, 7 decimals).
5
+ *
6
+ * This is used both by optimistic updates and by instruction builders that need
7
+ * to mirror on-chain accounting (refund vs bonus portions).
8
+ */
9
+ export declare function getTierPenaltyPerWindow(tier: SeasonDepositTier): BN;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTierPenaltyPerWindow = getTierPenaltyPerWindow;
4
+ const anchor_1 = require("@coral-xyz/anchor");
5
+ /**
6
+ * Tier-based per-window penalty amount (base units, 7 decimals).
7
+ *
8
+ * This is used both by optimistic updates and by instruction builders that need
9
+ * to mirror on-chain accounting (refund vs bonus portions).
10
+ */
11
+ function getTierPenaltyPerWindow(tier) {
12
+ // Base units (7 decimals): 1 MIZD = 10_000_000
13
+ if ("copper" in tier)
14
+ return new anchor_1.BN(1000000); // 0.1 MIZD
15
+ if ("silver" in tier)
16
+ return new anchor_1.BN(10000000); // 1 MIZD
17
+ if ("gold" in tier)
18
+ return new anchor_1.BN(100000000); // 10 MIZD
19
+ if ("platinum" in tier)
20
+ return new anchor_1.BN(1000000000); // 100 MIZD
21
+ if ("mithril" in tier)
22
+ return new anchor_1.BN(10000000000); // 1,000 MIZD
23
+ throw new Error("Unknown depositTier");
24
+ }
@@ -0,0 +1,77 @@
1
+ import { Connection, Transaction, TransactionInstruction, PublicKey, VersionedTransaction, SimulatedTransactionResponse, Commitment } from "@solana/web3.js";
2
+ import { SignerInfo } from "./signerHelpers";
3
+ /**
4
+ * Wallet interface for signing
5
+ */
6
+ export interface WalletAdapter {
7
+ publicKey: PublicKey;
8
+ signTransaction<T extends Transaction | VersionedTransaction>(tx: T): Promise<T>;
9
+ signAllTransactions<T extends Transaction | VersionedTransaction>(txs: T[]): Promise<T[]>;
10
+ }
11
+ /**
12
+ * Transaction send options
13
+ */
14
+ export interface SendOptions {
15
+ commitment?: Commitment;
16
+ skipPreflight?: boolean;
17
+ maxRetries?: number;
18
+ preflightCommitment?: Commitment;
19
+ }
20
+ /**
21
+ * Simulation result
22
+ */
23
+ export interface SimulationResult {
24
+ success: boolean;
25
+ logs: string[];
26
+ unitsConsumed: number;
27
+ error?: string;
28
+ returnData?: SimulatedTransactionResponse["returnData"];
29
+ }
30
+ /**
31
+ * Transaction Builder for Proof of Miztake instructions
32
+ * Handles transaction construction, signing, and sending
33
+ */
34
+ export declare class TransactionBuilder {
35
+ private connection;
36
+ private wallets;
37
+ constructor(connection: Connection, wallets: Map<string, WalletAdapter>);
38
+ /**
39
+ * Build a transaction from instructions
40
+ */
41
+ buildTransaction(instructions: TransactionInstruction[], feePayer: PublicKey, options?: {
42
+ addComputeBudget?: boolean;
43
+ computeUnits?: number;
44
+ priorityFee?: number;
45
+ }): Promise<Transaction>;
46
+ /**
47
+ * Sign a transaction with required signers
48
+ */
49
+ signTransaction(transaction: Transaction, signers: SignerInfo[]): Promise<Transaction>;
50
+ /**
51
+ * Build, sign, and send a transaction
52
+ */
53
+ buildSignAndSend(instructions: TransactionInstruction[], signers: SignerInfo[], options?: SendOptions & {
54
+ addComputeBudget?: boolean;
55
+ computeUnits?: number;
56
+ priorityFee?: number;
57
+ }): Promise<string>;
58
+ /**
59
+ * Simulate a transaction without sending
60
+ */
61
+ simulate(instructions: TransactionInstruction[], signers: SignerInfo[]): Promise<SimulationResult>;
62
+ /**
63
+ * Estimate fees for a transaction
64
+ */
65
+ estimateFees(instructions: TransactionInstruction[], feePayer: PublicKey): Promise<{
66
+ baseFee: number;
67
+ estimatedComputeUnits: number;
68
+ }>;
69
+ /**
70
+ * Build multiple transactions if instructions exceed size limits
71
+ */
72
+ buildBatchTransactions(instructions: TransactionInstruction[], feePayer: PublicKey, maxInstructionsPerTx?: number): Promise<Transaction[]>;
73
+ }
74
+ /**
75
+ * Quick helper to build and send without creating a TransactionBuilder instance
76
+ */
77
+ export declare function quickSend(connection: Connection, instructions: TransactionInstruction[], signers: SignerInfo[], wallets: Map<string, WalletAdapter>, options?: SendOptions): Promise<string>;
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TransactionBuilder = void 0;
4
+ exports.quickSend = quickSend;
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ /**
7
+ * Transaction Builder for Proof of Miztake instructions
8
+ * Handles transaction construction, signing, and sending
9
+ */
10
+ class TransactionBuilder {
11
+ constructor(connection, wallets) {
12
+ this.connection = connection;
13
+ this.wallets = wallets;
14
+ }
15
+ /**
16
+ * Build a transaction from instructions
17
+ */
18
+ async buildTransaction(instructions, feePayer, options) {
19
+ const transaction = new web3_js_1.Transaction();
20
+ // Add compute budget if requested
21
+ if (options?.addComputeBudget) {
22
+ if (options.computeUnits) {
23
+ transaction.add(web3_js_1.ComputeBudgetProgram.setComputeUnitLimit({
24
+ units: options.computeUnits,
25
+ }));
26
+ }
27
+ if (options.priorityFee) {
28
+ transaction.add(web3_js_1.ComputeBudgetProgram.setComputeUnitPrice({
29
+ microLamports: options.priorityFee,
30
+ }));
31
+ }
32
+ }
33
+ // Add instructions
34
+ for (const ix of instructions) {
35
+ transaction.add(ix);
36
+ }
37
+ // Set fee payer and recent blockhash
38
+ transaction.feePayer = feePayer;
39
+ const { blockhash, lastValidBlockHeight } = await this.connection.getLatestBlockhash();
40
+ transaction.recentBlockhash = blockhash;
41
+ return transaction;
42
+ }
43
+ /**
44
+ * Sign a transaction with required signers
45
+ */
46
+ async signTransaction(transaction, signers) {
47
+ for (const signerInfo of signers) {
48
+ const wallet = this.wallets.get(signerInfo.role);
49
+ if (!wallet) {
50
+ throw new Error(`No wallet provided for role: ${signerInfo.role}`);
51
+ }
52
+ if (!wallet.publicKey.equals(signerInfo.publicKey)) {
53
+ throw new Error(`Wallet mismatch for role ${signerInfo.role}: expected ${signerInfo.publicKey.toBase58()}, got ${wallet.publicKey.toBase58()}`);
54
+ }
55
+ transaction = await wallet.signTransaction(transaction);
56
+ }
57
+ return transaction;
58
+ }
59
+ /**
60
+ * Build, sign, and send a transaction
61
+ */
62
+ async buildSignAndSend(instructions, signers, options) {
63
+ // Determine fee payer (first signer by default)
64
+ const feePayer = signers[0]?.publicKey;
65
+ if (!feePayer) {
66
+ throw new Error("At least one signer required");
67
+ }
68
+ // Build transaction
69
+ const transaction = await this.buildTransaction(instructions, feePayer, options);
70
+ // Sign transaction
71
+ const signedTx = await this.signTransaction(transaction, signers);
72
+ // Send transaction
73
+ const signature = await this.connection.sendRawTransaction(signedTx.serialize(), {
74
+ skipPreflight: options?.skipPreflight ?? false,
75
+ preflightCommitment: options?.preflightCommitment ?? "confirmed",
76
+ maxRetries: options?.maxRetries,
77
+ });
78
+ // Confirm transaction
79
+ await this.connection.confirmTransaction(signature, options?.commitment ?? "confirmed");
80
+ return signature;
81
+ }
82
+ /**
83
+ * Simulate a transaction without sending
84
+ */
85
+ async simulate(instructions, signers) {
86
+ const feePayer = signers[0]?.publicKey;
87
+ if (!feePayer) {
88
+ throw new Error("At least one signer required for simulation");
89
+ }
90
+ const transaction = await this.buildTransaction(instructions, feePayer);
91
+ try {
92
+ const simulation = await this.connection.simulateTransaction(transaction);
93
+ return {
94
+ success: simulation.value.err === null,
95
+ logs: simulation.value.logs || [],
96
+ unitsConsumed: simulation.value.unitsConsumed || 0,
97
+ error: simulation.value.err
98
+ ? JSON.stringify(simulation.value.err)
99
+ : undefined,
100
+ returnData: simulation.value.returnData,
101
+ };
102
+ }
103
+ catch (error) {
104
+ return {
105
+ success: false,
106
+ logs: [],
107
+ unitsConsumed: 0,
108
+ error: error instanceof Error ? error.message : String(error),
109
+ };
110
+ }
111
+ }
112
+ /**
113
+ * Estimate fees for a transaction
114
+ */
115
+ async estimateFees(instructions, feePayer) {
116
+ const transaction = await this.buildTransaction(instructions, feePayer);
117
+ // Get fee for transaction
118
+ const message = transaction.compileMessage();
119
+ const baseFee = await this.connection.getFeeForMessage(message);
120
+ // Simulate to get compute units
121
+ const simulation = await this.connection.simulateTransaction(transaction);
122
+ return {
123
+ baseFee: baseFee.value || 5000,
124
+ estimatedComputeUnits: simulation.value.unitsConsumed || 200000,
125
+ };
126
+ }
127
+ /**
128
+ * Build multiple transactions if instructions exceed size limits
129
+ */
130
+ async buildBatchTransactions(instructions, feePayer, maxInstructionsPerTx = 10) {
131
+ const transactions = [];
132
+ for (let i = 0; i < instructions.length; i += maxInstructionsPerTx) {
133
+ const batch = instructions.slice(i, i + maxInstructionsPerTx);
134
+ const tx = await this.buildTransaction(batch, feePayer);
135
+ transactions.push(tx);
136
+ }
137
+ return transactions;
138
+ }
139
+ }
140
+ exports.TransactionBuilder = TransactionBuilder;
141
+ /**
142
+ * Quick helper to build and send without creating a TransactionBuilder instance
143
+ */
144
+ async function quickSend(connection, instructions, signers, wallets, options) {
145
+ const builder = new TransactionBuilder(connection, wallets);
146
+ return builder.buildSignAndSend(instructions, signers, options);
147
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "proof-of-take-sdk",
3
+ "version": "1.0.0",
4
+ "description": "TypeScript SDK for Proof of Take Solana program",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "check:idl": "node scripts/check-idl-drift.js",
9
+ "build": "tsc && cp -r src/idl/*.json dist/idl/",
10
+ "watch": "tsc --watch",
11
+ "clean": "rm -rf dist",
12
+ "prepublishOnly": "npm run check:idl && npm run clean && npm run build"
13
+ },
14
+ "keywords": [
15
+ "solana",
16
+ "anchor",
17
+ "proof-of-take",
18
+ "blockchain",
19
+ "web3",
20
+ "take",
21
+ "token"
22
+ ],
23
+ "author": "Proof of Take Team",
24
+ "license": "MIT",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/proof-of-take/proof-of-take.git"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "peerDependencies": {
33
+ "@coral-xyz/anchor": "^0.32.1",
34
+ "@solana/web3.js": "^1.95.0",
35
+ "@solana/spl-token": "^0.4.0"
36
+ },
37
+ "devDependencies": {
38
+ "@coral-xyz/anchor": "^0.32.1",
39
+ "@solana/web3.js": "^1.95.8",
40
+ "@solana/spl-token": "^0.4.8",
41
+ "@types/node": "^20.0.0",
42
+ "typescript": "^5.0.0"
43
+ },
44
+ "files": [
45
+ "dist",
46
+ "README.md",
47
+ "LIBRARY_GUIDE.md",
48
+ "FINAL_USAGE.md"
49
+ ]
50
+ }