@sovereign-sdk/modules 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +14 -1
- package/dist/index.d.ts +14 -1
- package/dist/index.js +15 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +13 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -2
package/dist/index.d.mts
CHANGED
|
@@ -7,6 +7,19 @@ type TokenMetadata = {
|
|
|
7
7
|
supplyCap: bigint;
|
|
8
8
|
admins: string[];
|
|
9
9
|
};
|
|
10
|
+
/**
|
|
11
|
+
* Derives a token ID from the originator, token name, and decimals.
|
|
12
|
+
*
|
|
13
|
+
* Matches the Rust `get_token_id` implementation: SHA-256 hash of
|
|
14
|
+
* originator bytes + token name bytes + decimals byte, with the
|
|
15
|
+
* last byte of the hash replaced by the decimals value.
|
|
16
|
+
*
|
|
17
|
+
* @param originator - The raw bytes of the token originator (e.g. decoded address bytes)
|
|
18
|
+
* @param tokenName - The name of the token
|
|
19
|
+
* @param decimals - The number of decimal places for the token
|
|
20
|
+
* @returns The 32-byte token ID
|
|
21
|
+
*/
|
|
22
|
+
declare function getTokenId(originator: Uint8Array, tokenName: string, decimals: number): Uint8Array;
|
|
10
23
|
/**
|
|
11
24
|
* Bank class for interacting with the Sovereign SDK Bank module.
|
|
12
25
|
*/
|
|
@@ -77,4 +90,4 @@ declare class Bank {
|
|
|
77
90
|
private isMissingAccountError;
|
|
78
91
|
}
|
|
79
92
|
|
|
80
|
-
export { Bank, type TokenMetadata };
|
|
93
|
+
export { Bank, type TokenMetadata, getTokenId };
|
package/dist/index.d.ts
CHANGED
|
@@ -7,6 +7,19 @@ type TokenMetadata = {
|
|
|
7
7
|
supplyCap: bigint;
|
|
8
8
|
admins: string[];
|
|
9
9
|
};
|
|
10
|
+
/**
|
|
11
|
+
* Derives a token ID from the originator, token name, and decimals.
|
|
12
|
+
*
|
|
13
|
+
* Matches the Rust `get_token_id` implementation: SHA-256 hash of
|
|
14
|
+
* originator bytes + token name bytes + decimals byte, with the
|
|
15
|
+
* last byte of the hash replaced by the decimals value.
|
|
16
|
+
*
|
|
17
|
+
* @param originator - The raw bytes of the token originator (e.g. decoded address bytes)
|
|
18
|
+
* @param tokenName - The name of the token
|
|
19
|
+
* @param decimals - The number of decimal places for the token
|
|
20
|
+
* @returns The 32-byte token ID
|
|
21
|
+
*/
|
|
22
|
+
declare function getTokenId(originator: Uint8Array, tokenName: string, decimals: number): Uint8Array;
|
|
10
23
|
/**
|
|
11
24
|
* Bank class for interacting with the Sovereign SDK Bank module.
|
|
12
25
|
*/
|
|
@@ -77,4 +90,4 @@ declare class Bank {
|
|
|
77
90
|
private isMissingAccountError;
|
|
78
91
|
}
|
|
79
92
|
|
|
80
|
-
export { Bank, type TokenMetadata };
|
|
93
|
+
export { Bank, type TokenMetadata, getTokenId };
|
package/dist/index.js
CHANGED
|
@@ -20,17 +20,29 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/index.ts
|
|
21
21
|
var src_exports = {};
|
|
22
22
|
__export(src_exports, {
|
|
23
|
-
Bank: () => Bank
|
|
23
|
+
Bank: () => Bank,
|
|
24
|
+
getTokenId: () => getTokenId
|
|
24
25
|
});
|
|
25
26
|
module.exports = __toCommonJS(src_exports);
|
|
26
27
|
|
|
27
28
|
// src/bank.ts
|
|
29
|
+
var import_sha2 = require("@noble/hashes/sha2");
|
|
28
30
|
var import_bech32 = require("bech32");
|
|
29
31
|
function getHolderAddress(holder) {
|
|
30
32
|
if ("user" in holder) return holder.user;
|
|
31
33
|
if ("module" in holder) return holder.module;
|
|
32
34
|
return holder.derived;
|
|
33
35
|
}
|
|
36
|
+
function getTokenId(originator, tokenName, decimals) {
|
|
37
|
+
const nameBytes = new TextEncoder().encode(tokenName);
|
|
38
|
+
const buffer = new Uint8Array(originator.length + nameBytes.length + 1);
|
|
39
|
+
buffer.set(originator, 0);
|
|
40
|
+
buffer.set(nameBytes, originator.length);
|
|
41
|
+
buffer[originator.length + nameBytes.length] = decimals;
|
|
42
|
+
const hash = (0, import_sha2.sha256)(buffer);
|
|
43
|
+
hash[31] = decimals;
|
|
44
|
+
return hash;
|
|
45
|
+
}
|
|
34
46
|
var Bank = class {
|
|
35
47
|
/**
|
|
36
48
|
* Creates a new Bank instance.
|
|
@@ -140,6 +152,7 @@ var Bank = class {
|
|
|
140
152
|
};
|
|
141
153
|
// Annotate the CommonJS export names for ESM import in node:
|
|
142
154
|
0 && (module.exports = {
|
|
143
|
-
Bank
|
|
155
|
+
Bank,
|
|
156
|
+
getTokenId
|
|
144
157
|
});
|
|
145
158
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/bank.ts"],"sourcesContent":["export * from \"./bank\";\n","import { type Rollup, SovereignClient } from \"@sovereign-sdk/web3\";\nimport { bech32m } from \"bech32\";\nimport type { ErrorResponse } from \"./types\";\n\n// TokenHolder is an enum: { user: string } | { module: string } | { derived: string }\ntype TokenHolderPayload =\n | { user: string }\n | { module: string }\n | { derived: string };\n\ntype TokenStatePayload = {\n key: string;\n value: {\n name: string;\n total_supply: string;\n supply_cap: string;\n admins: TokenHolderPayload[];\n };\n};\n\nexport type TokenMetadata = {\n name: string;\n decimals: number;\n totalSupply: bigint;\n supplyCap: bigint;\n admins: string[];\n};\n\nfunction getHolderAddress(holder: TokenHolderPayload): string {\n if (\"user\" in holder) return holder.user;\n if (\"module\" in holder) return holder.module;\n return holder.derived;\n}\n\ntype GasTokenIdPayload = {\n token_id: string;\n};\n\ntype BalancePayload = {\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: BalancePayload = await this.rollup.http.get(\n `/modules/bank/tokens/${token}/balances/${address}`,\n );\n\n return BigInt(response.amount);\n } catch (err) {\n if (this.isMissingAccountError(err)) return BigInt(0);\n\n throw err;\n }\n }\n\n /**\n * Gets the metadata of a specific token.\n *\n * If no token ID is provided, returns the metadata of the gas token.\n *\n * @param tokenId - Optional token ID. If not provided, uses the gas token\n * @returns Promise resolving to the token metadata\n * @throws {SovereignClient.APIError} When the request fails\n * @example\n * ```typescript\n * const bank = new Bank(rollup);\n * const metadata = await bank.tokenMetadata();\n * console.log(`Token name: ${metadata.name}, decimals: ${metadata.decimals}`);\n *\n * // Query specific token metadata\n * const tokenMeta = await bank.tokenMetadata(\"token_123\");\n * ```\n */\n async tokenMetadata(tokenId?: string): Promise<TokenMetadata> {\n const token = await this.tokenIdOrElseGasTokenId(tokenId);\n const response: TokenStatePayload = await this.rollup.http.get(\n `/modules/bank/state/tokens/items/${token}`,\n );\n\n // Decimals are encoded in the last byte of the token ID (byte 31 of the 32-byte hash)\n const decoded = bech32m.decode(token);\n const bytes = bech32m.fromWords(decoded.words);\n const decimals = bytes[31];\n\n return {\n name: response.value.name,\n decimals,\n totalSupply: BigInt(response.value.total_supply),\n supplyCap: BigInt(response.value.supply_cap),\n admins: response.value.admins.map(getHolderAddress),\n };\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: GasTokenIdPayload = await this.rollup.http.get(\n \"/modules/bank/tokens/gas_token\",\n );\n this._gasTokenId = response.token_id;\n return this._gasTokenId;\n }\n\n private async tokenIdOrElseGasTokenId(tokenId?: string): Promise<string> {\n return tokenId ?? this.gasTokenId();\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: todo\n private isMissingAccountError(anyError: any): boolean {\n if (anyError?.status !== 404) return false;\n const body = anyError?.error as ErrorResponse;\n return (\n body?.message?.startsWith(\"Balance\") &&\n body?.message?.endsWith(\"not found\")\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/bank.ts"],"sourcesContent":["export * from \"./bank\";\n","import { sha256 } from \"@noble/hashes/sha2\";\nimport { type Rollup, SovereignClient } from \"@sovereign-sdk/web3\";\nimport { bech32m } from \"bech32\";\nimport type { ErrorResponse } from \"./types\";\n\n// TokenHolder is an enum: { user: string } | { module: string } | { derived: string }\ntype TokenHolderPayload =\n | { user: string }\n | { module: string }\n | { derived: string };\n\ntype TokenStatePayload = {\n key: string;\n value: {\n name: string;\n total_supply: string;\n supply_cap: string;\n admins: TokenHolderPayload[];\n };\n};\n\nexport type TokenMetadata = {\n name: string;\n decimals: number;\n totalSupply: bigint;\n supplyCap: bigint;\n admins: string[];\n};\n\nfunction getHolderAddress(holder: TokenHolderPayload): string {\n if (\"user\" in holder) return holder.user;\n if (\"module\" in holder) return holder.module;\n return holder.derived;\n}\n\ntype GasTokenIdPayload = {\n token_id: string;\n};\n\ntype BalancePayload = {\n amount: string;\n token_id: string;\n};\n\n/**\n * Derives a token ID from the originator, token name, and decimals.\n *\n * Matches the Rust `get_token_id` implementation: SHA-256 hash of\n * originator bytes + token name bytes + decimals byte, with the\n * last byte of the hash replaced by the decimals value.\n *\n * @param originator - The raw bytes of the token originator (e.g. decoded address bytes)\n * @param tokenName - The name of the token\n * @param decimals - The number of decimal places for the token\n * @returns The 32-byte token ID\n */\nexport function getTokenId(\n originator: Uint8Array,\n tokenName: string,\n decimals: number,\n): Uint8Array {\n const nameBytes = new TextEncoder().encode(tokenName);\n\n const buffer = new Uint8Array(originator.length + nameBytes.length + 1);\n buffer.set(originator, 0);\n buffer.set(nameBytes, originator.length);\n buffer[originator.length + nameBytes.length] = decimals;\n\n const hash = sha256(buffer);\n hash[31] = decimals;\n return hash;\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: BalancePayload = await this.rollup.http.get(\n `/modules/bank/tokens/${token}/balances/${address}`,\n );\n\n return BigInt(response.amount);\n } catch (err) {\n if (this.isMissingAccountError(err)) return BigInt(0);\n\n throw err;\n }\n }\n\n /**\n * Gets the metadata of a specific token.\n *\n * If no token ID is provided, returns the metadata of the gas token.\n *\n * @param tokenId - Optional token ID. If not provided, uses the gas token\n * @returns Promise resolving to the token metadata\n * @throws {SovereignClient.APIError} When the request fails\n * @example\n * ```typescript\n * const bank = new Bank(rollup);\n * const metadata = await bank.tokenMetadata();\n * console.log(`Token name: ${metadata.name}, decimals: ${metadata.decimals}`);\n *\n * // Query specific token metadata\n * const tokenMeta = await bank.tokenMetadata(\"token_123\");\n * ```\n */\n async tokenMetadata(tokenId?: string): Promise<TokenMetadata> {\n const token = await this.tokenIdOrElseGasTokenId(tokenId);\n const response: TokenStatePayload = await this.rollup.http.get(\n `/modules/bank/state/tokens/items/${token}`,\n );\n\n // Decimals are encoded in the last byte of the token ID (byte 31 of the 32-byte hash)\n const decoded = bech32m.decode(token);\n const bytes = bech32m.fromWords(decoded.words);\n const decimals = bytes[31];\n\n return {\n name: response.value.name,\n decimals,\n totalSupply: BigInt(response.value.total_supply),\n supplyCap: BigInt(response.value.supply_cap),\n admins: response.value.admins.map(getHolderAddress),\n };\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: GasTokenIdPayload = await this.rollup.http.get(\n \"/modules/bank/tokens/gas_token\",\n );\n this._gasTokenId = response.token_id;\n return this._gasTokenId;\n }\n\n private async tokenIdOrElseGasTokenId(tokenId?: string): Promise<string> {\n return tokenId ?? this.gasTokenId();\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: todo\n private isMissingAccountError(anyError: any): boolean {\n if (anyError?.status !== 404) return false;\n const body = anyError?.error as ErrorResponse;\n return (\n body?.message?.startsWith(\"Balance\") &&\n body?.message?.endsWith(\"not found\")\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAAuB;AAEvB,oBAAwB;AA2BxB,SAAS,iBAAiB,QAAoC;AAC5D,MAAI,UAAU,OAAQ,QAAO,OAAO;AACpC,MAAI,YAAY,OAAQ,QAAO,OAAO;AACtC,SAAO,OAAO;AAChB;AAuBO,SAAS,WACd,YACA,WACA,UACY;AACZ,QAAM,YAAY,IAAI,YAAY,EAAE,OAAO,SAAS;AAEpD,QAAM,SAAS,IAAI,WAAW,WAAW,SAAS,UAAU,SAAS,CAAC;AACtE,SAAO,IAAI,YAAY,CAAC;AACxB,SAAO,IAAI,WAAW,WAAW,MAAM;AACvC,SAAO,WAAW,SAAS,UAAU,MAAM,IAAI;AAE/C,QAAM,WAAO,oBAAO,MAAM;AAC1B,OAAK,EAAE,IAAI;AACX,SAAO;AACT;AAKO,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,EAqBA,MAAM,QAAQ,SAAiB,SAAmC;AAChE,UAAM,QAAQ,MAAM,KAAK,wBAAwB,OAAO;AAExD,QAAI;AACF,YAAM,WAA2B,MAAM,KAAK,OAAO,KAAK;AAAA,QACtD,wBAAwB,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SAAS,WAAW,SAAS,KACnC,MAAM,SAAS,SAAS,WAAW;AAAA,EAEvC;AACF;","names":[]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
// src/bank.ts
|
|
2
|
+
import { sha256 } from "@noble/hashes/sha2";
|
|
2
3
|
import { bech32m } from "bech32";
|
|
3
4
|
function getHolderAddress(holder) {
|
|
4
5
|
if ("user" in holder) return holder.user;
|
|
5
6
|
if ("module" in holder) return holder.module;
|
|
6
7
|
return holder.derived;
|
|
7
8
|
}
|
|
9
|
+
function getTokenId(originator, tokenName, decimals) {
|
|
10
|
+
const nameBytes = new TextEncoder().encode(tokenName);
|
|
11
|
+
const buffer = new Uint8Array(originator.length + nameBytes.length + 1);
|
|
12
|
+
buffer.set(originator, 0);
|
|
13
|
+
buffer.set(nameBytes, originator.length);
|
|
14
|
+
buffer[originator.length + nameBytes.length] = decimals;
|
|
15
|
+
const hash = sha256(buffer);
|
|
16
|
+
hash[31] = decimals;
|
|
17
|
+
return hash;
|
|
18
|
+
}
|
|
8
19
|
var Bank = class {
|
|
9
20
|
/**
|
|
10
21
|
* Creates a new Bank instance.
|
|
@@ -113,6 +124,7 @@ var Bank = class {
|
|
|
113
124
|
}
|
|
114
125
|
};
|
|
115
126
|
export {
|
|
116
|
-
Bank
|
|
127
|
+
Bank,
|
|
128
|
+
getTokenId
|
|
117
129
|
};
|
|
118
130
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bank.ts"],"sourcesContent":["import { type Rollup, SovereignClient } from \"@sovereign-sdk/web3\";\nimport { bech32m } from \"bech32\";\nimport type { ErrorResponse } from \"./types\";\n\n// TokenHolder is an enum: { user: string } | { module: string } | { derived: string }\ntype TokenHolderPayload =\n | { user: string }\n | { module: string }\n | { derived: string };\n\ntype TokenStatePayload = {\n key: string;\n value: {\n name: string;\n total_supply: string;\n supply_cap: string;\n admins: TokenHolderPayload[];\n };\n};\n\nexport type TokenMetadata = {\n name: string;\n decimals: number;\n totalSupply: bigint;\n supplyCap: bigint;\n admins: string[];\n};\n\nfunction getHolderAddress(holder: TokenHolderPayload): string {\n if (\"user\" in holder) return holder.user;\n if (\"module\" in holder) return holder.module;\n return holder.derived;\n}\n\ntype GasTokenIdPayload = {\n token_id: string;\n};\n\ntype BalancePayload = {\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: BalancePayload = await this.rollup.http.get(\n `/modules/bank/tokens/${token}/balances/${address}`,\n );\n\n return BigInt(response.amount);\n } catch (err) {\n if (this.isMissingAccountError(err)) return BigInt(0);\n\n throw err;\n }\n }\n\n /**\n * Gets the metadata of a specific token.\n *\n * If no token ID is provided, returns the metadata of the gas token.\n *\n * @param tokenId - Optional token ID. If not provided, uses the gas token\n * @returns Promise resolving to the token metadata\n * @throws {SovereignClient.APIError} When the request fails\n * @example\n * ```typescript\n * const bank = new Bank(rollup);\n * const metadata = await bank.tokenMetadata();\n * console.log(`Token name: ${metadata.name}, decimals: ${metadata.decimals}`);\n *\n * // Query specific token metadata\n * const tokenMeta = await bank.tokenMetadata(\"token_123\");\n * ```\n */\n async tokenMetadata(tokenId?: string): Promise<TokenMetadata> {\n const token = await this.tokenIdOrElseGasTokenId(tokenId);\n const response: TokenStatePayload = await this.rollup.http.get(\n `/modules/bank/state/tokens/items/${token}`,\n );\n\n // Decimals are encoded in the last byte of the token ID (byte 31 of the 32-byte hash)\n const decoded = bech32m.decode(token);\n const bytes = bech32m.fromWords(decoded.words);\n const decimals = bytes[31];\n\n return {\n name: response.value.name,\n decimals,\n totalSupply: BigInt(response.value.total_supply),\n supplyCap: BigInt(response.value.supply_cap),\n admins: response.value.admins.map(getHolderAddress),\n };\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: GasTokenIdPayload = await this.rollup.http.get(\n \"/modules/bank/tokens/gas_token\",\n );\n this._gasTokenId = response.token_id;\n return this._gasTokenId;\n }\n\n private async tokenIdOrElseGasTokenId(tokenId?: string): Promise<string> {\n return tokenId ?? this.gasTokenId();\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: todo\n private isMissingAccountError(anyError: any): boolean {\n if (anyError?.status !== 404) return false;\n const body = anyError?.error as ErrorResponse;\n return (\n body?.message?.startsWith(\"Balance\") &&\n body?.message?.endsWith(\"not found\")\n );\n }\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"sources":["../src/bank.ts"],"sourcesContent":["import { sha256 } from \"@noble/hashes/sha2\";\nimport { type Rollup, SovereignClient } from \"@sovereign-sdk/web3\";\nimport { bech32m } from \"bech32\";\nimport type { ErrorResponse } from \"./types\";\n\n// TokenHolder is an enum: { user: string } | { module: string } | { derived: string }\ntype TokenHolderPayload =\n | { user: string }\n | { module: string }\n | { derived: string };\n\ntype TokenStatePayload = {\n key: string;\n value: {\n name: string;\n total_supply: string;\n supply_cap: string;\n admins: TokenHolderPayload[];\n };\n};\n\nexport type TokenMetadata = {\n name: string;\n decimals: number;\n totalSupply: bigint;\n supplyCap: bigint;\n admins: string[];\n};\n\nfunction getHolderAddress(holder: TokenHolderPayload): string {\n if (\"user\" in holder) return holder.user;\n if (\"module\" in holder) return holder.module;\n return holder.derived;\n}\n\ntype GasTokenIdPayload = {\n token_id: string;\n};\n\ntype BalancePayload = {\n amount: string;\n token_id: string;\n};\n\n/**\n * Derives a token ID from the originator, token name, and decimals.\n *\n * Matches the Rust `get_token_id` implementation: SHA-256 hash of\n * originator bytes + token name bytes + decimals byte, with the\n * last byte of the hash replaced by the decimals value.\n *\n * @param originator - The raw bytes of the token originator (e.g. decoded address bytes)\n * @param tokenName - The name of the token\n * @param decimals - The number of decimal places for the token\n * @returns The 32-byte token ID\n */\nexport function getTokenId(\n originator: Uint8Array,\n tokenName: string,\n decimals: number,\n): Uint8Array {\n const nameBytes = new TextEncoder().encode(tokenName);\n\n const buffer = new Uint8Array(originator.length + nameBytes.length + 1);\n buffer.set(originator, 0);\n buffer.set(nameBytes, originator.length);\n buffer[originator.length + nameBytes.length] = decimals;\n\n const hash = sha256(buffer);\n hash[31] = decimals;\n return hash;\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: BalancePayload = await this.rollup.http.get(\n `/modules/bank/tokens/${token}/balances/${address}`,\n );\n\n return BigInt(response.amount);\n } catch (err) {\n if (this.isMissingAccountError(err)) return BigInt(0);\n\n throw err;\n }\n }\n\n /**\n * Gets the metadata of a specific token.\n *\n * If no token ID is provided, returns the metadata of the gas token.\n *\n * @param tokenId - Optional token ID. If not provided, uses the gas token\n * @returns Promise resolving to the token metadata\n * @throws {SovereignClient.APIError} When the request fails\n * @example\n * ```typescript\n * const bank = new Bank(rollup);\n * const metadata = await bank.tokenMetadata();\n * console.log(`Token name: ${metadata.name}, decimals: ${metadata.decimals}`);\n *\n * // Query specific token metadata\n * const tokenMeta = await bank.tokenMetadata(\"token_123\");\n * ```\n */\n async tokenMetadata(tokenId?: string): Promise<TokenMetadata> {\n const token = await this.tokenIdOrElseGasTokenId(tokenId);\n const response: TokenStatePayload = await this.rollup.http.get(\n `/modules/bank/state/tokens/items/${token}`,\n );\n\n // Decimals are encoded in the last byte of the token ID (byte 31 of the 32-byte hash)\n const decoded = bech32m.decode(token);\n const bytes = bech32m.fromWords(decoded.words);\n const decimals = bytes[31];\n\n return {\n name: response.value.name,\n decimals,\n totalSupply: BigInt(response.value.total_supply),\n supplyCap: BigInt(response.value.supply_cap),\n admins: response.value.admins.map(getHolderAddress),\n };\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: GasTokenIdPayload = await this.rollup.http.get(\n \"/modules/bank/tokens/gas_token\",\n );\n this._gasTokenId = response.token_id;\n return this._gasTokenId;\n }\n\n private async tokenIdOrElseGasTokenId(tokenId?: string): Promise<string> {\n return tokenId ?? this.gasTokenId();\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: todo\n private isMissingAccountError(anyError: any): boolean {\n if (anyError?.status !== 404) return false;\n const body = anyError?.error as ErrorResponse;\n return (\n body?.message?.startsWith(\"Balance\") &&\n body?.message?.endsWith(\"not found\")\n );\n }\n}\n"],"mappings":";AAAA,SAAS,cAAc;AAEvB,SAAS,eAAe;AA2BxB,SAAS,iBAAiB,QAAoC;AAC5D,MAAI,UAAU,OAAQ,QAAO,OAAO;AACpC,MAAI,YAAY,OAAQ,QAAO,OAAO;AACtC,SAAO,OAAO;AAChB;AAuBO,SAAS,WACd,YACA,WACA,UACY;AACZ,QAAM,YAAY,IAAI,YAAY,EAAE,OAAO,SAAS;AAEpD,QAAM,SAAS,IAAI,WAAW,WAAW,SAAS,UAAU,SAAS,CAAC;AACtE,SAAO,IAAI,YAAY,CAAC;AACxB,SAAO,IAAI,WAAW,WAAW,MAAM;AACvC,SAAO,WAAW,SAAS,UAAU,MAAM,IAAI;AAE/C,QAAM,OAAO,OAAO,MAAM;AAC1B,OAAK,EAAE,IAAI;AACX,SAAO;AACT;AAKO,IAAM,OAAN,MAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWhB,YAAY,QAA0B;AACpC,SAAK,SAAS;AAA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KAAK,OAAO,KAAK;AAAA,MACzD;AAAA,IACF;AACA,SAAK,cAAc,SAAS;AAC5B,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAc,wBAAwB,SAAmC;AACvE,WAAO,WAAW,KAAK,WAAW;AAAA,EACpC;AAAA;AAAA,EAGQ,sBAAsB,UAAwB;AACpD,QAAI,UAAU,WAAW,IAAK,QAAO;AACrC,UAAM,OAAO,UAAU;AACvB,WACE,MAAM,SAAS,WAAW,SAAS,KACnC,MAAM,SAAS,SAAS,WAAW;AAAA,EAEvC;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sovereign-sdk/modules",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "A package providing convenient helpers for interacting with core Sovereign SDK modules",
|
|
5
5
|
"repository": "github:Sovereign-Labs/sovereign-sdk",
|
|
6
6
|
"files": [
|
|
@@ -32,8 +32,9 @@
|
|
|
32
32
|
"access": "public"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
+
"@noble/hashes": "^1.5.0",
|
|
35
36
|
"bech32": "^2.0.0",
|
|
36
|
-
"@sovereign-sdk/web3": "^0.12.
|
|
37
|
+
"@sovereign-sdk/web3": "^0.12.6",
|
|
37
38
|
"@sovereign-sdk/utils": "^0.0.4"
|
|
38
39
|
},
|
|
39
40
|
"scripts": {
|