kit-squared 0.2.7 → 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.
package/README.md CHANGED
@@ -108,9 +108,9 @@ It also tracks the transaction state, and fires events when the tx state changes
108
108
  ### Sending Transactions
109
109
  Send a transaction with any instructions using
110
110
  ```typescript
111
- transact(ixs, names);
111
+ transact(ixs, names, preSimulate);
112
112
  ```
113
- Where `ixs` is an array of `@solana/kit` `Instruction`s, and `names` is an optional array of ix names that will be fired with each tx lifecycle event.
113
+ Where `ixs` is an array of `@solana/kit` `Instruction`s, and `names` is an optional array of ix names that will be fired with each tx lifecycle event. If `preSimulate` is `true`, the library will simulate the tx before requesting it, and cause this function fail if the tx will fail.
114
114
 
115
115
  ### Transaction Lifecycle
116
116
  Kit² only expects one tx to be in progress at any given time. While it doesn't prevent multiple simultaneous txs, the tx-lifecycle management is simplified for only one.
package/dist/index.d.ts CHANGED
@@ -2,7 +2,8 @@ import { type NetworkType } from "./library/wallet.js";
2
2
  export declare function init(http: string, ws: string, networkType?: NetworkType): void;
3
3
  export { getNetworkType, getNetwork, getConnection, checkAccountExists, getAccountBalance } from "./library/connection.js";
4
4
  export { onConnect, onDisconnect } from "./library/connectSchedule.js";
5
- export { transacting, TRANSACTION_STATE, transactionState, onTransaction, clearAddedAccounts, addAccounts, getAddedAccounts, transact, createProgram, } from "./library/program.js";
5
+ export { clearAddedAccounts, addAccounts, getAddedAccounts, createProgram, } from "./library/program.js";
6
+ export { transacting, TRANSACTION_STATE, transactionState, onTransaction, transact, simulate, type Simulation, type SimulationError, } from "./library/transaction.ts";
6
7
  export * from "./library/utils.js";
7
8
  export { walletState, walletInitial, walletConnecting, walletConnected, walletError, signer, myKey, me, myKeyString, isMe, getStoredWalletSelection, disconnectWallet, unmountWallet } from "./library/wallet.js";
8
9
  export { availableWallets, selection, selectWallet, getWalletInfo, unmountTeardown, recheckWallets, } from "./library/walletSelection.js";
package/dist/index.js CHANGED
@@ -8,7 +8,8 @@ export function init(http, ws, networkType) {
8
8
  }
9
9
  export { getNetworkType, getNetwork, getConnection, checkAccountExists, getAccountBalance } from "./library/connection.js";
10
10
  export { onConnect, onDisconnect } from "./library/connectSchedule.js";
11
- export { transacting, TRANSACTION_STATE, transactionState, onTransaction, clearAddedAccounts, addAccounts, getAddedAccounts, transact, createProgram, } from "./library/program.js";
11
+ export { clearAddedAccounts, addAccounts, getAddedAccounts, createProgram, } from "./library/program.js";
12
+ export { transacting, TRANSACTION_STATE, transactionState, onTransaction, transact, simulate, } from "./library/transaction.js";
12
13
  export * from "./library/utils.js";
13
14
  export { walletState, walletInitial, walletConnecting, walletConnected, walletError, signer, myKey, me, myKeyString, isMe, getStoredWalletSelection, disconnectWallet, unmountWallet } from "./library/wallet.js";
14
15
  export { availableWallets, selection, selectWallet, getWalletInfo, unmountTeardown, recheckWallets, } from "./library/walletSelection.js";
@@ -58,12 +58,10 @@ export function getConnection() {
58
58
  throw new Error("Network not configured (you must call setNetwork before this point).");
59
59
  return _connect();
60
60
  }
61
- // !!! TODO
62
61
  export async function checkAccountExists(address) {
63
- // return true;
64
- //todo: this
65
62
  return await getAccountBalance(address) > 0n;
66
63
  }
67
64
  export async function getAccountBalance(address) {
65
+ //@ts-ignore
68
66
  return await (await getConnection().getLamportBalance(address)).value;
69
67
  }
@@ -1,41 +1,5 @@
1
- import { type Callback } from "./utils.js";
2
- import { type Address, type Instruction } from "@solana/kit";
1
+ import { type Address } from "@solana/kit";
3
2
  import type { TransactionSendingSigner } from "@solana/signers";
