-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
index.ts
367 lines (343 loc) · 9.88 KB
/
index.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import { inflate } from "pako";
import { PublicKey } from "@solana/web3.js";
import Provider, { getProvider } from "../provider.js";
import { Idl, idlAddress, decodeIdlAccount } from "../idl.js";
import { Coder, BorshCoder } from "../coder/index.js";
import NamespaceFactory, {
RpcNamespace,
InstructionNamespace,
TransactionNamespace,
AccountNamespace,
StateClient,
SimulateNamespace,
MethodsNamespace,
} from "./namespace/index.js";
import { utf8 } from "../utils/bytes/index.js";
import { EventManager } from "./event.js";
import { Address, translateAddress } from "./common.js";
export * from "./common.js";
export * from "./context.js";
export * from "./event.js";
export * from "./namespace/index.js";
/**
* ## Program
*
* Program provides the IDL deserialized client representation of an Anchor
* program.
*
* This API is the one stop shop for all things related to communicating with
* on-chain programs. Among other things, one can send transactions, fetch
* deserialized accounts, decode instruction data, subscribe to account
* changes, and listen to events.
*
* In addition to field accessors and methods, the object provides a set of
* dynamically generated properties, also known as namespaces, that
* map one-to-one to program methods and accounts. These namespaces generally
* can be used as follows:
*
* ## Usage
*
* ```javascript
* program.<namespace>.<program-specific-method>
* ```
*
* API specifics are namespace dependent. The examples used in the documentation
* below will refer to the two counter examples found
* [here](https://github.com/project-serum/anchor#examples).
*/
export class Program<IDL extends Idl = Idl> {
/**
* Async methods to send signed transactions to *non*-state methods on the
* program, returning a [[TransactionSignature]].
*
* ## Usage
*
* ```javascript
* rpc.<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 send a transaction invoking the `increment` method above,
*
* ```javascript
* const txSignature = await program.rpc.increment({
* accounts: {
* counter,
* authority,
* },
* });
* ```
*/
readonly rpc: RpcNamespace<IDL>;
/**
* The namespace provides handles to an [[AccountClient]] object for each
* account in the program.
*
* ## Usage
*
* ```javascript
* program.account.<account-client>
* ```
*
* ## Example
*
* To fetch a `Counter` account from the above example,
*
* ```javascript
* const counter = await program.account.counter.fetch(address);
* ```
*
* For the full API, see the [[AccountClient]] reference.
*/
readonly account: AccountNamespace<IDL>;
/**
* The namespace provides functions to build [[TransactionInstruction]]
* objects for each method of a program.
*
* ## Usage
*
* ```javascript
* program.instruction.<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.instruction.increment({
* accounts: {
* counter,
* },
* });
* ```
*/
readonly instruction: InstructionNamespace<IDL>;
/**
* 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,
* },
* });
* ```
*/
readonly transaction: TransactionNamespace<IDL>;
/**
* The namespace provides functions to simulate transactions for each method
* of a program, returning a list of deserialized events *and* raw program
* logs.
*
* One can use this to read data calculated from a program on chain, by
* emitting an event in the program and reading the emitted event client side
* via the `simulate` namespace.
*
* ## simulate
*
* ```javascript
* program.simulate.<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 simulate the `increment` method above,
*
* ```javascript
* const events = await program.simulate.increment({
* accounts: {
* counter,
* },
* });
* ```
*/
readonly simulate: SimulateNamespace<IDL>;
/**
* A client for the program state. Similar to the base [[Program]] client,
* one can use this to send transactions and read accounts for the state
* abstraction.
*/
readonly state?: StateClient<IDL>;
/**
* The namespace provides a builder API for all APIs on the program.
* This is an alternative to using namespace the other namespaces..
*/
readonly methods: MethodsNamespace<IDL>;
/**
* Address of the program.
*/
public get programId(): PublicKey {
return this._programId;
}
private _programId: PublicKey;
/**
* IDL defining the program's interface.
*/
public get idl(): IDL {
return this._idl;
}
private _idl: IDL;
/**
* Coder for serializing requests.
*/
public get coder(): Coder {
return this._coder;
}
private _coder: Coder;
/**
* Wallet and network provider.
*/
public get provider(): Provider {
return this._provider;
}
private _provider: Provider;
/**
* Handles event subscriptions.
*/
private _events: EventManager;
/**
* @param idl The interface definition.
* @param programId The on-chain address of the program.
* @param provider The network and wallet context to use. If not provided
* then uses [[getProvider]].
*/
public constructor(
idl: IDL,
programId: Address,
provider?: Provider,
coder?: Coder
) {
programId = translateAddress(programId);
if (!provider) {
provider = getProvider();
}
// Fields.
this._idl = idl;
this._provider = provider;
this._programId = programId;
this._coder = coder ?? new BorshCoder(idl);
this._events = new EventManager(this._programId, provider, this._coder);
// Dynamic namespaces.
const [
rpc,
instruction,
transaction,
account,
simulate,
methods,
state,
] = NamespaceFactory.build(idl, this._coder, programId, provider);
this.rpc = rpc;
this.instruction = instruction;
this.transaction = transaction;
this.account = account;
this.simulate = simulate;
this.methods = methods;
this.state = state;
}
/**
* Generates a Program client by fetching the IDL from the network.
*
* In order to use this method, an IDL must have been previously initialized
* via the anchor CLI's `anchor idl init` command.
*
* @param programId The on-chain address of the program.
* @param provider The network and wallet context.
*/
public static async at<IDL extends Idl = Idl>(
address: Address,
provider?: Provider
): Promise<Program<IDL>> {
const programId = translateAddress(address);
const idl = await Program.fetchIdl<IDL>(programId, provider);
if (!idl) {
throw new Error(`IDL not found for program: ${address.toString()}`);
}
return new Program(idl, programId, provider);
}
/**
* Fetches an idl from the blockchain.
*
* In order to use this method, an IDL must have been previously initialized
* via the anchor CLI's `anchor idl init` command.
*
* @param programId The on-chain address of the program.
* @param provider The network and wallet context.
*/
public static async fetchIdl<IDL extends Idl = Idl>(
address: Address,
provider?: Provider
): Promise<IDL | null> {
provider = provider ?? getProvider();
const programId = translateAddress(address);
const idlAddr = await idlAddress(programId);
const accountInfo = await provider.connection.getAccountInfo(idlAddr);
if (!accountInfo) {
return null;
}
// Chop off account discriminator.
let idlAccount = decodeIdlAccount(accountInfo.data.slice(8));
const inflatedIdl = inflate(idlAccount.data);
return JSON.parse(utf8.decode(inflatedIdl));
}
/**
* Invokes the given callback every time the given event is emitted.
*
* @param eventName The PascalCase name of the event, provided by the IDL.
* @param callback The function to invoke whenever the event is emitted from
* program logs.
*/
public addEventListener(
eventName: string,
callback: (event: any, slot: number) => void
): number {
return this._events.addEventListener(eventName, callback);
}
/**
* Unsubscribes from the given eventName.
*/
public async removeEventListener(listener: number): Promise<void> {
return await this._events.removeEventListener(listener);
}
}