@fogo/sessions-sdk 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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,37 @@
1
+ import type { Transaction } from "@solana/kit";
2
+ import type { Connection, TransactionError, TransactionInstruction } from "@solana/web3.js";
3
+ import { PublicKey } from "@solana/web3.js";
4
+ export type SessionAdapter = {
5
+ chainId: string;
6
+ connection: Connection;
7
+ payer: PublicKey;
8
+ domain: string;
9
+ sendTransaction: (sessionKey: CryptoKeyPair, instructions: TransactionInstruction[]) => Promise<TransactionResult>;
10
+ };
11
+ export declare enum TransactionResultType {
12
+ Success = 0,
13
+ Failed = 1
14
+ }
15
+ declare const TransactionResult: {
16
+ Success: (signature: string) => {
17
+ type: TransactionResultType.Success;
18
+ signature: string;
19
+ };
20
+ Failed: (signature: string, error: TransactionError) => {
21
+ type: TransactionResultType.Failed;
22
+ signature: string;
23
+ error: TransactionError;
24
+ };
25
+ };
26
+ export type TransactionResult = ReturnType<(typeof TransactionResult)[keyof typeof TransactionResult]>;
27
+ export declare const createSolanaWalletAdapter: (options: {
28
+ connection: Connection;
29
+ sponsor: PublicKey;
30
+ addressLookupTableAddress?: string | undefined;
31
+ domain?: string | undefined;
32
+ } & ({
33
+ paymasterUrl: string;
34
+ } | {
35
+ sendToPaymaster: (transaction: Transaction) => Promise<string>;
36
+ })) => Promise<SessionAdapter>;
37
+ export {};
package/cjs/adapter.js ADDED
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSolanaWalletAdapter = exports.TransactionResultType = void 0;
4
+ const anchor_1 = require("@coral-xyz/anchor");
5
+ const sessions_idls_1 = require("@fogo/sessions-idls");
6
+ const compat_1 = require("@solana/compat");
7
+ const kit_1 = require("@solana/kit");
8
+ const web3_js_1 = require("@solana/web3.js");
9
+ // eslint-disable-next-line no-constant-binary-expression, @typescript-eslint/no-unnecessary-condition, valid-typeof
10
+ const IS_BROWSER = typeof globalThis.window !== undefined;
11
+ var TransactionResultType;
12
+ (function (TransactionResultType) {
13
+ TransactionResultType[TransactionResultType["Success"] = 0] = "Success";
14
+ TransactionResultType[TransactionResultType["Failed"] = 1] = "Failed";
15
+ })(TransactionResultType || (exports.TransactionResultType = TransactionResultType = {}));
16
+ const TransactionResult = {
17
+ Success: (signature) => ({
18
+ type: TransactionResultType.Success,
19
+ signature,
20
+ }),
21
+ Failed: (signature, error) => ({
22
+ type: TransactionResultType.Failed,
23
+ signature,
24
+ error,
25
+ }),
26
+ };
27
+ const createSolanaWalletAdapter = async (options) => {
28
+ const addressLookupTables = await getAddressLookupTables(options.connection, options.addressLookupTableAddress);
29
+ return {
30
+ connection: options.connection,
31
+ payer: options.sponsor,
32
+ chainId: await fetchChainId(options.connection),
33
+ domain: getDomain(options.domain),
34
+ sendTransaction: async (sessionKey, instructions) => {
35
+ const rpc = (0, kit_1.createSolanaRpc)(options.connection.rpcEndpoint);
36
+ const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
37
+ const sessionKeySigner = await (0, kit_1.createSignerFromKeyPair)(sessionKey);
38
+ const transaction = await (0, kit_1.partiallySignTransactionMessageWithSigners)((0, kit_1.pipe)((0, kit_1.createTransactionMessage)({ version: 0 }), (tx) => (0, kit_1.setTransactionMessageFeePayer)((0, compat_1.fromLegacyPublicKey)(options.sponsor), tx), (tx) => (0, kit_1.setTransactionMessageLifetimeUsingBlockhash)(latestBlockhash, tx), (tx) => (0, kit_1.appendTransactionMessageInstructions)(instructions.map((instruction) => (0, compat_1.fromLegacyTransactionInstruction)(instruction)), tx), (tx) => (0, kit_1.compressTransactionMessageUsingAddressLookupTables)(tx, Object.fromEntries(addressLookupTables?.map((table) => [
39
+ (0, compat_1.fromLegacyPublicKey)(table.key),
40
+ table.state.addresses.map((address) => (0, compat_1.fromLegacyPublicKey)(address)),
41
+ ]) ?? [])), (tx) => (0, kit_1.addSignersToTransactionMessage)([sessionKeySigner], tx)));
42
+ const signature = "sendToPaymaster" in options
43
+ ? await options.sendToPaymaster(transaction)
44
+ : await sendToPaymaster(options.paymasterUrl, transaction);
45
+ const lastValidBlockHeight = await rpc.getSlot().send();
46
+ const confirmationResult = await options.connection.confirmTransaction({
47
+ signature,
48
+ blockhash: latestBlockhash.blockhash.toString(),
49
+ lastValidBlockHeight: Number(lastValidBlockHeight),
50
+ });
51
+ return confirmationResult.value.err === null
52
+ ? TransactionResult.Success(signature)
53
+ : TransactionResult.Failed(signature, confirmationResult.value.err);
54
+ },
55
+ };
56
+ };
57
+ exports.createSolanaWalletAdapter = createSolanaWalletAdapter;
58
+ const sendToPaymaster = async (paymasterUrl, transaction) => {
59
+ const response = await fetch(paymasterUrl, {
60
+ method: "POST",
61
+ headers: {
62
+ "Content-Type": "application/json",
63
+ },
64
+ body: JSON.stringify({
65
+ transaction: (0, kit_1.getBase64EncodedWireTransaction)(transaction),
66
+ }),
67
+ });
68
+ if (response.status === 200) {
69
+ return response.text();
70
+ }
71
+ else {
72
+ throw new PaymasterResponseError(response.status, await response.text());
73
+ }
74
+ };
75
+ const getAddressLookupTables = async (connection, addressLookupTableAddress) => {
76
+ if (addressLookupTableAddress === undefined) {
77
+ return [];
78
+ }
79
+ else {
80
+ const addressLookupTableResult = await connection.getAddressLookupTable(new web3_js_1.PublicKey(addressLookupTableAddress));
81
+ return addressLookupTableResult.value
82
+ ? [addressLookupTableResult.value]
83
+ : undefined;
84
+ }
85
+ };
86
+ const fetchChainId = async (connection) => {
87
+ const chainIdProgram = new sessions_idls_1.ChainIdProgram(new anchor_1.AnchorProvider(connection, { publicKey: new web3_js_1.Keypair().publicKey }, {})); // We mock the wallet because we don't need to sign anything
88
+ const { chainIdAccount: chainIdAddress } = await chainIdProgram.methods
89
+ .set("")
90
+ .pubkeys(); // We use Anchor to derive the chain ID address, not caring about the actual argument of `set`
91
+ if (chainIdAddress === undefined) {
92
+ throw new NoChainIdAddressError();
93
+ }
94
+ const chainId = await chainIdProgram.account.chainId.fetch(chainIdAddress);
95
+ return chainId.chainId;
96
+ };
97
+ const getDomain = (requestedDomain) => {
98
+ const detectedDomain = IS_BROWSER ? globalThis.location.origin : undefined;
99
+ if (requestedDomain === undefined) {
100
+ if (detectedDomain === undefined) {
101
+ throw new DomainRequiredError();
102
+ }
103
+ else {
104
+ return detectedDomain;
105
+ }
106
+ }
107
+ else {
108
+ if (detectedDomain === undefined ||
109
+ detectedDomain === requestedDomain ||
110
+ process.env.NODE_ENV !== "production" // eslint-disable-line n/no-process-env
111
+ ) {
112
+ return requestedDomain;
113
+ }
114
+ else {
115
+ throw new DomainOverrideNotAllowedError();
116
+ }
117
+ }
118
+ };
119
+ class PaymasterResponseError extends Error {
120
+ constructor(statusCode, message) {
121
+ super(`Paymaster sent a ${statusCode.toString()} response: ${message}`);
122
+ this.name = "PaymasterResponseError";
123
+ }
124
+ }
125
+ class NoChainIdAddressError extends Error {
126
+ constructor() {
127
+ super("Failed to derive chain ID address");
128
+ this.name = "NoChainIdAddressError";
129
+ }
130
+ }
131
+ class DomainRequiredError extends Error {
132
+ constructor() {
133
+ super("On platforms where the origin cannot be determined, you must pass a domain to create a session.");
134
+ this.name = "DomainRequiredError";
135
+ }
136
+ }
137
+ class DomainOverrideNotAllowedError extends Error {
138
+ constructor() {
139
+ super("You cannot create a session for a different domain.");
140
+ this.name = "DomainOverrideNotAllowedError";
141
+ }
142
+ }
package/cjs/index.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { TransactionError } from "@solana/web3.js";
2
+ import { PublicKey, TransactionInstruction } from "@solana/web3.js";
3
+ import type { SessionAdapter, TransactionResult } from "./adapter.js";
4
+ export { type SessionAdapter, type TransactionResult, TransactionResultType, createSolanaWalletAdapter, } from "./adapter.js";
5
+ type EstablishSessionOptions = {
6
+ adapter: SessionAdapter;
7
+ walletPublicKey: PublicKey;
8
+ signMessage: (message: Uint8Array) => Promise<Uint8Array>;
9
+ expires: Date;
10
+ limits: Map<PublicKey, bigint>;
11
+ extra?: string | undefined;
12
+ };
13
+ export declare const establishSession: (options: EstablishSessionOptions) => Promise<EstablishSessionResult>;
14
+ export declare const replaceSession: (options: {
15
+ adapter: SessionAdapter;
16
+ session: Session;
17
+ signMessage: (message: Uint8Array) => Promise<Uint8Array>;
18
+ expires: Date;
19
+ limits: Map<PublicKey, bigint>;
20
+ extra?: string | undefined;
21
+ }) => Promise<EstablishSessionResult>;
22
+ export declare const reestablishSession: (adapter: SessionAdapter, walletPublicKey: PublicKey, sessionKey: CryptoKeyPair) => Promise<Session>;
23
+ export declare const getDomainRecordAddress: (domain: string) => PublicKey;
24
+ export declare enum SessionResultType {
25
+ Success = 0,
26
+ Failed = 1
27
+ }
28
+ declare const EstablishSessionResult: {
29
+ Success: (signature: string, session: Session) => {
30
+ type: SessionResultType.Success;
31
+ signature: string;
32
+ session: Session;
33
+ };
34
+ Failed: (signature: string, error: TransactionError) => {
35
+ type: SessionResultType.Failed;
36
+ signature: string;
37
+ error: TransactionError;
38
+ };
39
+ };
40
+ type EstablishSessionResult = ReturnType<(typeof EstablishSessionResult)[keyof typeof EstablishSessionResult]>;
41
+ export type Session = {
42
+ sessionPublicKey: PublicKey;
43
+ sessionKey: CryptoKeyPair;
44
+ walletPublicKey: PublicKey;
45
+ payer: PublicKey;
46
+ sendTransaction: (instructions: TransactionInstruction[]) => Promise<TransactionResult>;
47
+ };
package/cjs/index.js ADDED
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionResultType = exports.getDomainRecordAddress = exports.reestablishSession = exports.replaceSession = exports.establishSession = exports.createSolanaWalletAdapter = exports.TransactionResultType = void 0;
4
+ const anchor_1 = require("@coral-xyz/anchor");
5
+ const sessions_idls_1 = require("@fogo/sessions-idls");
6
+ const mpl_token_metadata_1 = require("@metaplex-foundation/mpl-token-metadata");
7
+ const umi_1 = require("@metaplex-foundation/umi");
8
+ const umi_bundle_defaults_1 = require("@metaplex-foundation/umi-bundle-defaults");
9
+ const sha2_1 = require("@noble/hashes/sha2");
10
+ const kit_1 = require("@solana/kit");
11
+ const spl_token_1 = require("@solana/spl-token");
12
+ const web3_js_1 = require("@solana/web3.js");
13
+ const adapter_js_1 = require("./adapter.js");
14
+ var adapter_js_2 = require("./adapter.js");
15
+ Object.defineProperty(exports, "TransactionResultType", { enumerable: true, get: function () { return adapter_js_2.TransactionResultType; } });
16
+ Object.defineProperty(exports, "createSolanaWalletAdapter", { enumerable: true, get: function () { return adapter_js_2.createSolanaWalletAdapter; } });
17
+ const MESSAGE_HEADER = `Fogo Sessions:
18
+ Signing this intent will allow this app to interact with your on-chain balances. Please make sure you trust this app and the domain in the message matches the domain of the current web application.
19
+ `;
20
+ const CURRENT_MAJOR = "0";
21
+ const CURRENT_MINOR = "1";
22
+ const establishSession = async (options) => {
23
+ const sessionKey = await (0, kit_1.generateKeyPair)();
24
+ const tokenInfo = await getTokenInfo(options);
25
+ const [intentInstruction, startSessionInstruction] = await Promise.all([
26
+ buildIntentInstruction(options, sessionKey, tokenInfo),
27
+ buildStartSessionInstruction(options, sessionKey, tokenInfo),
28
+ ]);
29
+ const result = await options.adapter.sendTransaction(sessionKey, [
30
+ intentInstruction,
31
+ ...buildCreateAssociatedTokenAccountInstructions(options, tokenInfo),
32
+ startSessionInstruction,
33
+ ]);
34
+ switch (result.type) {
35
+ case adapter_js_1.TransactionResultType.Success: {
36
+ return EstablishSessionResult.Success(result.signature, await createSession(options.adapter, options.walletPublicKey, sessionKey));
37
+ }
38
+ case adapter_js_1.TransactionResultType.Failed: {
39
+ return EstablishSessionResult.Failed(result.signature, result.error);
40
+ }
41
+ }
42
+ };
43
+ exports.establishSession = establishSession;
44
+ const replaceSession = async (options) => (0, exports.establishSession)({
45
+ ...options,
46
+ walletPublicKey: options.session.walletPublicKey,
47
+ });
48
+ exports.replaceSession = replaceSession;
49
+ // TODO we really should check to ensure the session is still valid...
50
+ const reestablishSession = async (adapter, walletPublicKey, sessionKey) => createSession(adapter, walletPublicKey, sessionKey);
51
+ exports.reestablishSession = reestablishSession;
52
+ const createSession = async (adapter, walletPublicKey, sessionKey) => ({
53
+ sessionPublicKey: new web3_js_1.PublicKey(await (0, kit_1.getAddressFromPublicKey)(sessionKey.publicKey)),
54
+ walletPublicKey,
55
+ sessionKey,
56
+ payer: adapter.payer,
57
+ sendTransaction: (instructions) => adapter.sendTransaction(sessionKey, instructions),
58
+ });
59
+ const SymbolOrMintType = {
60
+ Symbol: "Symbol",
61
+ Mint: "Mint",
62
+ };
63
+ const SymbolOrMint = {
64
+ Symbol: (symbol) => ({
65
+ type: SymbolOrMintType.Symbol,
66
+ symbol,
67
+ }),
68
+ Mint: (mint) => ({
69
+ type: SymbolOrMintType.Mint,
70
+ mint,
71
+ }),
72
+ };
73
+ const getTokenInfo = async (options) => {
74
+ const umi = (0, umi_bundle_defaults_1.createUmi)(options.adapter.connection.rpcEndpoint);
75
+ return Promise.all(options.limits.entries().map(async ([mint, amount]) => {
76
+ const metaplexMint = (0, umi_1.publicKey)(mint.toBase58());
77
+ const metadataAddress = (0, mpl_token_metadata_1.findMetadataPda)(umi, { mint: metaplexMint })[0];
78
+ const [mintInfo, metadata] = await Promise.all([
79
+ (0, spl_token_1.getMint)(options.adapter.connection, mint),
80
+ (0, mpl_token_metadata_1.safeFetchMetadata)(umi, metadataAddress),
81
+ ]);
82
+ return {
83
+ symbolOrMint: metadata?.symbol
84
+ ? SymbolOrMint.Symbol(metadata.symbol)
85
+ : SymbolOrMint.Mint(mint),
86
+ metadataAddress: new web3_js_1.PublicKey(metadataAddress),
87
+ amount,
88
+ mint,
89
+ decimals: mintInfo.decimals,
90
+ };
91
+ }));
92
+ };
93
+ const buildIntentInstruction = async (options, sessionKey, tokens) => {
94
+ const message = await buildMessage({
95
+ chainId: options.adapter.chainId,
96
+ domain: options.adapter.domain,
97
+ sessionKey,
98
+ expires: options.expires,
99
+ tokens,
100
+ extra: options.extra,
101
+ });
102
+ const intentSignature = await options.signMessage(message);
103
+ return web3_js_1.Ed25519Program.createInstructionWithPublicKey({
104
+ publicKey: options.walletPublicKey.toBytes(),
105
+ signature: intentSignature,
106
+ message: message,
107
+ });
108
+ };
109
+ const buildMessage = async (body) => new TextEncoder().encode([
110
+ MESSAGE_HEADER,
111
+ serializeKV({
112
+ version: `${CURRENT_MAJOR}.${CURRENT_MINOR}`,
113
+ chain_id: body.chainId,
114
+ domain: body.domain,
115
+ expires: body.expires.toISOString(),
116
+ session_key: await (0, kit_1.getAddressFromPublicKey)(body.sessionKey.publicKey),
117
+ tokens: serializeTokenList(body.tokens),
118
+ ...(body.extra && { extra: body.extra }),
119
+ }),
120
+ ].join("\n"));
121
+ const serializeKV = (data) => Object.entries(data)
122
+ .map(([key, value]) => [key, ":", value.startsWith("\n") ? "" : " ", value].join(""))
123
+ .join("\n");
124
+ const serializeTokenList = (tokens) => tokens
125
+ .values()
126
+ .filter(({ amount }) => amount > 0n)
127
+ .map(({ symbolOrMint, amount, decimals }) => `\n-${symbolOrMint.type === SymbolOrMintType.Symbol ? symbolOrMint.symbol : symbolOrMint.mint.toBase58()}: ${amountToString(amount, decimals)}`)
128
+ .toArray()
129
+ .join("");
130
+ const amountToString = (amount, decimals) => {
131
+ const asStr = amount.toString();
132
+ const whole = asStr.length > decimals ? asStr.slice(0, asStr.length - decimals) : "0";
133
+ const decimal = asStr.length > decimals ? asStr.slice(asStr.length - decimals) : asStr;
134
+ const decimalPadded = decimal.padStart(decimals, "0");
135
+ const decimalTruncated = decimalPadded.replace(/0+$/, "");
136
+ return [
137
+ whole,
138
+ ...(decimalTruncated === "" ? [] : [".", decimalTruncated]),
139
+ ].join("");
140
+ };
141
+ const buildCreateAssociatedTokenAccountInstructions = (options, tokens) => tokens.map(({ mint }) => (0, spl_token_1.createAssociatedTokenAccountIdempotentInstruction)(options.adapter.payer, (0, spl_token_1.getAssociatedTokenAddressSync)(mint, options.walletPublicKey), options.walletPublicKey, mint));
142
+ const getDomainRecordAddress = (domain) => {
143
+ const hash = (0, sha2_1.sha256)(domain);
144
+ return web3_js_1.PublicKey.findProgramAddressSync([Buffer.from("domain-record"), hash], new web3_js_1.PublicKey(sessions_idls_1.DomainRegistryIdl.address))[0];
145
+ };
146
+ exports.getDomainRecordAddress = getDomainRecordAddress;
147
+ const buildStartSessionInstruction = async (options, sessionKey, tokens) => new sessions_idls_1.SessionManagerProgram(new anchor_1.AnchorProvider(options.adapter.connection, {}, {})).methods
148
+ .startSession()
149
+ .accounts({
150
+ sponsor: options.adapter.payer,
151
+ session: await (0, kit_1.getAddressFromPublicKey)(sessionKey.publicKey),
152
+ domainRegistry: (0, exports.getDomainRecordAddress)(options.adapter.domain),
153
+ })
154
+ .remainingAccounts(tokens.flatMap(({ symbolOrMint, mint, metadataAddress }) => [
155
+ {
156
+ pubkey: (0, spl_token_1.getAssociatedTokenAddressSync)(mint, options.walletPublicKey),
157
+ isWritable: true,
158
+ isSigner: false,
159
+ },
160
+ {
161
+ pubkey: mint,
162
+ isWritable: false,
163
+ isSigner: false,
164
+ },
165
+ ...(symbolOrMint.type === SymbolOrMintType.Symbol
166
+ ? [
167
+ {
168
+ pubkey: metadataAddress,
169
+ isWritable: false,
170
+ isSigner: false,
171
+ },
172
+ ]
173
+ : []),
174
+ ]))
175
+ .instruction();
176
+ var SessionResultType;
177
+ (function (SessionResultType) {
178
+ SessionResultType[SessionResultType["Success"] = 0] = "Success";
179
+ SessionResultType[SessionResultType["Failed"] = 1] = "Failed";
180
+ })(SessionResultType || (exports.SessionResultType = SessionResultType = {}));
181
+ const EstablishSessionResult = {
182
+ Success: (signature, session) => ({
183
+ type: SessionResultType.Success,
184
+ signature,
185
+ session,
186
+ }),
187
+ Failed: (signature, error) => ({
188
+ type: SessionResultType.Failed,
189
+ signature,
190
+ error,
191
+ }),
192
+ };
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,7 @@
1
+ import type { Transaction, Rpc, SolanaRpcApi } from "@solana/kit";
2
+ import { Keypair } from "@solana/web3.js";
3
+ export declare const sponsorAndSend: (rpc: Rpc<SolanaRpcApi>, sponsor: CryptoKeyPair, transaction: Transaction) => Promise<import("@solana/kit").Signature>;
4
+ export declare const createPaymasterEndpoint: (options: {
5
+ rpc: string;
6
+ sponsor: Keypair;
7
+ }) => Promise<(req: Request) => Promise<Response>>;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPaymasterEndpoint = exports.sponsorAndSend = void 0;
4
+ const compat_1 = require("@solana/compat");
5
+ const kit_1 = require("@solana/kit");
6
+ const zod_1 = require("zod");
7
+ const sponsorAndSend = async (rpc, sponsor, transaction) => {
8
+ const signedTransaction = await (0, kit_1.signTransaction)([sponsor], transaction);
9
+ await rpc
10
+ .sendTransaction((0, kit_1.getBase64EncodedWireTransaction)(signedTransaction), {
11
+ encoding: "base64",
12
+ skipPreflight: true,
13
+ })
14
+ .send();
15
+ return (0, kit_1.getSignatureFromTransaction)(signedTransaction);
16
+ };
17
+ exports.sponsorAndSend = sponsorAndSend;
18
+ const createPaymasterEndpoint = async (options) => {
19
+ const rpc = (0, kit_1.createSolanaRpc)(options.rpc);
20
+ const sponsor = await (0, compat_1.fromLegacyKeypair)(options.sponsor);
21
+ return async (req) => {
22
+ const data = postBodySchema.parse(await req.json());
23
+ try {
24
+ const transaction = (0, kit_1.getTransactionDecoder)().decode((0, kit_1.getBase64Encoder)().encode(data.transaction));
25
+ try {
26
+ return new Response(await (0, exports.sponsorAndSend)(rpc, sponsor, transaction));
27
+ }
28
+ catch (error) {
29
+ // eslint-disable-next-line no-console
30
+ console.error(error);
31
+ return new Response(`Failed to sponsor and send: ${serializeError(error)}`, { status: 500 });
32
+ }
33
+ }
34
+ catch (error) {
35
+ // eslint-disable-next-line no-console
36
+ console.error(error);
37
+ return new Response("Failed to deserialize transaction", { status: 400 });
38
+ }
39
+ };
40
+ };
41
+ exports.createPaymasterEndpoint = createPaymasterEndpoint;
42
+ const postBodySchema = zod_1.z.strictObject({
43
+ transaction: zod_1.z.string(),
44
+ });
45
+ const serializeError = (error) => {
46
+ if (error instanceof Error) {
47
+ return error.message;
48
+ }
49
+ else if (typeof error === "string") {
50
+ return error.toString();
51
+ }
52
+ else {
53
+ return "Unknown Error";
54
+ }
55
+ };
@@ -0,0 +1,37 @@
1
+ import type { Transaction } from "@solana/kit";
2
+ import type { Connection, TransactionError, TransactionInstruction } from "@solana/web3.js";
3
+ import { PublicKey } from "@solana/web3.js";
4
+ export type SessionAdapter = {
5
+ chainId: string;
6
+ connection: Connection;
7
+ payer: PublicKey;
8
+ domain: string;
9
+ sendTransaction: (sessionKey: CryptoKeyPair, instructions: TransactionInstruction[]) => Promise<TransactionResult>;
10
+ };
11
+ export declare enum TransactionResultType {
12
+ Success = 0,
13
+ Failed = 1
14
+ }
15
+ declare const TransactionResult: {
16
+ Success: (signature: string) => {
17
+ type: TransactionResultType.Success;
18
+ signature: string;
19
+ };
20
+ Failed: (signature: string, error: TransactionError) => {
21
+ type: TransactionResultType.Failed;
22
+ signature: string;
23
+ error: TransactionError;
24
+ };
25
+ };
26
+ export type TransactionResult = ReturnType<(typeof TransactionResult)[keyof typeof TransactionResult]>;
27
+ export declare const createSolanaWalletAdapter: (options: {
28
+ connection: Connection;
29
+ sponsor: PublicKey;
30
+ addressLookupTableAddress?: string | undefined;
31
+ domain?: string | undefined;
32
+ } & ({
33
+ paymasterUrl: string;
34
+ } | {
35
+ sendToPaymaster: (transaction: Transaction) => Promise<string>;
36
+ })) => Promise<SessionAdapter>;
37
+ export {};
package/esm/adapter.js ADDED
@@ -0,0 +1,138 @@
1
+ import { AnchorProvider } from "@coral-xyz/anchor";
2
+ import { ChainIdProgram } from "@fogo/sessions-idls";
3
+ import { fromLegacyPublicKey, fromLegacyTransactionInstruction, } from "@solana/compat";
4
+ import { createTransactionMessage, setTransactionMessageFeePayer, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, getBase64EncodedWireTransaction, partiallySignTransactionMessageWithSigners, pipe, createSolanaRpc, addSignersToTransactionMessage, compressTransactionMessageUsingAddressLookupTables, createSignerFromKeyPair, } from "@solana/kit";
5
+ import { PublicKey, Keypair } from "@solana/web3.js";
6
+ // eslint-disable-next-line no-constant-binary-expression, @typescript-eslint/no-unnecessary-condition, valid-typeof
7
+ const IS_BROWSER = typeof globalThis.window !== undefined;
8
+ export var TransactionResultType;
9
+ (function (TransactionResultType) {
10
+ TransactionResultType[TransactionResultType["Success"] = 0] = "Success";
11
+ TransactionResultType[TransactionResultType["Failed"] = 1] = "Failed";
12
+ })(TransactionResultType || (TransactionResultType = {}));
13
+ const TransactionResult = {
14
+ Success: (signature) => ({
15
+ type: TransactionResultType.Success,
16
+ signature,
17
+ }),
18
+ Failed: (signature, error) => ({
19
+ type: TransactionResultType.Failed,
20
+ signature,
21
+ error,
22
+ }),
23
+ };
24
+ export const createSolanaWalletAdapter = async (options) => {
25
+ const addressLookupTables = await getAddressLookupTables(options.connection, options.addressLookupTableAddress);
26
+ return {
27
+ connection: options.connection,
28
+ payer: options.sponsor,
29
+ chainId: await fetchChainId(options.connection),
30
+ domain: getDomain(options.domain),
31
+ sendTransaction: async (sessionKey, instructions) => {
32
+ const rpc = createSolanaRpc(options.connection.rpcEndpoint);
33
+ const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
34
+ const sessionKeySigner = await createSignerFromKeyPair(sessionKey);
35
+ const transaction = await partiallySignTransactionMessageWithSigners(pipe(createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayer(fromLegacyPublicKey(options.sponsor), tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(instructions.map((instruction) => fromLegacyTransactionInstruction(instruction)), tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, Object.fromEntries(addressLookupTables?.map((table) => [
36
+ fromLegacyPublicKey(table.key),
37
+ table.state.addresses.map((address) => fromLegacyPublicKey(address)),
38
+ ]) ?? [])), (tx) => addSignersToTransactionMessage([sessionKeySigner], tx)));
39
+ const signature = "sendToPaymaster" in options
40
+ ? await options.sendToPaymaster(transaction)
41
+ : await sendToPaymaster(options.paymasterUrl, transaction);
42
+ const lastValidBlockHeight = await rpc.getSlot().send();
43
+ const confirmationResult = await options.connection.confirmTransaction({
44
+ signature,
45
+ blockhash: latestBlockhash.blockhash.toString(),
46
+ lastValidBlockHeight: Number(lastValidBlockHeight),
47
+ });
48
+ return confirmationResult.value.err === null
49
+ ? TransactionResult.Success(signature)
50
+ : TransactionResult.Failed(signature, confirmationResult.value.err);
51
+ },
52
+ };
53
+ };
54
+ const sendToPaymaster = async (paymasterUrl, transaction) => {
55
+ const response = await fetch(paymasterUrl, {
56
+ method: "POST",
57
+ headers: {
58
+ "Content-Type": "application/json",
59
+ },
60
+ body: JSON.stringify({
61
+ transaction: getBase64EncodedWireTransaction(transaction),
62
+ }),
63
+ });
64
+ if (response.status === 200) {
65
+ return response.text();
66
+ }
67
+ else {
68
+ throw new PaymasterResponseError(response.status, await response.text());
69
+ }
70
+ };
71
+ const getAddressLookupTables = async (connection, addressLookupTableAddress) => {
72
+ if (addressLookupTableAddress === undefined) {
73
+ return [];
74
+ }
75
+ else {
76
+ const addressLookupTableResult = await connection.getAddressLookupTable(new PublicKey(addressLookupTableAddress));
77
+ return addressLookupTableResult.value
78
+ ? [addressLookupTableResult.value]
79
+ : undefined;
80
+ }
81
+ };
82
+ const fetchChainId = async (connection) => {
83
+ const chainIdProgram = new ChainIdProgram(new AnchorProvider(connection, { publicKey: new Keypair().publicKey }, {})); // We mock the wallet because we don't need to sign anything
84
+ const { chainIdAccount: chainIdAddress } = await chainIdProgram.methods
85
+ .set("")
86
+ .pubkeys(); // We use Anchor to derive the chain ID address, not caring about the actual argument of `set`
87
+ if (chainIdAddress === undefined) {
88
+ throw new NoChainIdAddressError();
89
+ }
90
+ const chainId = await chainIdProgram.account.chainId.fetch(chainIdAddress);
91
+ return chainId.chainId;
92
+ };
93
+ const getDomain = (requestedDomain) => {
94
+ const detectedDomain = IS_BROWSER ? globalThis.location.origin : undefined;
95
+ if (requestedDomain === undefined) {
96
+ if (detectedDomain === undefined) {
97
+ throw new DomainRequiredError();
98
+ }
99
+ else {
100
+ return detectedDomain;
101
+ }
102
+ }
103
+ else {
104
+ if (detectedDomain === undefined ||
105
+ detectedDomain === requestedDomain ||
106
+ process.env.NODE_ENV !== "production" // eslint-disable-line n/no-process-env
107
+ ) {
108
+ return requestedDomain;
109
+ }
110
+ else {
111
+ throw new DomainOverrideNotAllowedError();
112
+ }
113
+ }
114
+ };
115
+ class PaymasterResponseError extends Error {
116
+ constructor(statusCode, message) {
117
+ super(`Paymaster sent a ${statusCode.toString()} response: ${message}`);
118
+ this.name = "PaymasterResponseError";
119
+ }
120
+ }
121
+ class NoChainIdAddressError extends Error {
122
+ constructor() {
123
+ super("Failed to derive chain ID address");
124
+ this.name = "NoChainIdAddressError";
125
+ }
126
+ }
127
+ class DomainRequiredError extends Error {
128
+ constructor() {
129
+ super("On platforms where the origin cannot be determined, you must pass a domain to create a session.");
130
+ this.name = "DomainRequiredError";
131
+ }
132
+ }
133
+ class DomainOverrideNotAllowedError extends Error {
134
+ constructor() {
135
+ super("You cannot create a session for a different domain.");
136
+ this.name = "DomainOverrideNotAllowedError";
137
+ }
138
+ }
package/esm/index.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { TransactionError } from "@solana/web3.js";
2
+ import { PublicKey, TransactionInstruction } from "@solana/web3.js";
3
+ import type { SessionAdapter, TransactionResult } from "./adapter.js";
4
+ export { type SessionAdapter, type TransactionResult, TransactionResultType, createSolanaWalletAdapter, } from "./adapter.js";
5
+ type EstablishSessionOptions = {
6
+ adapter: SessionAdapter;
7
+ walletPublicKey: PublicKey;
8
+ signMessage: (message: Uint8Array) => Promise<Uint8Array>;
9
+ expires: Date;
10
+ limits: Map<PublicKey, bigint>;
11
+ extra?: string | undefined;
12
+ };
13
+ export declare const establishSession: (options: EstablishSessionOptions) => Promise<EstablishSessionResult>;
14
+ export declare const replaceSession: (options: {
15
+ adapter: SessionAdapter;
16
+ session: Session;
17
+ signMessage: (message: Uint8Array) => Promise<Uint8Array>;
18
+ expires: Date;
19
+ limits: Map<PublicKey, bigint>;
20
+ extra?: string | undefined;
21
+ }) => Promise<EstablishSessionResult>;
22
+ export declare const reestablishSession: (adapter: SessionAdapter, walletPublicKey: PublicKey, sessionKey: CryptoKeyPair) => Promise<Session>;
23
+ export declare const getDomainRecordAddress: (domain: string) => PublicKey;
24
+ export declare enum SessionResultType {
25
+ Success = 0,
26
+ Failed = 1
27
+ }
28
+ declare const EstablishSessionResult: {
29
+ Success: (signature: string, session: Session) => {
30
+ type: SessionResultType.Success;
31
+ signature: string;
32
+ session: Session;
33
+ };
34
+ Failed: (signature: string, error: TransactionError) => {
35
+ type: SessionResultType.Failed;
36
+ signature: string;
37
+ error: TransactionError;
38
+ };
39
+ };
40
+ type EstablishSessionResult = ReturnType<(typeof EstablishSessionResult)[keyof typeof EstablishSessionResult]>;
41
+ export type Session = {
42
+ sessionPublicKey: PublicKey;
43
+ sessionKey: CryptoKeyPair;
44
+ walletPublicKey: PublicKey;
45
+ payer: PublicKey;
46
+ sendTransaction: (instructions: TransactionInstruction[]) => Promise<TransactionResult>;
47
+ };
package/esm/index.js ADDED
@@ -0,0 +1,183 @@
1
+ import { AnchorProvider, Wallet } from "@coral-xyz/anchor";
2
+ import { DomainRegistryIdl, SessionManagerProgram } from "@fogo/sessions-idls";
3
+ import { findMetadataPda, safeFetchMetadata, } from "@metaplex-foundation/mpl-token-metadata";
4
+ import { publicKey as metaplexPublicKey } from "@metaplex-foundation/umi";
5
+ import { createUmi } from "@metaplex-foundation/umi-bundle-defaults";
6
+ import { sha256 } from "@noble/hashes/sha2";
7
+ import { generateKeyPair, getAddressFromPublicKey } from "@solana/kit";
8
+ import { createAssociatedTokenAccountIdempotentInstruction, getAssociatedTokenAddressSync, getMint, } from "@solana/spl-token";
9
+ import { Ed25519Program, PublicKey, TransactionInstruction, } from "@solana/web3.js";
10
+ import { TransactionResultType } from "./adapter.js";
11
+ export { TransactionResultType, createSolanaWalletAdapter, } from "./adapter.js";
12
+ const MESSAGE_HEADER = `Fogo Sessions:
13
+ Signing this intent will allow this app to interact with your on-chain balances. Please make sure you trust this app and the domain in the message matches the domain of the current web application.
14
+ `;
15
+ const CURRENT_MAJOR = "0";
16
+ const CURRENT_MINOR = "1";
17
+ export const establishSession = async (options) => {
18
+ const sessionKey = await generateKeyPair();
19
+ const tokenInfo = await getTokenInfo(options);
20
+ const [intentInstruction, startSessionInstruction] = await Promise.all([
21
+ buildIntentInstruction(options, sessionKey, tokenInfo),
22
+ buildStartSessionInstruction(options, sessionKey, tokenInfo),
23
+ ]);
24
+ const result = await options.adapter.sendTransaction(sessionKey, [
25
+ intentInstruction,
26
+ ...buildCreateAssociatedTokenAccountInstructions(options, tokenInfo),
27
+ startSessionInstruction,
28
+ ]);
29
+ switch (result.type) {
30
+ case TransactionResultType.Success: {
31
+ return EstablishSessionResult.Success(result.signature, await createSession(options.adapter, options.walletPublicKey, sessionKey));
32
+ }
33
+ case TransactionResultType.Failed: {
34
+ return EstablishSessionResult.Failed(result.signature, result.error);
35
+ }
36
+ }
37
+ };
38
+ export const replaceSession = async (options) => establishSession({
39
+ ...options,
40
+ walletPublicKey: options.session.walletPublicKey,
41
+ });
42
+ // TODO we really should check to ensure the session is still valid...
43
+ export const reestablishSession = async (adapter, walletPublicKey, sessionKey) => createSession(adapter, walletPublicKey, sessionKey);
44
+ const createSession = async (adapter, walletPublicKey, sessionKey) => ({
45
+ sessionPublicKey: new PublicKey(await getAddressFromPublicKey(sessionKey.publicKey)),
46
+ walletPublicKey,
47
+ sessionKey,
48
+ payer: adapter.payer,
49
+ sendTransaction: (instructions) => adapter.sendTransaction(sessionKey, instructions),
50
+ });
51
+ const SymbolOrMintType = {
52
+ Symbol: "Symbol",
53
+ Mint: "Mint",
54
+ };
55
+ const SymbolOrMint = {
56
+ Symbol: (symbol) => ({
57
+ type: SymbolOrMintType.Symbol,
58
+ symbol,
59
+ }),
60
+ Mint: (mint) => ({
61
+ type: SymbolOrMintType.Mint,
62
+ mint,
63
+ }),
64
+ };
65
+ const getTokenInfo = async (options) => {
66
+ const umi = createUmi(options.adapter.connection.rpcEndpoint);
67
+ return Promise.all(options.limits.entries().map(async ([mint, amount]) => {
68
+ const metaplexMint = metaplexPublicKey(mint.toBase58());
69
+ const metadataAddress = findMetadataPda(umi, { mint: metaplexMint })[0];
70
+ const [mintInfo, metadata] = await Promise.all([
71
+ getMint(options.adapter.connection, mint),
72
+ safeFetchMetadata(umi, metadataAddress),
73
+ ]);
74
+ return {
75
+ symbolOrMint: metadata?.symbol
76
+ ? SymbolOrMint.Symbol(metadata.symbol)
77
+ : SymbolOrMint.Mint(mint),
78
+ metadataAddress: new PublicKey(metadataAddress),
79
+ amount,
80
+ mint,
81
+ decimals: mintInfo.decimals,
82
+ };
83
+ }));
84
+ };
85
+ const buildIntentInstruction = async (options, sessionKey, tokens) => {
86
+ const message = await buildMessage({
87
+ chainId: options.adapter.chainId,
88
+ domain: options.adapter.domain,
89
+ sessionKey,
90
+ expires: options.expires,
91
+ tokens,
92
+ extra: options.extra,
93
+ });
94
+ const intentSignature = await options.signMessage(message);
95
+ return Ed25519Program.createInstructionWithPublicKey({
96
+ publicKey: options.walletPublicKey.toBytes(),
97
+ signature: intentSignature,
98
+ message: message,
99
+ });
100
+ };
101
+ const buildMessage = async (body) => new TextEncoder().encode([
102
+ MESSAGE_HEADER,
103
+ serializeKV({
104
+ version: `${CURRENT_MAJOR}.${CURRENT_MINOR}`,
105
+ chain_id: body.chainId,
106
+ domain: body.domain,
107
+ expires: body.expires.toISOString(),
108
+ session_key: await getAddressFromPublicKey(body.sessionKey.publicKey),
109
+ tokens: serializeTokenList(body.tokens),
110
+ ...(body.extra && { extra: body.extra }),
111
+ }),
112
+ ].join("\n"));
113
+ const serializeKV = (data) => Object.entries(data)
114
+ .map(([key, value]) => [key, ":", value.startsWith("\n") ? "" : " ", value].join(""))
115
+ .join("\n");
116
+ const serializeTokenList = (tokens) => tokens
117
+ .values()
118
+ .filter(({ amount }) => amount > 0n)
119
+ .map(({ symbolOrMint, amount, decimals }) => `\n-${symbolOrMint.type === SymbolOrMintType.Symbol ? symbolOrMint.symbol : symbolOrMint.mint.toBase58()}: ${amountToString(amount, decimals)}`)
120
+ .toArray()
121
+ .join("");
122
+ const amountToString = (amount, decimals) => {
123
+ const asStr = amount.toString();
124
+ const whole = asStr.length > decimals ? asStr.slice(0, asStr.length - decimals) : "0";
125
+ const decimal = asStr.length > decimals ? asStr.slice(asStr.length - decimals) : asStr;
126
+ const decimalPadded = decimal.padStart(decimals, "0");
127
+ const decimalTruncated = decimalPadded.replace(/0+$/, "");
128
+ return [
129
+ whole,
130
+ ...(decimalTruncated === "" ? [] : [".", decimalTruncated]),
131
+ ].join("");
132
+ };
133
+ const buildCreateAssociatedTokenAccountInstructions = (options, tokens) => tokens.map(({ mint }) => createAssociatedTokenAccountIdempotentInstruction(options.adapter.payer, getAssociatedTokenAddressSync(mint, options.walletPublicKey), options.walletPublicKey, mint));
134
+ export const getDomainRecordAddress = (domain) => {
135
+ const hash = sha256(domain);
136
+ return PublicKey.findProgramAddressSync([Buffer.from("domain-record"), hash], new PublicKey(DomainRegistryIdl.address))[0];
137
+ };
138
+ const buildStartSessionInstruction = async (options, sessionKey, tokens) => new SessionManagerProgram(new AnchorProvider(options.adapter.connection, {}, {})).methods
139
+ .startSession()
140
+ .accounts({
141
+ sponsor: options.adapter.payer,
142
+ session: await getAddressFromPublicKey(sessionKey.publicKey),
143
+ domainRegistry: getDomainRecordAddress(options.adapter.domain),
144
+ })
145
+ .remainingAccounts(tokens.flatMap(({ symbolOrMint, mint, metadataAddress }) => [
146
+ {
147
+ pubkey: getAssociatedTokenAddressSync(mint, options.walletPublicKey),
148
+ isWritable: true,
149
+ isSigner: false,
150
+ },
151
+ {
152
+ pubkey: mint,
153
+ isWritable: false,
154
+ isSigner: false,
155
+ },
156
+ ...(symbolOrMint.type === SymbolOrMintType.Symbol
157
+ ? [
158
+ {
159
+ pubkey: metadataAddress,
160
+ isWritable: false,
161
+ isSigner: false,
162
+ },
163
+ ]
164
+ : []),
165
+ ]))
166
+ .instruction();
167
+ export var SessionResultType;
168
+ (function (SessionResultType) {
169
+ SessionResultType[SessionResultType["Success"] = 0] = "Success";
170
+ SessionResultType[SessionResultType["Failed"] = 1] = "Failed";
171
+ })(SessionResultType || (SessionResultType = {}));
172
+ const EstablishSessionResult = {
173
+ Success: (signature, session) => ({
174
+ type: SessionResultType.Success,
175
+ signature,
176
+ session,
177
+ }),
178
+ Failed: (signature, error) => ({
179
+ type: SessionResultType.Failed,
180
+ signature,
181
+ error,
182
+ }),
183
+ };
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1,7 @@
1
+ import type { Transaction, Rpc, SolanaRpcApi } from "@solana/kit";
2
+ import { Keypair } from "@solana/web3.js";
3
+ export declare const sponsorAndSend: (rpc: Rpc<SolanaRpcApi>, sponsor: CryptoKeyPair, transaction: Transaction) => Promise<import("@solana/kit").Signature>;
4
+ export declare const createPaymasterEndpoint: (options: {
5
+ rpc: string;
6
+ sponsor: Keypair;
7
+ }) => Promise<(req: Request) => Promise<Response>>;
@@ -0,0 +1,51 @@
1
+ import { fromLegacyKeypair } from "@solana/compat";
2
+ import { signTransaction, createSolanaRpc, getBase64EncodedWireTransaction, getTransactionDecoder, getBase64Encoder, getSignatureFromTransaction, } from "@solana/kit";
3
+ import { Keypair } from "@solana/web3.js";
4
+ import { z } from "zod";
5
+ export const sponsorAndSend = async (rpc, sponsor, transaction) => {
6
+ const signedTransaction = await signTransaction([sponsor], transaction);
7
+ await rpc
8
+ .sendTransaction(getBase64EncodedWireTransaction(signedTransaction), {
9
+ encoding: "base64",
10
+ skipPreflight: true,
11
+ })
12
+ .send();
13
+ return getSignatureFromTransaction(signedTransaction);
14
+ };
15
+ export const createPaymasterEndpoint = async (options) => {
16
+ const rpc = createSolanaRpc(options.rpc);
17
+ const sponsor = await fromLegacyKeypair(options.sponsor);
18
+ return async (req) => {
19
+ const data = postBodySchema.parse(await req.json());
20
+ try {
21
+ const transaction = getTransactionDecoder().decode(getBase64Encoder().encode(data.transaction));
22
+ try {
23
+ return new Response(await sponsorAndSend(rpc, sponsor, transaction));
24
+ }
25
+ catch (error) {
26
+ // eslint-disable-next-line no-console
27
+ console.error(error);
28
+ return new Response(`Failed to sponsor and send: ${serializeError(error)}`, { status: 500 });
29
+ }
30
+ }
31
+ catch (error) {
32
+ // eslint-disable-next-line no-console
33
+ console.error(error);
34
+ return new Response("Failed to deserialize transaction", { status: 400 });
35
+ }
36
+ };
37
+ };
38
+ const postBodySchema = z.strictObject({
39
+ transaction: z.string(),
40
+ });
41
+ const serializeError = (error) => {
42
+ if (error instanceof Error) {
43
+ return error.message;
44
+ }
45
+ else if (typeof error === "string") {
46
+ return error.toString();
47
+ }
48
+ else {
49
+ return "Unknown Error";
50
+ }
51
+ };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@fogo/sessions-sdk",
3
+ "version": "0.0.1",
4
+ "description": "A set of utilities for integrating with Fogo sessions",
5
+ "keywords": [
6
+ "fogo",
7
+ "sessions",
8
+ "crypto",
9
+ "wallet"
10
+ ],
11
+ "type": "module",
12
+ "main": "./cjs/index.js",
13
+ "types": "./cjs/index.d.ts",
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "exports": {
18
+ ".": {
19
+ "import": {
20
+ "types": "./esm/index.d.ts",
21
+ "default": "./esm/index.js"
22
+ },
23
+ "require": {
24
+ "types": "./cjs/index.d.ts",
25
+ "default": "./cjs/index.js"
26
+ }
27
+ },
28
+ "./paymaster": {
29
+ "import": {
30
+ "types": "./esm/paymaster.d.ts",
31
+ "default": "./esm/paymaster.js"
32
+ },
33
+ "require": {
34
+ "types": "./cjs/paymaster.d.ts",
35
+ "default": "./cjs/paymaster.js"
36
+ }
37
+ }
38
+ },
39
+ "dependencies": {
40
+ "@coral-xyz/anchor": "^0.31.1",
41
+ "@metaplex-foundation/mpl-token-metadata": "^3.4.0",
42
+ "@metaplex-foundation/umi": "^1.2.0",
43
+ "@metaplex-foundation/umi-bundle-defaults": "^1.2.0",
44
+ "@solana/compat": "^2.1.1",
45
+ "@solana/kit": "^2.1.1",
46
+ "@solana/spl-token": "^0.4.13",
47
+ "@solana/web3.js": "^1.92.3",
48
+ "bs58": "^6.0.0",
49
+ "zod": "^3.25.62",
50
+ "@fogo/sessions-idls": "0.0.1"
51
+ }
52
+ }