4
- export declare let _transacting: boolean;
5
- export declare let transacting: import("svelte/store").Writable<boolean>;
6
- export declare const TRANSACTION_STATE: {
7
- INITIAL: string;
8
- REQUESTED: string;
9
- PENDING: string;
10
- };
11
- export declare const transactionState: import("svelte/store").Writable<string>;
12
- export declare const onTransaction: {
13
- request: {
14
- (callback: Callback): () => void;
15
- trigger: (...args: any[]) => Promise<void>;
16
- killAll: () => void;
17
- };
18
- submit: {
19
- (callback: Callback): () => void;
20
- trigger: (...args: any[]) => Promise<void>;
21
- killAll: () => void;
22
- };
23
- confirm: {
24
- (callback: Callback): () => void;
25
- trigger: (...args: any[]) => Promise<void>;
26
- killAll: () => void;
27
- };
28
- cancel: {
29
- (callback: Callback): () => void;
30
- trigger: (...args: any[]) => Promise<void>;
31
- killAll: () => void;
32
- };
33
- fail: {
34
- (callback: Callback): () => void;
35
- trigger: (...args: any[]) => Promise<void>;
36
- killAll: () => void;
37
- };
38
- };
39
3
  export declare function clearAddedAccounts(): void;
40
4
  export declare function addAccounts(accounts: {
41
5
  [key: string]: Address;
@@ -43,8 +7,6 @@ export declare function addAccounts(accounts: {
43
7
  export declare function getAddedAccounts(): {
44
8
  [key: string]: Address;
45
9
  };
46
- export declare function transact(ixs?: Instruction[], names?: string[]): Promise<void>;
47
- export declare function transactSingle(ix: Instruction, name?: string | null): Promise<void>;
48
10
  export declare function createProgram(programClient: {
49
11
  [key: string]: any;
50
12
  }, idl: {
@@ -4,35 +4,9 @@ import { Event } from "./utils.js";
4
4
  import { signer } from "./wallet.js";
5
5
  import { getConnection } from "./connection.js";
6
6
  import { typeEncoder } from "./utils.js";
7
- import { fetchEncodedAccount, getBase64Codec } from "@solana/kit";
7
+ import { appendTransactionMessageInstructions, assertIsTransactionMessageWithSingleSendingSigner, createTransactionMessage, fetchEncodedAccount, getBase64Codec, getBase64EncodedWireTransaction, getBase64Encoder, getTransactionEncoder, partiallySignTransactionMessageWithSigners, partiallySignTransactionWithSigners, pipe, sequentialInstructionPlan, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, signTransactionMessageWithSigners, singleInstructionPlan } from "@solana/kit";
8
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
- };
9
+ import { transactSingle } from "./transaction.js";
36
10
  let addedAccounts = {};
37
11
  export function clearAddedAccounts() {
38
12
  addedAccounts = {};
@@ -45,53 +19,6 @@ export function addAccounts(accounts) {
45
19
  export function getAddedAccounts() {
46
20
  return addedAccounts;
47
21
  }
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
- console.error(e);
81
- if (_txWasCancelled(e)) {
82
- // TODO: properly catch this and other errors
83
- onCancel.trigger(names);
84
- }
85
- else {
86
- onFail.trigger(names);
87
- }
88
- _setTransacting(INITIAL);
89
- }
90
- }
91
- export async function transactSingle(ix, name = null) {
92
- let names = name ? [name] : [];
93
- return await transact([ix], names);
94
- }
95
22
  export async function createProgram(programClient, idl, signer = null, noEvents = false) {
96
23
  if (!programClient) {
97
24
  throw new Error("Missing program client.");
@@ -0,0 +1,52 @@
1
+ import { type Instruction } from "@solana/kit";
2
+ export declare let _transacting: boolean;
3
+ export declare let transacting: import("svelte/store").Writable<boolean>;
4
+ export declare const TRANSACTION_STATE: {
5
+ INITIAL: string;
6
+ REQUESTED: string;
7
+ PENDING: string;
8
+ };
9
+ export declare const transactionState: import("svelte/store").Writable<string>;
10
+ export declare const onTransaction: {
11
+ request: {
12
+ (callback: import("./utils.ts").Callback): () => void;
13
+ trigger: (...args: any[]) => Promise<void>;
14
+ killAll: () => void;
15
+ };
16
+ submit: {
17
+ (callback: import("./utils.ts").Callback): () => void;
18
+ trigger: (...args: any[]) => Promise<void>;
19
+ killAll: () => void;
20
+ };
21
+ confirm: {
22
+ (callback: import("./utils.ts").Callback): () => void;
23
+ trigger: (...args: any[]) => Promise<void>;
24
+ killAll: () => void;
25
+ };
26
+ cancel: {
27
+ (callback: import("./utils.ts").Callback): () => void;
28
+ trigger: (...args: any[]) => Promise<void>;
29
+ killAll: () => void;
30
+ };
31
+ fail: {
32
+ (callback: import("./utils.ts").Callback): () => void;
33
+ trigger: (...args: any[]) => Promise<void>;
34
+ killAll: () => void;
35
+ };
36
+ };
37
+ export type Simulation = {
38
+ result: any;
39
+ success: boolean;
40
+ error: null | SimulationError;
41
+ };
42
+ export type SimulationError = {
43
+ instruction: string;
44
+ type: string;
45
+ code: string;
46
+ number: number;
47
+ label: string;
48
+ anchorErrorLog: string;
49
+ };
50
+ export declare function simulate(ixs?: Instruction[]): Promise<Simulation>;
51
+ export declare function transact(ixs?: Instruction[], names?: string[], preSimulate?: boolean): Promise<void>;
52
+ export declare function transactSingle(ix: Instruction, name?: string | null, preSimulate?: boolean): Promise<void>;
@@ -0,0 +1,180 @@
1
+ import { writable } from "svelte/store";
2
+ import { Event } from "./utils.js";
3
+ import { signer } from "./wallet.js";
4
+ import { appendTransactionMessageInstructions, assertIsTransactionMessageWithSingleSendingSigner, createTransactionMessage, getBase64EncodedWireTransaction, partiallySignTransactionMessageWithSigners, pipe, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash } from "@solana/kit";
5
+ import { getConnection } from "./connection.js";
6
+ export let _transacting = false;
7
+ export let transacting = writable(_transacting);
8
+ function _setTransacting(state) {
9
+ _transacting = state !== TRANSACTION_STATE.INITIAL;
10
+ transacting.set(_transacting);
11
+ }
12
+ export const TRANSACTION_STATE = {
13
+ INITIAL: "INITIAL",
14
+ REQUESTED: "REQUESTED",
15
+ PENDING: "PENDING",
16
+ };
17
+ const INITIAL = TRANSACTION_STATE.INITIAL;
18
+ const REQUESTED = TRANSACTION_STATE.REQUESTED;
19
+ const PENDING = TRANSACTION_STATE.PENDING;
20
+ export const transactionState = writable(TRANSACTION_STATE.INITIAL);
21
+ const onRequest = Event();
22
+ const onSubmit = Event();
23
+ const onConfirm = Event();
24
+ const onCancel = Event();
25
+ const onFail = Event();
26
+ export const onTransaction = {
27
+ request: onRequest,
28
+ submit: onSubmit,
29
+ confirm: onConfirm,
30
+ cancel: onCancel,
31
+ fail: onFail,
32
+ };
33
+ function _txWasCancelled(e) {
34
+ let msg;
35
+ if (e.message) {
36
+ msg = e.message.toLowerCase();
37
+ }
38
+ else {
39
+ msg = e.toString().toLowerCase();
40
+ }
41
+ return msg.includes('denied') || msg.includes('rejected') || msg.includes('cancelled');
42
+ }
43
+ function _parseError(result) {
44
+ const instructionPrefix = "Program log: Instruction: ";
45
+ const errorPrefix = "Program log: AnchorError ";
46
+ const programErrorPrefix = errorPrefix + "thrown";
47
+ const errorCodeFlag = "failed: custom program error: ";
48
+ function _isPrefix(log, prefix) {
49
+ return (log.substring(0, prefix.length) === prefix);
50
+ }
51
+ function _between(str, prefix, suffix) {
52
+ if (!str.includes(prefix) || !str.includes(suffix))
53
+ return "";
54
+ let from = str.indexOf(prefix) + prefix.length;
55
+ let to;
56
+ if (suffix.length === 0) {
57
+ to = str.length;
58
+ }
59
+ else {
60
+ to = str.indexOf(suffix);
61
+ }
62
+ return str.substring(from, to);
63
+ }
64
+ let errorType = "anchor";
65
+ let instruction = "";
66
+ let errorNumber = 0;
67
+ let errorMessage = "";
68
+ let errorLabel = "";
69
+ let anchorErrorLog = "";
70
+ let errorCode = "";
71
+ const logs = result.value.logs;
72
+ for (let log of logs) {
73
+ if (_isPrefix(log, instructionPrefix)) {
74
+ instruction = log.substring(instructionPrefix.length);
75
+ }
76
+ else if (_isPrefix(log, errorPrefix)) {
77
+ anchorErrorLog = log;
78
+ if (_isPrefix(log, programErrorPrefix)) {
79
+ errorType = "program";
80
+ }
81
+ else {
82
+ errorType = "anchor";
83
+ //TODO: catch other
84
+ }
85
+ errorNumber = Number(_between(log, "Error Number: ", ". Error Message:"));
86
+ errorMessage = _between(log, " Error Message: ", "");
87
+ errorLabel = _between(log, "Error Code: ", ". Error Number:");
88
+ }
89
+ else if (log.includes(errorCodeFlag)) {
90
+ errorCode = _between(log, errorCodeFlag, "");
91
+ }
92
+ }
93
+ return {
94
+ instruction,
95
+ type: errorType,
96
+ code: errorCode,
97
+ number: errorNumber,
98
+ label: errorLabel,
99
+ anchorErrorLog: anchorErrorLog,
100
+ };
101
+ }
102
+ export async function simulate(ixs = []) {
103
+ const connection = getConnection();
104
+ const rpc = connection.rpc;
105
+ let simulateTxConfig = {
106
+ commitment: "finalized",
107
+ encoding: "base64",
108
+ replaceRecentBlockhash: true,
109
+ sigVerify: false,
110
+ minContextSlot: undefined,
111
+ innerInstructions: true,
112
+ accounts: undefined
113
+ };
114
+ const feePayer = signer;
115
+ // Set up an abort controller.
116
+ const abortController = new AbortController();
117
+ const abortSignal = abortController.signal;
118
+ const { value: latestBlockhash } = await rpc.getLatestBlockhash().send({ abortSignal });
119
+ const transactionMessage = pipe(createTransactionMessage({ version: 0 }), (message) => setTransactionMessageFeePayerSigner(feePayer, message), (message) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, message), (message) => appendTransactionMessageInstructions(ixs, message));
120
+ assertIsTransactionMessageWithSingleSendingSigner(transactionMessage);
121
+ const partiallySigned = await partiallySignTransactionMessageWithSigners(transactionMessage);
122
+ const base64EncodedWireTransaction = getBase64EncodedWireTransaction(partiallySigned);
123
+ let simulateResult = await rpc
124
+ //@ts-ignore
125
+ .simulateTransaction(base64EncodedWireTransaction, simulateTxConfig)
126
+ .send();
127
+ const success = !Boolean(simulateResult?.value?.err);
128
+ const error = success ? null : _parseError(simulateResult);
129
+ return {
130
+ result: simulateResult,
131
+ success,
132
+ error
133
+ };
134
+ }
135
+ export async function transact(ixs = [], names = [], preSimulate = true) {
136
+ _setTransacting(REQUESTED);
137
+ onRequest.trigger(names);
138
+ if (preSimulate) {
139
+ const simResult = await simulate(ixs);
140
+ if (!simResult.success) {
141
+ console.error(simResult.error);
142
+ onFail.trigger(names);
143
+ _setTransacting(INITIAL);
144
+ return;
145
+ }
146
+ }
147
+ const connection = getConnection();
148
+ try {
149
+ const signature = await connection.sendTransactionFromInstructionsWithWalletApp({
150
+ feePayer: signer,
151
+ instructions: ixs
152
+ });
153
+ _setTransacting(PENDING);
154
+ onSubmit.trigger(names);
155
+ // Set up an abort controller.
156
+ const abortController = new AbortController();
157
+ const confirmed = await connection.getRecentSignatureConfirmation({
158
+ abortSignal: abortController.signal,
159
+ commitment: 'confirmed',
160
+ signature: signature
161
+ });
162
+ _setTransacting(INITIAL);
163
+ onConfirm.trigger(names);
164
+ }
165
+ catch (e) {
166
+ console.error(e);
167
+ if (_txWasCancelled(e)) {
168
+ // TODO: properly catch this and other errors
169
+ onCancel.trigger(names);
170
+ }
171
+ else {
172
+ onFail.trigger(names);
173
+ }
174
+ _setTransacting(INITIAL);
175
+ }
176
+ }
177
+ export async function transactSingle(ix, name = null, preSimulate = true) {
178
+ let names = name ? [name] : [];
179
+ return await transact([ix], names, preSimulate);
180
+ }
@@ -83,8 +83,6 @@ async function connectWallet(uiWallet) {
83
83
  const accountsPromise = connectFeature
84
84
  .connect()
85
85
  .then(({ accounts }) => {
86
- // console.log("connected", accounts);
87
- // return accounts;
88
86
  return accounts.map(getOrCreateUiWalletAccountForStandardWalletAccount_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.bind(null, wallet));
89
87
  });
90
88
  const nextAccounts = await accountsPromise;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kit-squared",
3
- "version": "0.2.7",
3
+ "version": "1.0.0",
4
4
  "description": "Solana Kit functionality with SvelteKit",
5
5
  "license": "ISC",
6
6
  "author": "AnAllergyToAnalogy",