@sovereign-sdk/modules 0.0.2

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,73 @@
1
+ import { Rollup } from '@sovereign-sdk/web3';
2
+
3
+ /**
4
+ * Bank class for interacting with the Sovereign SDK Bank module.
5
+ */
6
+ declare class Bank {
7
+ private readonly rollup;
8
+ private _gasTokenId?;
9
+ /**
10
+ * Creates a new Bank instance.
11
+ *
12
+ * @param rollup - The rollup instance to use for HTTP requests
13
+ */
14
+ constructor(rollup: Rollup<any, any>);
15
+ /**
16
+ * Gets the balance of a specific token for a given address.
17
+ *
18
+ * If no token ID is provided, the gas token balance will be returned.
19
+ *
20
+ * @param address - The address to query the balance for
21
+ * @param tokenId - Optional token ID. If not provided, uses the gas token
22
+ * @returns Promise resolving to the token balance as a bigint
23
+ * @throws {SovereignClient.APIError} When the request fails for reasons other than missing account
24
+ * @example
25
+ * ```typescript
26
+ * const bank = new Bank(rollup);
27
+ * const balance = await bank.balance("0x123...");
28
+ * console.log(`Balance: ${balance}`);
29
+ *
30
+ * // Query specific token balance
31
+ * const tokenBalance = await bank.balance("0x123...", "token_123");
32
+ * ```
33
+ */
34
+ balance(address: string, tokenId?: string): Promise<bigint>;
35
+ /**
36
+ * Gets the total supply of a specific token.
37
+ *
38
+ * If no token ID is provided, returns the total supply of the gas token.
39
+ *
40
+ * @param tokenId - Optional token ID. If not provided, uses the gas token
41
+ * @returns Promise resolving to the total supply as a bigint
42
+ * @throws {SovereignClient.APIError} When the request fails
43
+ * @example
44
+ * ```typescript
45
+ * const bank = new Bank(rollup);
46
+ * const totalSupply = await bank.totalSupply();
47
+ * console.log(`Total gas token supply: ${totalSupply}`);
48
+ *
49
+ * // Query specific token supply
50
+ * const tokenSupply = await bank.totalSupply("token_123");
51
+ * ```
52
+ */
53
+ totalSupply(tokenId?: string): Promise<bigint>;
54
+ /**
55
+ * Gets the gas token identifier.
56
+ *
57
+ * The gas token ID is cached after the first request to avoid repeated API calls.
58
+ *
59
+ * @returns Promise resolving to the gas token ID as a string
60
+ * @throws {Error} When the gas token ID cannot be retrieved
61
+ * @example
62
+ * ```typescript
63
+ * const bank = new Bank(rollup);
64
+ * const gasTokenId = await bank.gasTokenId();
65
+ * console.log(`Gas token ID: ${gasTokenId}`);
66
+ * ```
67
+ */
68
+ gasTokenId(): Promise<string>;
69
+ private tokenIdOrElseGasTokenId;
70
+ private isMissingAccountError;
71
+ }
72
+
73
+ export { Bank };
@@ -0,0 +1,73 @@
1
+ import { Rollup } from '@sovereign-sdk/web3';
2
+
3
+ /**
4
+ * Bank class for interacting with the Sovereign SDK Bank module.
5
+ */
6
+ declare class Bank {
7
+ private readonly rollup;
8
+ private _gasTokenId?;
9
+ /**
10
+ * Creates a new Bank instance.
11
+ *
12
+ * @param rollup - The rollup instance to use for HTTP requests
13
+ */
14
+ constructor(rollup: Rollup<any, any>);
15
+ /**
16
+ * Gets the balance of a specific token for a given address.
17
+ *
18
+ * If no token ID is provided, the gas token balance will be returned.
19
+ *
20
+ * @param address - The address to query the balance for
21
+ * @param tokenId - Optional token ID. If not provided, uses the gas token
22
+ * @returns Promise resolving to the token balance as a bigint
23
+ * @throws {SovereignClient.APIError} When the request fails for reasons other than missing account
24
+ * @example
25
+ * ```typescript
26
+ * const bank = new Bank(rollup);
27
+ * const balance = await bank.balance("0x123...");
28
+ * console.log(`Balance: ${balance}`);
29
+ *
30
+ * // Query specific token balance
31
+ * const tokenBalance = await bank.balance("0x123...", "token_123");
32
+ * ```
33
+ */
34
+ balance(address: string, tokenId?: string): Promise<bigint>;
35
+ /**
36
+ * Gets the total supply of a specific token.
37
+ *
38
+ * If no token ID is provided, returns the total supply of the gas token.
39
+ *
40
+ * @param tokenId - Optional token ID. If not provided, uses the gas token
41
+ * @returns Promise resolving to the total supply as a bigint
42
+ * @throws {SovereignClient.APIError} When the request fails
43
+ * @example
44
+ * ```typescript
45
+ * const bank = new Bank(rollup);
46
+ * const totalSupply = await bank.totalSupply();
47
+ * console.log(`Total gas token supply: ${totalSupply}`);
48
+ *
49
+ * // Query specific token supply
50
+ * const tokenSupply = await bank.totalSupply("token_123");
51
+ * ```
52
+ */
53
+ totalSupply(tokenId?: string): Promise<bigint>;
54
+ /**
55
+ * Gets the gas token identifier.
56
+ *
57
+ * The gas token ID is cached after the first request to avoid repeated API calls.
58
+ *
59
+ * @returns Promise resolving to the gas token ID as a string
60
+ * @throws {Error} When the gas token ID cannot be retrieved
61
+ * @example
62
+ * ```typescript
63
+ * const bank = new Bank(rollup);
64
+ * const gasTokenId = await bank.gasTokenId();
65
+ * console.log(`Gas token ID: ${gasTokenId}`);
66
+ * ```
67
+ */
68
+ gasTokenId(): Promise<string>;
69
+ private tokenIdOrElseGasTokenId;
70
+ private isMissingAccountError;
71
+ }
72
+
73
+ export { Bank };
package/dist/index.js ADDED
@@ -0,0 +1,173 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __async = (__this, __arguments, generator) => {
20
+ return new Promise((resolve, reject) => {
21
+ var fulfilled = (value) => {
22
+ try {
23
+ step(generator.next(value));
24
+ } catch (e) {
25
+ reject(e);
26
+ }
27
+ };
28
+ var rejected = (value) => {
29
+ try {
30
+ step(generator.throw(value));
31
+ } catch (e) {
32
+ reject(e);
33
+ }
34
+ };
35
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
36
+ step((generator = generator.apply(__this, __arguments)).next());
37
+ });
38
+ };
39
+
40
+ // src/index.ts
41
+ var src_exports = {};
42
+ __export(src_exports, {
43
+ Bank: () => Bank
44
+ });
45
+ module.exports = __toCommonJS(src_exports);
46
+
47
+ // src/bank.ts
48
+ var import_web3 = require("@sovereign-sdk/web3");
49
+
50
+ // src/types.ts
51
+ function isSuccessResponse(response) {
52
+ if (response.data === void 0)
53
+ throw new Error("data field missing from response");
54
+ }
55
+
56
+ // src/bank.ts
57
+ var Bank = class {
58
+ /**
59
+ * Creates a new Bank instance.
60
+ *
61
+ * @param rollup - The rollup instance to use for HTTP requests
62
+ */
63
+ // biome-ignore lint/suspicious/noExplicitAny: types arent used
64
+ constructor(rollup) {
65
+ this.rollup = rollup;
66
+ }
67
+ /**
68
+ * Gets the balance of a specific token for a given address.
69
+ *
70
+ * If no token ID is provided, the gas token balance will be returned.
71
+ *
72
+ * @param address - The address to query the balance for
73
+ * @param tokenId - Optional token ID. If not provided, uses the gas token
74
+ * @returns Promise resolving to the token balance as a bigint
75
+ * @throws {SovereignClient.APIError} When the request fails for reasons other than missing account
76
+ * @example
77
+ * ```typescript
78
+ * const bank = new Bank(rollup);
79
+ * const balance = await bank.balance("0x123...");
80
+ * console.log(`Balance: ${balance}`);
81
+ *
82
+ * // Query specific token balance
83
+ * const tokenBalance = await bank.balance("0x123...", "token_123");
84
+ * ```
85
+ */
86
+ balance(address, tokenId) {
87
+ return __async(this, null, function* () {
88
+ const token = yield this.tokenIdOrElseGasTokenId(tokenId);
89
+ try {
90
+ const response = yield this.rollup.http.get(
91
+ `/modules/bank/tokens/${token}/balances/${address}`
92
+ );
93
+ isSuccessResponse(response);
94
+ return BigInt(response.data.amount);
95
+ } catch (e) {
96
+ const err = e;
97
+ if (this.isMissingAccountError(err)) return BigInt(0);
98
+ throw e;
99
+ }
100
+ });
101
+ }
102
+ /**
103
+ * Gets the total supply of a specific token.
104
+ *
105
+ * If no token ID is provided, returns the total supply of the gas token.
106
+ *
107
+ * @param tokenId - Optional token ID. If not provided, uses the gas token
108
+ * @returns Promise resolving to the total supply as a bigint
109
+ * @throws {SovereignClient.APIError} When the request fails
110
+ * @example
111
+ * ```typescript
112
+ * const bank = new Bank(rollup);
113
+ * const totalSupply = await bank.totalSupply();
114
+ * console.log(`Total gas token supply: ${totalSupply}`);
115
+ *
116
+ * // Query specific token supply
117
+ * const tokenSupply = await bank.totalSupply("token_123");
118
+ * ```
119
+ */
120
+ totalSupply(tokenId) {
121
+ return __async(this, null, function* () {
122
+ const token = yield this.tokenIdOrElseGasTokenId(tokenId);
123
+ const response = yield this.rollup.http.get(
124
+ `/modules/bank/tokens/${token}/total-supply`
125
+ );
126
+ isSuccessResponse(response);
127
+ return BigInt(response.data.amount);
128
+ });
129
+ }
130
+ /**
131
+ * Gets the gas token identifier.
132
+ *
133
+ * The gas token ID is cached after the first request to avoid repeated API calls.
134
+ *
135
+ * @returns Promise resolving to the gas token ID as a string
136
+ * @throws {Error} When the gas token ID cannot be retrieved
137
+ * @example
138
+ * ```typescript
139
+ * const bank = new Bank(rollup);
140
+ * const gasTokenId = await bank.gasTokenId();
141
+ * console.log(`Gas token ID: ${gasTokenId}`);
142
+ * ```
143
+ */
144
+ gasTokenId() {
145
+ return __async(this, null, function* () {
146
+ if (this._gasTokenId) return this._gasTokenId;
147
+ const response = yield this.rollup.http.get(
148
+ "/modules/bank/tokens/gas_token"
149
+ );
150
+ isSuccessResponse(response);
151
+ this._gasTokenId = response.data.token_id;
152
+ return this._gasTokenId;
153
+ });
154
+ }
155
+ tokenIdOrElseGasTokenId(tokenId) {
156
+ return __async(this, null, function* () {
157
+ return tokenId != null ? tokenId : this.gasTokenId();
158
+ });
159
+ }
160
+ isMissingAccountError(anyError) {
161
+ if (!(anyError instanceof import_web3.SovereignClient.APIError)) return false;
162
+ if (anyError.status !== 404) return false;
163
+ const body = anyError.error;
164
+ const error = body.errors[0];
165
+ if (!error) return false;
166
+ return error.title.startsWith("Balance") && error.title.endsWith("not found");
167
+ }
168
+ };
169
+ // Annotate the CommonJS export names for ESM import in node:
170
+ 0 && (module.exports = {
171
+ Bank
172
+ });
173
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/bank.ts","../src/types.ts"],"sourcesContent":["export * from \"./bank\";\n","import { type Rollup, SovereignClient } from \"@sovereign-sdk/web3\";\nimport { type ErrorResponse, type Response, isSuccessResponse } from \"./types\";\n\ntype GasTokenIdPayload = {\n token_id: string;\n};\n\ntype BalancePayload = {\n amount: string;\n token_id: string;\n};\n\ntype TotalSupplyPayload = {\n amount: string;\n token_id: string;\n};\n\n/**\n * Bank class for interacting with the Sovereign SDK Bank module.\n */\nexport class Bank {\n // biome-ignore lint/suspicious/noExplicitAny: types arent used\n private readonly rollup: Rollup<any, any>;\n private _gasTokenId?: string;\n\n /**\n * Creates a new Bank instance.\n *\n * @param rollup - The rollup instance to use for HTTP requests\n */\n // biome-ignore lint/suspicious/noExplicitAny: types arent used\n constructor(rollup: Rollup<any, any>) {\n this.rollup = rollup;\n }\n\n /**\n * Gets the balance of a specific token for a given address.\n *\n * If no token ID is provided, the gas token balance will be returned.\n *\n * @param address - The address to query the balance for\n * @param tokenId - Optional token ID. If not provided, uses the gas token\n * @returns Promise resolving to the token balance as a bigint\n * @throws {SovereignClient.APIError} When the request fails for reasons other than missing account\n * @example\n * ```typescript\n * const bank = new Bank(rollup);\n * const balance = await bank.balance(\"0x123...\");\n * console.log(`Balance: ${balance}`);\n *\n * // Query specific token balance\n * const tokenBalance = await bank.balance(\"0x123...\", \"token_123\");\n * ```\n */\n async balance(address: string, tokenId?: string): Promise<bigint> {\n const token = await this.tokenIdOrElseGasTokenId(tokenId);\n\n try {\n const response: Response<BalancePayload> = await this.rollup.http.get(\n `/modules/bank/tokens/${token}/balances/${address}`,\n );\n\n isSuccessResponse(response);\n return BigInt(response.data.amount);\n } catch (e) {\n const err = e as SovereignClient.APIError;\n\n if (this.isMissingAccountError(err)) return BigInt(0);\n\n throw e;\n }\n }\n\n /**\n * Gets the total supply of a specific token.\n *\n * If no token ID is provided, returns the total supply of the gas token.\n *\n * @param tokenId - Optional token ID. If not provided, uses the gas token\n * @returns Promise resolving to the total supply as a bigint\n * @throws {SovereignClient.APIError} When the request fails\n * @example\n * ```typescript\n * const bank = new Bank(rollup);\n * const totalSupply = await bank.totalSupply();\n * console.log(`Total gas token supply: ${totalSupply}`);\n *\n * // Query specific token supply\n * const tokenSupply = await bank.totalSupply(\"token_123\");\n * ```\n */\n async totalSupply(tokenId?: string): Promise<bigint> {\n const token = await this.tokenIdOrElseGasTokenId(tokenId);\n const response: Response<TotalSupplyPayload> = await this.rollup.http.get(\n `/modules/bank/tokens/${token}/total-supply`,\n );\n isSuccessResponse(response);\n return BigInt(response.data.amount);\n }\n\n /**\n * Gets the gas token identifier.\n *\n * The gas token ID is cached after the first request to avoid repeated API calls.\n *\n * @returns Promise resolving to the gas token ID as a string\n * @throws {Error} When the gas token ID cannot be retrieved\n * @example\n * ```typescript\n * const bank = new Bank(rollup);\n * const gasTokenId = await bank.gasTokenId();\n * console.log(`Gas token ID: ${gasTokenId}`);\n * ```\n */\n async gasTokenId(): Promise<string> {\n if (this._gasTokenId) return this._gasTokenId;\n const response: Response<GasTokenIdPayload> = await this.rollup.http.get(\n \"/modules/bank/tokens/gas_token\",\n );\n isSuccessResponse(response);\n this._gasTokenId = response.data.token_id;\n return this._gasTokenId;\n }\n\n private async tokenIdOrElseGasTokenId(tokenId?: string): Promise<string> {\n return tokenId ?? this.gasTokenId();\n }\n\n private isMissingAccountError(anyError: unknown): boolean {\n if (!(anyError instanceof SovereignClient.APIError)) return false;\n if (anyError.status !== 404) return false;\n const body = anyError.error as ErrorResponse;\n const error = body.errors[0];\n if (!error) return false;\n return (\n error.title.startsWith(\"Balance\") && error.title.endsWith(\"not found\")\n );\n }\n}\n","export type SuccessResponse<T> = {\n data: T;\n};\n\nexport type ErrorResponse = {\n data: undefined;\n errors: {\n status: number;\n title: string;\n details: Record<string, unknown>;\n }[];\n};\n\nexport type Response<T> = SuccessResponse<T> | ErrorResponse;\n\nexport function isSuccessResponse<T>(\n response: Response<T>,\n): asserts response is SuccessResponse<T> {\n if (response.data === undefined)\n throw new Error(\"data field missing from response\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAA6C;;;ACetC,SAAS,kBACd,UACwC;AACxC,MAAI,SAAS,SAAS;AACpB,UAAM,IAAI,MAAM,kCAAkC;AACtD;;;ADAO,IAAM,OAAN,MAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWhB,YAAY,QAA0B;AACpC,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBM,QAAQ,SAAiB,SAAmC;AAAA;AAChE,YAAM,QAAQ,MAAM,KAAK,wBAAwB,OAAO;AAExD,UAAI;AACF,cAAM,WAAqC,MAAM,KAAK,OAAO,KAAK;AAAA,UAChE,wBAAwB,KAAK,aAAa,OAAO;AAAA,QACnD;AAEA,0BAAkB,QAAQ;AAC1B,eAAO,OAAO,SAAS,KAAK,MAAM;AAAA,MACpC,SAAS,GAAG;AACV,cAAM,MAAM;AAEZ,YAAI,KAAK,sBAAsB,GAAG,EAAG,QAAO,OAAO,CAAC;AAEpD,cAAM;AAAA,MACR;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoBM,YAAY,SAAmC;AAAA;AACnD,YAAM,QAAQ,MAAM,KAAK,wBAAwB,OAAO;AACxD,YAAM,WAAyC,MAAM,KAAK,OAAO,KAAK;AAAA,QACpE,wBAAwB,KAAK;AAAA,MAC/B;AACA,wBAAkB,QAAQ;AAC1B,aAAO,OAAO,SAAS,KAAK,MAAM;AAAA,IACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBM,aAA8B;AAAA;AAClC,UAAI,KAAK,YAAa,QAAO,KAAK;AAClC,YAAM,WAAwC,MAAM,KAAK,OAAO,KAAK;AAAA,QACnE;AAAA,MACF;AACA,wBAAkB,QAAQ;AAC1B,WAAK,cAAc,SAAS,KAAK;AACjC,aAAO,KAAK;AAAA,IACd;AAAA;AAAA,EAEc,wBAAwB,SAAmC;AAAA;AACvE,aAAO,4BAAW,KAAK,WAAW;AAAA,IACpC;AAAA;AAAA,EAEQ,sBAAsB,UAA4B;AACxD,QAAI,EAAE,oBAAoB,4BAAgB,UAAW,QAAO;AAC5D,QAAI,SAAS,WAAW,IAAK,QAAO;AACpC,UAAM,OAAO,SAAS;AACtB,UAAM,QAAQ,KAAK,OAAO,CAAC;AAC3B,QAAI,CAAC,MAAO,QAAO;AACnB,WACE,MAAM,MAAM,WAAW,SAAS,KAAK,MAAM,MAAM,SAAS,WAAW;AAAA,EAEzE;AACF;","names":[]}
package/dist/index.mjs ADDED
@@ -0,0 +1,147 @@
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
8
+ }
9
+ };
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
15
+ }
16
+ };
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
19
+ });
20
+ };
21
+
22
+ // src/bank.ts
23
+ import { SovereignClient } from "@sovereign-sdk/web3";
24
+
25
+ // src/types.ts
26
+ function isSuccessResponse(response) {
27
+ if (response.data === void 0)
28
+ throw new Error("data field missing from response");
29
+ }
30
+
31
+ // src/bank.ts
32
+ var Bank = class {
33
+ /**
34
+ * Creates a new Bank instance.
35
+ *
36
+ * @param rollup - The rollup instance to use for HTTP requests
37
+ */
38
+ // biome-ignore lint/suspicious/noExplicitAny: types arent used
39
+ constructor(rollup) {
40
+ this.rollup = rollup;
41
+ }
42
+ /**
43
+ * Gets the balance of a specific token for a given address.
44
+ *
45
+ * If no token ID is provided, the gas token balance will be returned.
46
+ *
47
+ * @param address - The address to query the balance for
48
+ * @param tokenId - Optional token ID. If not provided, uses the gas token
49
+ * @returns Promise resolving to the token balance as a bigint
50
+ * @throws {SovereignClient.APIError} When the request fails for reasons other than missing account
51
+ * @example
52
+ * ```typescript
53
+ * const bank = new Bank(rollup);
54
+ * const balance = await bank.balance("0x123...");
55
+ * console.log(`Balance: ${balance}`);
56
+ *
57
+ * // Query specific token balance
58
+ * const tokenBalance = await bank.balance("0x123...", "token_123");
59
+ * ```
60
+ */
61
+ balance(address, tokenId) {
62
+ return __async(this, null, function* () {
63
+ const token = yield this.tokenIdOrElseGasTokenId(tokenId);
64
+ try {
65
+ const response = yield this.rollup.http.get(
66
+ `/modules/bank/tokens/${token}/balances/${address}`
67
+ );
68
+ isSuccessResponse(response);
69
+ return BigInt(response.data.amount);
70
+ } catch (e) {
71
+ const err = e;
72
+ if (this.isMissingAccountError(err)) return BigInt(0);
73
+ throw e;
74
+ }
75
+ });
76
+ }
77
+ /**
78
+ * Gets the total supply of a specific token.
79
+ *
80
+ * If no token ID is provided, returns the total supply of the gas token.
81
+ *
82
+ * @param tokenId - Optional token ID. If not provided, uses the gas token
83
+ * @returns Promise resolving to the total supply as a bigint
84
+ * @throws {SovereignClient.APIError} When the request fails
85
+ * @example
86
+ * ```typescript
87
+ * const bank = new Bank(rollup);
88
+ * const totalSupply = await bank.totalSupply();
89
+ * console.log(`Total gas token supply: ${totalSupply}`);
90
+ *
91
+ * // Query specific token supply
92
+ * const tokenSupply = await bank.totalSupply("token_123");
93
+ * ```
94
+ */
95
+ totalSupply(tokenId) {
96
+ return __async(this, null, function* () {
97
+ const token = yield this.tokenIdOrElseGasTokenId(tokenId);
98
+ const response = yield this.rollup.http.get(
99
+ `/modules/bank/tokens/${token}/total-supply`
100
+ );
101
+ isSuccessResponse(response);
102
+ return BigInt(response.data.amount);
103
+ });
104
+ }
105
+ /**
106
+ * Gets the gas token identifier.
107
+ *
108
+ * The gas token ID is cached after the first request to avoid repeated API calls.
109
+ *
110
+ * @returns Promise resolving to the gas token ID as a string
111
+ * @throws {Error} When the gas token ID cannot be retrieved
112
+ * @example
113
+ * ```typescript
114
+ * const bank = new Bank(rollup);
115
+ * const gasTokenId = await bank.gasTokenId();
116
+ * console.log(`Gas token ID: ${gasTokenId}`);
117
+ * ```
118
+ */
119
+ gasTokenId() {
120
+ return __async(this, null, function* () {
121
+ if (this._gasTokenId) return this._gasTokenId;
122
+ const response = yield this.rollup.http.get(
123
+ "/modules/bank/tokens/gas_token"
124
+ );
125
+ isSuccessResponse(response);
126
+ this._gasTokenId = response.data.token_id;
127
+ return this._gasTokenId;
128
+ });
129
+ }
130
+ tokenIdOrElseGasTokenId(tokenId) {
131
+ return __async(this, null, function* () {
132
+ return tokenId != null ? tokenId : this.gasTokenId();
133
+ });
134
+ }
135
+ isMissingAccountError(anyError) {
136
+ if (!(anyError instanceof SovereignClient.APIError)) return false;
137
+ if (anyError.status !== 404) return false;
138
+ const body = anyError.error;
139
+ const error = body.errors[0];
140
+ if (!error) return false;
141
+ return error.title.startsWith("Balance") && error.title.endsWith("not found");
142
+ }
143
+ };
144
+ export {
145
+ Bank
146
+ };
147
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/bank.ts","../src/types.ts"],"sourcesContent":["import { type Rollup, SovereignClient } from \"@sovereign-sdk/web3\";\nimport { type ErrorResponse, type Response, isSuccessResponse } from \"./types\";\n\ntype GasTokenIdPayload = {\n token_id: string;\n};\n\ntype BalancePayload = {\n amount: string;\n token_id: string;\n};\n\ntype TotalSupplyPayload = {\n amount: string;\n token_id: string;\n};\n\n/**\n * Bank class for interacting with the Sovereign SDK Bank module.\n */\nexport class Bank {\n // biome-ignore lint/suspicious/noExplicitAny: types arent used\n private readonly rollup: Rollup<any, any>;\n private _gasTokenId?: string;\n\n /**\n * Creates a new Bank instance.\n *\n * @param rollup - The rollup instance to use for HTTP requests\n */\n // biome-ignore lint/suspicious/noExplicitAny: types arent used\n constructor(rollup: Rollup<any, any>) {\n this.rollup = rollup;\n }\n\n /**\n * Gets the balance of a specific token for a given address.\n *\n * If no token ID is provided, the gas token balance will be returned.\n *\n * @param address - The address to query the balance for\n * @param tokenId - Optional token ID. If not provided, uses the gas token\n * @returns Promise resolving to the token balance as a bigint\n * @throws {SovereignClient.APIError} When the request fails for reasons other than missing account\n * @example\n * ```typescript\n * const bank = new Bank(rollup);\n * const balance = await bank.balance(\"0x123...\");\n * console.log(`Balance: ${balance}`);\n *\n * // Query specific token balance\n * const tokenBalance = await bank.balance(\"0x123...\", \"token_123\");\n * ```\n */\n async balance(address: string, tokenId?: string): Promise<bigint> {\n const token = await this.tokenIdOrElseGasTokenId(tokenId);\n\n try {\n const response: Response<BalancePayload> = await this.rollup.http.get(\n `/modules/bank/tokens/${token}/balances/${address}`,\n );\n\n isSuccessResponse(response);\n return BigInt(response.data.amount);\n } catch (e) {\n const err = e as SovereignClient.APIError;\n\n if (this.isMissingAccountError(err)) return BigInt(0);\n\n throw e;\n }\n }\n\n /**\n * Gets the total supply of a specific token.\n *\n * If no token ID is provided, returns the total supply of the gas token.\n *\n * @param tokenId - Optional token ID. If not provided, uses the gas token\n * @returns Promise resolving to the total supply as a bigint\n * @throws {SovereignClient.APIError} When the request fails\n * @example\n * ```typescript\n * const bank = new Bank(rollup);\n * const totalSupply = await bank.totalSupply();\n * console.log(`Total gas token supply: ${totalSupply}`);\n *\n * // Query specific token supply\n * const tokenSupply = await bank.totalSupply(\"token_123\");\n * ```\n */\n async totalSupply(tokenId?: string): Promise<bigint> {\n const token = await this.tokenIdOrElseGasTokenId(tokenId);\n const response: Response<TotalSupplyPayload> = await this.rollup.http.get(\n `/modules/bank/tokens/${token}/total-supply`,\n );\n isSuccessResponse(response);\n return BigInt(response.data.amount);\n }\n\n /**\n * Gets the gas token identifier.\n *\n * The gas token ID is cached after the first request to avoid repeated API calls.\n *\n * @returns Promise resolving to the gas token ID as a string\n * @throws {Error} When the gas token ID cannot be retrieved\n * @example\n * ```typescript\n * const bank = new Bank(rollup);\n * const gasTokenId = await bank.gasTokenId();\n * console.log(`Gas token ID: ${gasTokenId}`);\n * ```\n */\n async gasTokenId(): Promise<string> {\n if (this._gasTokenId) return this._gasTokenId;\n const response: Response<GasTokenIdPayload> = await this.rollup.http.get(\n \"/modules/bank/tokens/gas_token\",\n );\n isSuccessResponse(response);\n this._gasTokenId = response.data.token_id;\n return this._gasTokenId;\n }\n\n private async tokenIdOrElseGasTokenId(tokenId?: string): Promise<string> {\n return tokenId ?? this.gasTokenId();\n }\n\n private isMissingAccountError(anyError: unknown): boolean {\n if (!(anyError instanceof SovereignClient.APIError)) return false;\n if (anyError.status !== 404) return false;\n const body = anyError.error as ErrorResponse;\n const error = body.errors[0];\n if (!error) return false;\n return (\n error.title.startsWith(\"Balance\") && error.title.endsWith(\"not found\")\n );\n }\n}\n","export type SuccessResponse<T> = {\n data: T;\n};\n\nexport type ErrorResponse = {\n data: undefined;\n errors: {\n status: number;\n title: string;\n details: Record<string, unknown>;\n }[];\n};\n\nexport type Response<T> = SuccessResponse<T> | ErrorResponse;\n\nexport function isSuccessResponse<T>(\n response: Response<T>,\n): asserts response is SuccessResponse<T> {\n if (response.data === undefined)\n throw new Error(\"data field missing from response\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAsB,uBAAuB;;;ACetC,SAAS,kBACd,UACwC;AACxC,MAAI,SAAS,SAAS;AACpB,UAAM,IAAI,MAAM,kCAAkC;AACtD;;;ADAO,IAAM,OAAN,MAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWhB,YAAY,QAA0B;AACpC,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBM,QAAQ,SAAiB,SAAmC;AAAA;AAChE,YAAM,QAAQ,MAAM,KAAK,wBAAwB,OAAO;AAExD,UAAI;AACF,cAAM,WAAqC,MAAM,KAAK,OAAO,KAAK;AAAA,UAChE,wBAAwB,KAAK,aAAa,OAAO;AAAA,QACnD;AAEA,0BAAkB,QAAQ;AAC1B,eAAO,OAAO,SAAS,KAAK,MAAM;AAAA,MACpC,SAAS,GAAG;AACV,cAAM,MAAM;AAEZ,YAAI,KAAK,sBAAsB,GAAG,EAAG,QAAO,OAAO,CAAC;AAEpD,cAAM;AAAA,MACR;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoBM,YAAY,SAAmC;AAAA;AACnD,YAAM,QAAQ,MAAM,KAAK,wBAAwB,OAAO;AACxD,YAAM,WAAyC,MAAM,KAAK,OAAO,KAAK;AAAA,QACpE,wBAAwB,KAAK;AAAA,MAC/B;AACA,wBAAkB,QAAQ;AAC1B,aAAO,OAAO,SAAS,KAAK,MAAM;AAAA,IACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBM,aAA8B;AAAA;AAClC,UAAI,KAAK,YAAa,QAAO,KAAK;AAClC,YAAM,WAAwC,MAAM,KAAK,OAAO,KAAK;AAAA,QACnE;AAAA,MACF;AACA,wBAAkB,QAAQ;AAC1B,WAAK,cAAc,SAAS,KAAK;AACjC,aAAO,KAAK;AAAA,IACd;AAAA;AAAA,EAEc,wBAAwB,SAAmC;AAAA;AACvE,aAAO,4BAAW,KAAK,WAAW;AAAA,IACpC;AAAA;AAAA,EAEQ,sBAAsB,UAA4B;AACxD,QAAI,EAAE,oBAAoB,gBAAgB,UAAW,QAAO;AAC5D,QAAI,SAAS,WAAW,IAAK,QAAO;AACpC,UAAM,OAAO,SAAS;AACtB,UAAM,QAAQ,KAAK,OAAO,CAAC;AAC3B,QAAI,CAAC,MAAO,QAAO;AACnB,WACE,MAAM,MAAM,WAAW,SAAS,KAAK,MAAM,MAAM,SAAS,WAAW;AAAA,EAEzE;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@sovereign-sdk/modules",
3
+ "version": "0.0.2",
4
+ "description": "A package providing convenient helpers for interacting with core Sovereign SDK modules",
5
+ "repository": "github:Sovereign-Labs/sovereign-sdk-web3-js",
6
+ "files": [
7
+ "dist",
8
+ "README.md",
9
+ "package.json"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "require": "./dist/index.js",
15
+ "import": "./dist/index.mjs"
16
+ }
17
+ },
18
+ "main": "./dist/index.js",
19
+ "module": "./dist/index.mjs",
20
+ "types": "./dist/index.d.ts",
21
+ "devDependencies": {
22
+ "tsup": "^8.3.0",
23
+ "typescript": "^5.6.3",
24
+ "vitest": "^3.0.5"
25
+ },
26
+ "peerDependencies": {
27
+ "tsup": "^8.3.0",
28
+ "typescript": "^5.6.3"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "dependencies": {
34
+ "@sovereign-sdk/web3": "^0.4.1",
35
+ "@sovereign-sdk/utils": "^0.0.3"
36
+ },
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "ci": "biome ci",
40
+ "fix": "biome check --write",
41
+ "lint": "biome lint",
42
+ "test": "vitest"
43
+ }
44
+ }