forked from solana-foundation/anchor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction.ts
73 lines (69 loc) · 2.07 KB
/
transaction.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { Transaction } from "@solana/web3.js";
import { Idl, IdlInstruction } from "../../idl";
import { splitArgsAndCtx } from "../context";
import { InstructionFn } from "./instruction";
import {
AllInstructions,
InstructionContextFn,
MakeInstructionsNamespace,
} from "./types";
export default class TransactionFactory {
public static build<IDL extends Idl, I extends AllInstructions<IDL>>(
idlIx: I,
ixFn: InstructionFn<IDL, I>
): TransactionFn<IDL, I> {
const txFn: TransactionFn<IDL, I> = (...args): Transaction => {
const [, ctx] = splitArgsAndCtx(idlIx, [...args]);
const tx = new Transaction();
if (ctx.preInstructions && ctx.instructions) {
throw new Error("instructions is deprecated, use preInstructions");
}
ctx.preInstructions?.forEach((ix) => tx.add(ix));
ctx.instructions?.forEach((ix) => tx.add(ix));
tx.add(ixFn(...args));
ctx.postInstructions?.forEach((ix) => tx.add(ix));
return tx;
};
return txFn;
}
}
/**
* The namespace provides functions to build [[Transaction]] objects for each
* method of a program.
*
* ## Usage
*
* ```javascript
* program.transaction.<method>(...args, ctx);
* ```
*
* ## Parameters
*
* 1. `args` - The positional arguments for the program. The type and number
* of these arguments depend on the program being used.
* 2. `ctx` - [[Context]] non-argument parameters to pass to the method.
* Always the last parameter in the method call.
*
* ## Example
*
* To create an instruction for the `increment` method above,
*
* ```javascript
* const tx = await program.transaction.increment({
* accounts: {
* counter,
* },
* });
* ```
*/
export type TransactionNamespace<
IDL extends Idl = Idl,
I extends AllInstructions<IDL> = AllInstructions<IDL>
> = MakeInstructionsNamespace<IDL, I, Transaction>;
/**
* Tx is a function to create a `Transaction` for a given program instruction.
*/
export type TransactionFn<
IDL extends Idl = Idl,
I extends AllInstructions<IDL> = AllInstructions<IDL>
> = InstructionContextFn<IDL, I, Transaction>;