kit-squared 0.0.1

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.
@@ -0,0 +1,431 @@
1
+ import { writable } from "svelte/store";
2
+ import { camelToSnake, snakeToCamel, camelToPascal, snakeToPascal, getPDA, pascalToCamel, sleep } from "./utils.js";
3
+ import { Event } from "./utils.js";
4
+ import { signer } from "./wallet.js";
5
+ import { getConnection } from "./connection.js";
6
+ import { typeEncoder } from "./utils.js";
7
+ import { fetchEncodedAccount, getBase64Codec } from "@solana/kit";
8
+ import {} from "@solana/kit";
9
+ export let _transacting = false;
10
+ export let transacting = writable(_transacting);
11
+ function _setTransacting(state) {
12
+ _transacting = state !== TRANSACTION_STATE.INITIAL;
13
+ transacting.set(_transacting);
14
+ }
15
+ export const TRANSACTION_STATE = {
16
+ INITIAL: "INITIAL",
17
+ REQUESTED: "REQUESTED",
18
+ PENDING: "PENDING",
19
+ };
20
+ const INITIAL = TRANSACTION_STATE.INITIAL;
21
+ const REQUESTED = TRANSACTION_STATE.REQUESTED;
22
+ const PENDING = TRANSACTION_STATE.PENDING;
23
+ export const transactionState = writable(TRANSACTION_STATE.INITIAL);
24
+ const onRequest = Event();
25
+ const onSubmit = Event();
26
+ const onConfirm = Event();
27
+ const onCancel = Event();
28
+ const onFail = Event();
29
+ export const onTransaction = {
30
+ request: onRequest,
31
+ submit: onSubmit,
32
+ confirm: onConfirm,
33
+ cancel: onCancel,
34
+ fail: onFail,
35
+ };
36
+ let addedAccounts = {};
37
+ export function clearAddedAccounts() {
38
+ addedAccounts = {};
39
+ }
40
+ export function addAccounts(accounts) {
41
+ for (let a in accounts) {
42
+ addedAccounts[a] = accounts[a];
43
+ }
44
+ }
45
+ export function getAddedAccounts() {
46
+ return addedAccounts;
47
+ }
48
+ function _txWasCancelled(e) {
49
+ let msg;
50
+ if (e.message) {
51
+ msg = e.message.toLowerCase();
52
+ }
53
+ else {
54
+ msg = e.toString().toLowerCase();
55
+ }
56
+ return msg.includes('denied') || msg.includes('rejected') || msg.includes('cancelled');
57
+ }
58
+ export async function transact(ixs = [], names = []) {
59
+ _setTransacting(REQUESTED);
60
+ onRequest.trigger(names);
61
+ const connection = getConnection();
62
+ try {
63
+ const signature = await connection.sendTransactionFromInstructionsWithWalletApp({
64
+ feePayer: signer,
65
+ instructions: ixs
66
+ });
67
+ _setTransacting(PENDING);
68
+ onSubmit.trigger(names);
69
+ // Set up an abort controller.
70
+ const abortController = new AbortController();
71
+ const confirmed = await connection.getRecentSignatureConfirmation({
72
+ abortSignal: abortController.signal,
73
+ commitment: 'confirmed',
74
+ signature: signature
75
+ });
76
+ _setTransacting(INITIAL);
77
+ onConfirm.trigger(names);
78
+ }
79
+ catch (e) {
80
+ if (_txWasCancelled(e)) {
81
+ // TODO: properly catch this and other errors
82
+ onCancel.trigger(names);
83
+ }
84
+ else {
85
+ onFail.trigger(names);
86
+ }
87
+ _setTransacting(INITIAL);
88
+ }
89
+ }
90
+ export async function transactSingle(ix, name = null) {
91
+ let names = name ? [name] : [];
92
+ return await transact([ix], names);
93
+ }
94
+ export async function createProgram(programClient, idl, signer = null, noEvents = false) {
95
+ if (!programClient) {
96
+ throw new Error("Missing program client.");
97
+ }
98
+ if (!idl) {
99
+ throw new Error("Missing program IDL.");
100
+ }
101
+ const program_name = idl.metadata.name;
102
+ const PROGRAM_NAME = program_name.toUpperCase();
103
+ const programName = snakeToCamel(program_name);
104
+ const programId = programClient[PROGRAM_NAME + "_PROGRAM_ADDRESS"];
105
+ const programId_fromIDL = idl.address;
106
+ if (programId !== programId_fromIDL) {
107
+ throw new Error("IDL and program client do not have matching address.");
108
+ }
109
+ async function pda(seeds) {
110
+ return getPDA(seeds, programId);
111
+ }
112
+ const onEventDropout = Event();
113
+ const on = function (eventName, callback) {
114
+ _eventTranslation[eventName](callback);
115
+ };
116
+ const _eventTranslation = {};
117
+ // Events
118
+ const _events = {};
119
+ for (let event of idl.events) {
120
+ const nameCamel = pascalToCamel(event.name);
121
+ _events[event.name] = {
122
+ name: nameCamel,
123
+ discriminator: event.discriminator,
124
+ codec: programClient[`get${event.name}Codec`](),
125
+ };
126
+ _eventTranslation[nameCamel] = Event();
127
+ }
128
+ // Set up an abort controller.
129
+ const abortController = new AbortController();
130
+ async function _beginConsumingMessage(programNotifications) {
131
+ // Keep this part separate so that it can be done separately and doesn't lock up the rest of the init
132
+ try {
133
+ // Consume messages.
134
+ for await (const notification of programNotifications) {
135
+ // slot: notification.context.slot : bigInt
136
+ // signature: notification.value.signature : string (big sig)
137
+ _parseNotification(notification);
138
+ }
139
+ }
140
+ catch (e) {
141
+ //todo e catch
142
+ // The subscription went down.
143
+ // Retry it and also trigger event informing connection died
144
+ onEventDropout.trigger(programName);
145
+ setTimeout(_subscribeToProgram, 1000);
146
+ }
147
+ }
148
+ async function _subscribeToProgram() {
149
+ const connection = getConnection();
150
+ const rpcSubscriptions = connection.rpcSubscriptions;
151
+ const logsNotifications = rpcSubscriptions.logsNotifications({
152
+ mentions: [programId]
153
+ });
154
+ let programNotifications;
155
+ try {
156
+ programNotifications = await logsNotifications.subscribe({ abortSignal: abortController.signal });
157
+ }
158
+ catch (e) {
159
+ console.error(e);
160
+ throw new Error("failed to subscribe to program");
161
+ return;
162
+ }
163
+ _beginConsumingMessage(programNotifications);
164
+ }
165
+ const DISCRIMINATOR_LENGTH = 8;
166
+ function _findMatchingEvent(data) {
167
+ for (let e in _events) {
168
+ const event = _events[e];
169
+ if (data.subarray(0, DISCRIMINATOR_LENGTH).join(",") === event.discriminator.join(",")) {
170
+ return event;
171
+ }
172
+ }
173
+ return null;
174
+ }
175
+ function _parseNotification(notification) {
176
+ // slot: notification.context.slot : bigInt
177
+ // signature: notification.value.signature : string (big sig)
178
+ const slot = notification.context.slot;
179
+ const signature = notification.value.signature;
180
+ const UNCONFIRMED = "1111111111111111111111111111111111111111111111111111111111111111";
181
+ if (signature === UNCONFIRMED)
182
+ return; //Don't parse those weird pre-transactions
183
+ const STEM = "Program data: ";
184
+ const logs = notification.value.logs;
185
+ const datas = logs.filter((a) => a.includes(STEM));
186
+ const rawEvents = datas.map((a) => a.substring(STEM.length));
187
+ for (let d of rawEvents) {
188
+ const data = getBase64Codec().encode(d);
189
+ const matchingEvent = _findMatchingEvent(data);
190
+ if (matchingEvent) {
191
+ const { codec, name } = matchingEvent;
192
+ const usable_data = data.subarray(DISCRIMINATOR_LENGTH);
193
+ const decoded = codec.decode(usable_data);
194
+ // TODO: better integer parsing than just assuming numbers should be integers
195
+ for (let v in decoded) {
196
+ if (typeof decoded[v] === "number") {
197
+ decoded[v] = BigInt(decoded[v]);
198
+ }
199
+ }
200
+ _eventTranslation[name].trigger(decoded, slot, signature);
201
+ }
202
+ else {
203
+ //todo catch event name not found
204
+ }
205
+ }
206
+ }
207
+ function _killProgramSubscription() {
208
+ abortController.abort();
209
+ }
210
+ if (!noEvents) {
211
+ await _subscribeToProgram();
212
+ }
213
+ function killProgram() {
214
+ _killProgramSubscription();
215
+ killEvents();
216
+ }
217
+ function killEvents() {
218
+ //@ts-ignore
219
+ for (let e in _eventTranslation) {
220
+ _eventTranslation[e].killAll();
221
+ }
222
+ }
223
+ const ixs = {};
224
+ const tx = {};
225
+ async function readAccount(accountName, address) {
226
+ const account = await fetchEncodedAccount(getConnection().rpc, address);
227
+ if (account.exists) {
228
+ const AccountName = camelToPascal(accountName);
229
+ const codec = programClient[`get${AccountName}Codec`]();
230
+ const values = codec.decode(account.data);
231
+ for (let v in values) {
232
+ if (typeof values[v] === "number") {
233
+ values[v] = BigInt(values[v]);
234
+ }
235
+ }
236
+ return values;
237
+ }
238
+ else {
239
+ return null;
240
+ }
241
+ }
242
+ function getAccountPropertyType(accountName, propertyName) {
243
+ const AccountName = camelToPascal(accountName);
244
+ const property_name = camelToSnake(propertyName);
245
+ for (let t of idl.types) {
246
+ if (t.name === AccountName) {
247
+ for (let f of t.type.fields) {
248
+ if (f.name === property_name) {
249
+ return f.type;
250
+ }
251
+ }
252
+ }
253
+ }
254
+ return null;
255
+ }
256
+ async function addIxAccounts(instruction, ixProps) {
257
+ function getArgType(name_snake) {
258
+ for (let arg of instruction.args) {
259
+ if (arg.name === name_snake) {
260
+ return arg.type;
261
+ }
262
+ }
263
+ }
264
+ //instruction is the property from the IDL
265
+ // Adds accounts to ixProps
266
+ // PDAs are listed and calculated last
267
+ let PDAs = [];
268
+ // Iterate through accounts and add them as possible. Save PDAs for last in case they are derived from other
269
+ // accounts.
270
+ const accounts = instruction.accounts;
271
+ for (let account of accounts) {
272
+ const name = account.name;
273
+ const nameCamel = snakeToCamel(name);
274
+ if (ixProps[nameCamel])
275
+ continue; // skip if it's already been added
276
+ if (account.signer) {
277
+ if (!signer)
278
+ throw new Error("Signer not found");
279
+ ixProps[nameCamel] = signer.address;
280
+ }
281
+ else if (account.address) {
282
+ ixProps[nameCamel] = account.address;
283
+ }
284
+ else if (account.pda) {
285
+ // Do all the PDAs at the end when all the other accounts are done, in case they are derived from other
286
+ // accounts or variables.
287
+ PDAs.push(account);
288
+ }
289
+ else {
290
+ }
291
+ }
292
+ // Now do the PDAs
293
+ while (PDAs.length > 0) {
294
+ const unadded = [];
295
+ for (let account of PDAs) {
296
+ const seeds = [];
297
+ let failed = false;
298
+ for (let seed of account.pda.seeds) {
299
+ switch (seed.kind) {
300
+ case "const":
301
+ seeds.push(Uint8Array.from(seed.value));
302
+ break;
303
+ case "arg":
304
+ let argType = getArgType(seed.path);
305
+ const argValue = ixProps[snakeToCamel(seed.path)]; // assume this has already been encoded
306
+ if (argType === "string") {
307
+ seeds.push(argValue);
308
+ break;
309
+ }
310
+ if (argType === "pubkey") {
311
+ argType = "address";
312
+ }
313
+ if (!typeEncoder[argType]) {
314
+ throw new Error(`no encoder for arg type:` + argType);
315
+ }
316
+ seeds.push(typeEncoder[argType].encode(argValue));
317
+ break;
318
+ case "account":
319
+ if (seed.account) {
320
+ // It is the value of property of another account that must be read
321
+ //path: accountName.variableName
322
+ const [parentName, property] = seed.path.split(".");
323
+ //account: AccountType
324
+ if (ixProps[parentName]) {
325
+ //TODO: read account of type seed.account, with address ixProps[parentName] and
326
+ // use [property] of that.
327
+ // Will need to infer type from the account
328
+ const accountData = await readAccount(seed.account, ixProps[parentName]);
329
+ if (!accountData)
330
+ throw new Error(`Unable to read account relating to ${seed.account}: ${ixProps[parentName]}`);
331
+ const value = accountData[property];
332
+ const propertyType = getAccountPropertyType(seed.account, property);
333
+ if (!propertyType)
334
+ throw new Error(`Unable to read property type relating to ${seed.account}: ${property}`);
335
+ seeds.push(typeEncoder[propertyType].encode(value));
336
+ }
337
+ else {
338
+ // its not ready yet
339
+ failed = true;
340
+ break;
341
+ }
342
+ }
343
+ else {
344
+ // It is just the address of the account
345
+ const value = ixProps[seed.path];
346
+ if (!value) {
347
+ // Hasn't been added yet, so can't do this PDA yet
348
+ failed = true;
349
+ break;
350
+ }
351
+ else {
352
+ seeds.push(typeEncoder.address.encode(value));
353
+ }
354
+ }
355
+ break;
356
+ }
357
+ if (failed) {
358
+ unadded.push(account);
359
+ break;
360
+ }
361
+ }
362
+ ixProps[snakeToCamel(account.name)] = await pda(seeds);
363
+ }
364
+ if (unadded.length === PDAs.length) {
365
+ // None added this iteration. This is a failing state.
366
+ if (unadded.length === 1) {
367
+ throw new Error("Unable to calculate PDA: " + unadded[0].name);
368
+ }
369
+ else {
370
+ throw new Error(`Unable to calculate ${unadded.length} PDAs.`);
371
+ }
372
+ }
373
+ else {
374
+ PDAs = unadded;
375
+ }
376
+ }
377
+ }
378
+ for (let instruction of idl.instructions) {
379
+ const name = instruction.name;
380
+ const nameCamel = snakeToCamel(name);
381
+ const NamePascal = snakeToPascal(name);
382
+ const argTypes = instruction.args;
383
+ ixs[nameCamel] = async function () {
384
+ if (arguments.length !== argTypes.length) {
385
+ throw new Error(`Incorrect arguments provided for ${name}. Received ${arguments.length}, expected ${argTypes.length}.`);
386
+ }
387
+ let ixProps = {};
388
+ for (let account in addedAccounts) {
389
+ ixProps[account] = addedAccounts[account];
390
+ }
391
+ for (let i = 0; i < arguments.length; i++) {
392
+ ixProps[snakeToCamel(argTypes[i].name)] = arguments[i];
393
+ }
394
+ await addIxAccounts(instruction, ixProps);
395
+ return programClient[`get${NamePascal}Instruction`](ixProps);
396
+ };
397
+ tx[nameCamel] = async function () {
398
+ let ix = await ixs[nameCamel](...arguments);
399
+ await transactSingle(ix, nameCamel);
400
+ };
401
+ }
402
+ let account = {};
403
+ for (let a of idl.accounts) {
404
+ const nameCamel = pascalToCamel(a.name);
405
+ account[nameCamel] = async function (addressOrSeeds) {
406
+ if (Array.isArray(addressOrSeeds)) {
407
+ // it's array, assume it's seeds
408
+ const address = await pda(addressOrSeeds);
409
+ return await readAccount(nameCamel, address);
410
+ }
411
+ else {
412
+ // assume address
413
+ return await readAccount(nameCamel, addressOrSeeds);
414
+ }
415
+ };
416
+ }
417
+ const returns = {
418
+ on,
419
+ killEvents,
420
+ killProgram,
421
+ startSubscription: _subscribeToProgram,
422
+ account,
423
+ pda,
424
+ programId,
425
+ };
426
+ if (signer) {
427
+ returns.tx = tx;
428
+ returns.ix = ixs;
429
+ }
430
+ return returns;
431
+ }
@@ -0,0 +1,50 @@
1
+ import { type Address } from "@solana/kit";
2
+ export declare const ZERO_ADDRESS = "11111111111111111111111111111111";
3
+ export declare function integerTypeToSize(type: string): string;
4
+ export declare function isIntergerType(type: string): boolean;
5
+ export declare const typeEncoder: {
6
+ [key: string]: any;
7
+ };
8
+ export declare function address(str: string): any;
9
+ export declare function camelToSnake(name: string): string;
10
+ export declare function snakeToCamel(name: string): string;
11
+ export declare function pascalToCamel(name: string): string;
12
+ export declare function camelToPascal(name: string): string;
13
+ export declare function snakeToPascal(name: string): string;
14
+ export declare function pascalToSnake(name: string): string;
15
+ export interface Callback {
16
+ (...args: any[]): void;
17
+ }
18
+ export interface EventSingleType {
19
+ (callback: Callback): void;
20
+ trigger: Function;
21
+ }
22
+ export declare function EventSingle(): EventSingleType;
23
+ export interface OnEvent {
24
+ (...args: any[]): void;
25
+ }
26
+ export interface EventType {
27
+ (callback: Callback): void;
28
+ killAll: Function;
29
+ trigger: Function;
30
+ }
31
+ export declare function Event(): {
32
+ (callback: Callback): () => void;
33
+ trigger: (...args: any[]) => Promise<void>;
34
+ killAll: () => void;
35
+ };
36
+ export declare function getPDA(seeds: any[], programId: Address): Promise<Address<string>>;
37
+ export declare function lamportsToSol(lamports: bigint): string;
38
+ export declare function roundSol(sol: number): number;
39
+ export declare function zeroes(length: number): string;
40
+ export declare function solToLamports(sol: any): bigint;
41
+ export declare function safeMultiply(num0: number, num1: number): number;
42
+ export declare function sleep(ms: number): Promise<unknown>;
43
+ export declare function fnv32a(): number;
44
+ export declare function now(ms?: boolean): bigint;
45
+ export declare function parseSeconds(time: bigint): string;
46
+ export declare function parseMilliseconds(time: bigint): string;
47
+ export declare function isSameKey(key0: any, key1: any): boolean;
48
+ export declare function readStorage(key: string, defaultVal?: any): any;
49
+ export declare function writeStorage(key: string, value: any): void;
50
+ export declare function clearStorage(key: string): void;