@d9-network/ink 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,7 +20,7 @@ import { usdt } from "@d9-network/spec"; // Contract descriptor
20
20
 
21
21
  // Create SDK instance
22
22
  const sdk = await createD9InkSdk({
23
- endpoint: "wss://mainnet.d9network.xyz:40300",
23
+ endpoint: "wss://mainnet.d9network.com:40300",
24
24
  });
25
25
 
26
26
  // Create contract instance
@@ -75,7 +75,7 @@ if (result.success) {
75
75
 
76
76
  For complete documentation, examples, and API reference, visit:
77
77
 
78
- - [D9 SDK Documentation](https://docs.d9network.xyz/docs/sdk/ink/overview)
78
+ - [D9 SDK Documentation](https://docs.d9network.com/docs/sdk/ink/overview)
79
79
 
80
80
  ## License
81
81
 
package/dist/index.cjs CHANGED
@@ -5,39 +5,9 @@ let _polkadot_labs_hdkd_helpers = require("@polkadot-labs/hdkd-helpers");
5
5
  let _subsquid_scale_codec = require("@subsquid/scale-codec");
6
6
  let _polkadot_api_substrate_bindings = require("@polkadot-api/substrate-bindings");
7
7
  let _noble_hashes_blake2_js = require("@noble/hashes/blake2.js");
8
+ let _d9_network_spec = require("@d9-network/spec");
8
9
  let rxjs = require("rxjs");
9
10
 
10
- //#region src/constants.ts
11
- /**
12
- * D9 Network constants
13
- */
14
- /**
15
- * D9 SS58 address prefix.
16
- *
17
- * SS58 is the address format used by Substrate-based chains. Each chain has a unique
18
- * prefix that determines the address format and ensures addresses are network-specific.
19
- *
20
- * D9 uses prefix 9, which produces addresses starting with 'c' or 'd'.
21
- *
22
- * This prefix is automatically applied to all AccountId encoding/decoding operations
23
- * in the SDK, including:
24
- * - Contract call parameter encoding
25
- * - Result decoding
26
- * - Event parsing
27
- *
28
- * @see https://github.com/paritytech/ss58-registry for the full SS58 registry
29
- */
30
- const D9_SS58_PREFIX = 9;
31
- /** D9 token decimals */
32
- const D9_DECIMALS = 12;
33
- /** D9 token symbol */
34
- const D9_SYMBOL = "D9";
35
- /** USDT token decimals */
36
- const USDT_DECIMALS = 2;
37
- /** USDT token symbol */
38
- const USDT_SYMBOL = "USDT";
39
-
40
- //#endregion
41
11
  //#region src/encode.ts
42
12
  /**
43
13
  * Encode a contract call for ContractsApi_call state_call.
@@ -299,7 +269,7 @@ function buildPrimitiveCodec$1(primitive) {
299
269
  * Build codec for special types based on path
300
270
  */
301
271
  function buildSpecialTypeCodec$1(path, typeEntry, types, cache) {
302
- if (path.join("::").includes("AccountId")) return (0, _polkadot_api_substrate_bindings.AccountId)(D9_SS58_PREFIX);
272
+ if (path.join("::").includes("AccountId")) return (0, _polkadot_api_substrate_bindings.AccountId)(_d9_network_spec.D9_SS58_PREFIX);
303
273
  if (path[0] === "Option") {
304
274
  const params = typeEntry.type.params;
305
275
  if (params && params.length > 0 && params[0]?.type !== void 0) return (0, _polkadot_api_substrate_bindings.Option)(buildCodecFromType(params[0].type, types, cache));
@@ -942,161 +912,35 @@ function createMessageBuilder(descriptor) {
942
912
  }
943
913
 
944
914
  //#endregion
945
- //#region src/errors.ts
946
- /**
947
- * Base error class for all contract-related errors
948
- */
949
- var ContractError = class ContractError extends Error {
950
- timestamp;
951
- cause;
952
- constructor(message, type, label, details, cause) {
953
- super(message, { cause });
954
- this.type = type;
955
- this.label = label;
956
- this.details = details;
957
- this.name = "ContractError";
958
- this.timestamp = /* @__PURE__ */ new Date();
959
- if (Error.captureStackTrace) Error.captureStackTrace(this, ContractError);
960
- }
961
- /**
962
- * Create a formatted error message for logging
963
- */
964
- toLogString() {
965
- const parts = [
966
- `[${this.type}]`,
967
- this.label ? `${this.label}:` : "",
968
- this.message
969
- ].filter(Boolean);
970
- if (this.details) parts.push(`Details: ${JSON.stringify(this.details)}`);
971
- return parts.join(" ");
972
- }
973
- /**
974
- * Convert to a plain object for serialization
975
- */
976
- toJSON() {
977
- return {
978
- name: this.name,
979
- type: this.type,
980
- message: this.message,
981
- label: this.label,
982
- details: this.details,
983
- timestamp: this.timestamp.toISOString(),
984
- stack: this.stack
985
- };
986
- }
987
- };
988
- /**
989
- * Error thrown when contract metadata is missing or invalid
990
- */
991
- var MetadataError = class extends ContractError {
992
- constructor(message, details) {
993
- super(message, "METADATA_ERROR", void 0, details);
994
- this.name = "MetadataError";
995
- }
996
- };
997
- /**
998
- * Error thrown when encoding call data fails
999
- */
1000
- var EncodeError = class extends ContractError {
1001
- constructor(label, message, details) {
1002
- super(message, "ENCODE_ERROR", label, details);
1003
- this.name = "EncodeError";
1004
- }
1005
- };
1006
- /**
1007
- * Error thrown when decoding response fails
1008
- */
1009
- var DecodeError = class extends ContractError {
1010
- constructor(label, message, details) {
1011
- super(message, "DECODE_ERROR", label, details);
1012
- this.name = "DecodeError";
1013
- }
1014
- };
1015
- /**
1016
- * Error thrown for network/RPC errors
1017
- */
1018
- var NetworkError = class extends ContractError {
1019
- constructor(message, cause, details) {
1020
- super(message, "NETWORK_ERROR", void 0, details, cause);
1021
- this.name = "NetworkError";
1022
- }
1023
- };
1024
- /**
1025
- * Error thrown when contract returns an error result
1026
- */
1027
- var ContractExecutionError = class extends ContractError {
1028
- constructor(label, errorValue) {
1029
- super(`Contract execution failed: ${JSON.stringify(errorValue)}`, "CONTRACT_ERROR", label, errorValue);
1030
- this.errorValue = errorValue;
1031
- this.name = "ContractExecutionError";
1032
- }
1033
- };
1034
- /**
1035
- * Error thrown for Ink LangError
1036
- */
1037
- var LangError = class extends ContractError {
1038
- constructor(label, variant) {
1039
- const variantName = variant === 1 ? "CouldNotReadInput" : `Unknown(${variant})`;
1040
- super(`Ink LangError: ${variantName}`, "LANG_ERROR", label, {
1041
- variant,
1042
- variantName
1043
- });
1044
- this.variant = variant;
1045
- this.name = "LangError";
1046
- }
1047
- };
1048
- /**
1049
- * Error thrown when request times out
1050
- */
1051
- var TimeoutError = class extends ContractError {
1052
- constructor(label, timeoutMs) {
1053
- super(`Request timed out after ${timeoutMs}ms`, "TIMEOUT_ERROR", label, { timeoutMs });
1054
- this.timeoutMs = timeoutMs;
1055
- this.name = "TimeoutError";
1056
- }
1057
- };
1058
- /**
1059
- * Error thrown when request is aborted
1060
- */
1061
- var AbortedError = class extends ContractError {
1062
- constructor(label, reason) {
1063
- super(reason || "Request was aborted", "ABORTED", label, { reason });
1064
- this.name = "AbortedError";
1065
- }
1066
- };
1067
- /**
1068
- * Error thrown for signer-related issues
1069
- */
1070
- var SignerError = class extends ContractError {
1071
- constructor(message, details) {
1072
- super(message, "SIGNER_ERROR", void 0, details);
1073
- this.name = "SignerError";
1074
- }
1075
- };
1076
- /**
1077
- * Error thrown when transaction submission fails
1078
- */
1079
- var TransactionError = class extends ContractError {
1080
- constructor(label, message, txHash, details) {
1081
- super(message, "TX_ERROR", label, {
1082
- ...details,
1083
- txHash
1084
- });
1085
- this.txHash = txHash;
1086
- this.name = "TransactionError";
1087
- }
1088
- };
1089
- /**
1090
- * Type guard to check if an error is a ContractError
1091
- */
1092
- function isContractError(error) {
1093
- return error instanceof ContractError;
1094
- }
915
+ //#region src/rpc.ts
1095
916
  /**
1096
- * Type guard to check for specific error types
917
+ * Create a type-safe RPC proxy from a PolkadotClient
918
+ *
919
+ * This wraps the client's `_request` method with a Proxy that provides
920
+ * a dot-syntax interface with proper TypeScript types.
921
+ *
922
+ * @param client - The PolkadotClient instance
923
+ * @returns A type-safe RPC proxy object
924
+ *
925
+ * @example
926
+ * ```ts
927
+ * const rpc = createTypedRpc(client);
928
+ *
929
+ * // Dot syntax with full type inference
930
+ * const hash = await rpc.chain_getBlockHash(12345);
931
+ * // hash: HexString | null
932
+ *
933
+ * const header = await rpc.chain_getHeader(hash);
934
+ * // header: BlockHeader | null
935
+ *
936
+ * const result = await rpc.state_call("ContractsApi_call", message, blockHash);
937
+ * // result: HexString
938
+ * ```
1097
939
  */
1098
- function isErrorType(error, type) {
1099
- return isContractError(error) && error.type === type;
940
+ function createTypedRpc(client) {
941
+ return new Proxy({}, { get(_target, prop) {
942
+ return (...args) => client._request(prop, args);
943
+ } });
1100
944
  }
1101
945
 
1102
946
  //#endregion
@@ -1124,7 +968,7 @@ function decodeWithPapiFallback(innerData, codec, method) {
1124
968
  };
1125
969
  return {
1126
970
  success: false,
1127
- error: new DecodeError(method, `Contract returned error: ${JSON.stringify(papiResult.value)}`, papiResult.value)
971
+ error: new _d9_network_spec.DecodeError(method, `Contract returned error: ${JSON.stringify(papiResult.value)}`, papiResult.value)
1128
972
  };
1129
973
  }
1130
974
  return {
@@ -1134,7 +978,7 @@ function decodeWithPapiFallback(innerData, codec, method) {
1134
978
  } catch (error) {
1135
979
  return {
1136
980
  success: false,
1137
- error: new DecodeError(method, `Failed to decode response: ${error instanceof Error ? error.message : String(error)}`, { error })
981
+ error: new _d9_network_spec.DecodeError(method, `Failed to decode response: ${error instanceof Error ? error.message : String(error)}`, { error })
1138
982
  };
1139
983
  }
1140
984
  }
@@ -1176,7 +1020,7 @@ function createTimeout(ms, label) {
1176
1020
  return {
1177
1021
  promise: new Promise((_, reject) => {
1178
1022
  timeoutId = setTimeout(() => {
1179
- reject(new TimeoutError(label, ms));
1023
+ reject(new _d9_network_spec.TimeoutError(label, ms));
1180
1024
  }, ms);
1181
1025
  }),
1182
1026
  clear: () => clearTimeout(timeoutId)
@@ -1186,14 +1030,14 @@ function createTimeout(ms, label) {
1186
1030
  * Check if AbortSignal is aborted and throw if so
1187
1031
  */
1188
1032
  function checkAborted(signal, label) {
1189
- if (signal?.aborted) throw new AbortedError(label, signal.reason);
1033
+ if (signal?.aborted) throw new _d9_network_spec.AbortedError(label, signal.reason);
1190
1034
  }
1191
1035
  /**
1192
1036
  * Create a D9 Ink Contract instance
1193
1037
  */
1194
1038
  function createD9InkContract(descriptor, address, options) {
1195
1039
  const { client, typedApi, defaultQueryOptions = {}, defaultSendOptions = {} } = options;
1196
- if (!descriptor.metadata) throw new MetadataError("Contract descriptor must include metadata");
1040
+ if (!descriptor.metadata) throw new _d9_network_spec.MetadataError("Contract descriptor must include metadata");
1197
1041
  const patchedMetadata = patchLangErrorInMetadata(descriptor.metadata);
1198
1042
  const builder = (0, _polkadot_api_ink_contracts.getInkDynamicBuilder)((0, _polkadot_api_ink_contracts.getInkLookup)(patchedMetadata));
1199
1043
  const patchedDescriptor = {
@@ -1208,6 +1052,7 @@ function createD9InkContract(descriptor, address, options) {
1208
1052
  codecRegistry = /* @__PURE__ */ new Map();
1209
1053
  }
1210
1054
  const addressBytes = ss58ToBytes(address);
1055
+ const rpc = createTypedRpc(client);
1211
1056
  const messageCodecCache = /* @__PURE__ */ new Map();
1212
1057
  function getMessageCodec(label) {
1213
1058
  const cached = messageCodecCache.get(label);
@@ -1238,11 +1083,7 @@ function createD9InkContract(descriptor, address, options) {
1238
1083
  const blockHash = at ?? (await client.getFinalizedBlock()).hash;
1239
1084
  checkAborted(signal, method);
1240
1085
  const executeCall = async () => {
1241
- return (0, polkadot_api_utils.fromHex)(await client._request("state_call", [
1242
- "ContractsApi_call",
1243
- message$1,
1244
- blockHash
1245
- ]));
1086
+ return (0, polkadot_api_utils.fromHex)(await rpc.state_call("ContractsApi_call", message$1, blockHash));
1246
1087
  };
1247
1088
  let rawResponse;
1248
1089
  if (timeout) {
@@ -1257,11 +1098,11 @@ function createD9InkContract(descriptor, address, options) {
1257
1098
  const callResult = decodeContractCallResult(rawResponse);
1258
1099
  if (!callResult.success) return {
1259
1100
  success: false,
1260
- error: new ContractError(`Contract execution failed: ${callResult.debugMessage}`, "CONTRACT_ERROR", method)
1101
+ error: new _d9_network_spec.ContractError(`Contract execution failed: ${callResult.debugMessage}`, "CONTRACT_ERROR", method)
1261
1102
  };
1262
1103
  if (isLangError(callResult.data)) return {
1263
1104
  success: false,
1264
- error: new LangError(method, callResult.data[1] ?? 1)
1105
+ error: new _d9_network_spec.LangError(method, callResult.data[1] ?? 1)
1265
1106
  };
1266
1107
  const innerData = unwrapInkResult(callResult.data);
1267
1108
  let decodedResponse;
@@ -1300,13 +1141,13 @@ function createD9InkContract(descriptor, address, options) {
1300
1141
  })
1301
1142
  };
1302
1143
  } catch (error) {
1303
- if (error instanceof ContractError) return {
1144
+ if (error instanceof _d9_network_spec.ContractError) return {
1304
1145
  success: false,
1305
1146
  error
1306
1147
  };
1307
1148
  return {
1308
1149
  success: false,
1309
- error: new ContractError(error instanceof Error ? error.message : String(error), "NETWORK_ERROR", method)
1150
+ error: new _d9_network_spec.ContractError(error instanceof Error ? error.message : String(error), "NETWORK_ERROR", method)
1310
1151
  };
1311
1152
  }
1312
1153
  }
@@ -1323,17 +1164,13 @@ function createD9InkContract(descriptor, address, options) {
1323
1164
  return {
1324
1165
  getEncodedData: () => callData,
1325
1166
  async signAndSubmit(signer) {
1326
- if (!typedApi) throw new TransactionError(method, "typedApi is required for transaction submission. Pass typedApi in SDK options.");
1167
+ if (!typedApi) throw new _d9_network_spec.TransactionError(method, "typedApi is required for transaction submission. Pass typedApi in SDK options.");
1327
1168
  try {
1328
1169
  let gas = gasLimit;
1329
1170
  if (!gas) {
1330
1171
  const message$1 = encodeContractCall(originBytes, addressBytes, callData, value);
1331
1172
  const blockHash = (await client.getFinalizedBlock()).hash;
1332
- gas = decodeContractCallResult((0, polkadot_api_utils.fromHex)(await client._request("state_call", [
1333
- "ContractsApi_call",
1334
- message$1,
1335
- blockHash
1336
- ]))).gas.gasRequired;
1173
+ gas = decodeContractCallResult((0, polkadot_api_utils.fromHex)(await rpc.state_call("ContractsApi_call", message$1, blockHash))).gas.gasRequired;
1337
1174
  }
1338
1175
  const txResult = await typedApi.tx.Contracts.call({
1339
1176
  dest: {
@@ -1393,14 +1230,14 @@ function createD9InkContract(descriptor, address, options) {
1393
1230
  notImplementedWarning("getRoot");
1394
1231
  return {
1395
1232
  success: false,
1396
- value: new ContractError("Storage queries not yet implemented. Use contract messages to read state.", "METADATA_ERROR")
1233
+ value: new _d9_network_spec.ContractError("Storage queries not yet implemented. Use contract messages to read state.", "METADATA_ERROR")
1397
1234
  };
1398
1235
  },
1399
1236
  async getNested(path, ..._keys) {
1400
1237
  notImplementedWarning("getNested");
1401
1238
  return {
1402
1239
  success: false,
1403
- value: new ContractError(`Storage query for "${path}" not yet implemented. Use contract messages to read state.`, "METADATA_ERROR")
1240
+ value: new _d9_network_spec.ContractError(`Storage query for "${path}" not yet implemented. Use contract messages to read state.`, "METADATA_ERROR")
1404
1241
  };
1405
1242
  }
1406
1243
  };
@@ -1451,37 +1288,6 @@ function createD9InkContract(descriptor, address, options) {
1451
1288
  };
1452
1289
  }
1453
1290
 
1454
- //#endregion
1455
- //#region src/rpc.ts
1456
- /**
1457
- * Create a type-safe RPC request function from a PolkadotClient
1458
- *
1459
- * This wraps the client's `_request` method with proper TypeScript types,
1460
- * providing autocomplete for known RPC methods and type inference for
1461
- * parameters and return values.
1462
- *
1463
- * @param client - The PolkadotClient instance
1464
- * @returns A type-safe RPC request function
1465
- *
1466
- * @example
1467
- * ```ts
1468
- * const rpc = createTypedRpc(client);
1469
- *
1470
- * // Autocomplete for method names, typed params and return
1471
- * const hash = await rpc("chain_getBlockHash", [12345]);
1472
- * // hash: HexString | null
1473
- *
1474
- * const header = await rpc("chain_getHeader", [hash]);
1475
- * // header: BlockHeader | null
1476
- *
1477
- * // Custom methods still work with explicit types
1478
- * const custom = await rpc<MyType>("my_custom_method", [arg]);
1479
- * ```
1480
- */
1481
- function createTypedRpc(client) {
1482
- return ((method, params) => client._request(method, params));
1483
- }
1484
-
1485
1291
  //#endregion
1486
1292
  //#region src/sdk.ts
1487
1293
  /**
@@ -1622,7 +1428,7 @@ function buildPrimitiveCodec(primitive) {
1622
1428
  }
1623
1429
  }
1624
1430
  function buildSpecialTypeCodec(path, typeEntry, types, cache) {
1625
- if (path.join("::").includes("AccountId")) return (0, _polkadot_api_substrate_bindings.AccountId)(D9_SS58_PREFIX);
1431
+ if (path.join("::").includes("AccountId")) return (0, _polkadot_api_substrate_bindings.AccountId)(_d9_network_spec.D9_SS58_PREFIX);
1626
1432
  if (path[0] === "Option") {
1627
1433
  const params = typeEntry.type.params;
1628
1434
  if (params && params.length > 0 && params[0]?.type !== void 0) return (0, _polkadot_api_substrate_bindings.Option)(buildCodecFromTypeInternal(params[0].type, types, cache));
@@ -2019,25 +1825,75 @@ function gasExceedsLimit(gas, limit) {
2019
1825
  }
2020
1826
 
2021
1827
  //#endregion
2022
- exports.AbortedError = AbortedError;
1828
+ Object.defineProperty(exports, 'AbortedError', {
1829
+ enumerable: true,
1830
+ get: function () {
1831
+ return _d9_network_spec.AbortedError;
1832
+ }
1833
+ });
2023
1834
  exports.ContractCallParser = ContractCallParser;
2024
- exports.ContractError = ContractError;
1835
+ Object.defineProperty(exports, 'ContractError', {
1836
+ enumerable: true,
1837
+ get: function () {
1838
+ return _d9_network_spec.ContractError;
1839
+ }
1840
+ });
2025
1841
  exports.ContractEventParser = ContractEventParser;
2026
- exports.ContractExecutionError = ContractExecutionError;
2027
- exports.D9_DECIMALS = D9_DECIMALS;
2028
- exports.D9_SS58_PREFIX = D9_SS58_PREFIX;
2029
- exports.D9_SYMBOL = D9_SYMBOL;
2030
- exports.DecodeError = DecodeError;
2031
- exports.EncodeError = EncodeError;
1842
+ Object.defineProperty(exports, 'ContractExecutionError', {
1843
+ enumerable: true,
1844
+ get: function () {
1845
+ return _d9_network_spec.ContractExecutionError;
1846
+ }
1847
+ });
1848
+ Object.defineProperty(exports, 'DecodeError', {
1849
+ enumerable: true,
1850
+ get: function () {
1851
+ return _d9_network_spec.DecodeError;
1852
+ }
1853
+ });
1854
+ Object.defineProperty(exports, 'EncodeError', {
1855
+ enumerable: true,
1856
+ get: function () {
1857
+ return _d9_network_spec.EncodeError;
1858
+ }
1859
+ });
2032
1860
  exports.InkCodecs = InkCodecs;
2033
- exports.LangError = LangError;
2034
- exports.MetadataError = MetadataError;
2035
- exports.NetworkError = NetworkError;
2036
- exports.SignerError = SignerError;
2037
- exports.TimeoutError = TimeoutError;
2038
- exports.TransactionError = TransactionError;
2039
- exports.USDT_DECIMALS = USDT_DECIMALS;
2040
- exports.USDT_SYMBOL = USDT_SYMBOL;
1861
+ Object.defineProperty(exports, 'LangError', {
1862
+ enumerable: true,
1863
+ get: function () {
1864
+ return _d9_network_spec.LangError;
1865
+ }
1866
+ });
1867
+ Object.defineProperty(exports, 'MetadataError', {
1868
+ enumerable: true,
1869
+ get: function () {
1870
+ return _d9_network_spec.MetadataError;
1871
+ }
1872
+ });
1873
+ Object.defineProperty(exports, 'NetworkError', {
1874
+ enumerable: true,
1875
+ get: function () {
1876
+ return _d9_network_spec.NetworkError;
1877
+ }
1878
+ });
1879
+ Object.defineProperty(exports, 'SignerError', {
1880
+ enumerable: true,
1881
+ get: function () {
1882
+ return _d9_network_spec.SignerError;
1883
+ }
1884
+ });
1885
+ Object.defineProperty(exports, 'TimeoutError', {
1886
+ enumerable: true,
1887
+ get: function () {
1888
+ return _d9_network_spec.TimeoutError;
1889
+ }
1890
+ });
1891
+ Object.defineProperty(exports, 'TransactionError', {
1892
+ enumerable: true,
1893
+ get: function () {
1894
+ return _d9_network_spec.TransactionError;
1895
+ }
1896
+ });
2041
1897
  exports.applyGasMargin = applyGasMargin;
2042
1898
  exports.buildAllEventDecoders = buildAllEventDecoders;
2043
1899
  exports.buildAllMessageDecoders = buildAllMessageDecoders;
@@ -2063,8 +1919,18 @@ exports.formatGasInfo = formatGasInfo;
2063
1919
  exports.gasExceedsLimit = gasExceedsLimit;
2064
1920
  exports.getEventSignature = getEventSignature;
2065
1921
  exports.isCallType = isCallType;
2066
- exports.isContractError = isContractError;
2067
- exports.isErrorType = isErrorType;
1922
+ Object.defineProperty(exports, 'isContractError', {
1923
+ enumerable: true,
1924
+ get: function () {
1925
+ return _d9_network_spec.isContractError;
1926
+ }
1927
+ });
1928
+ Object.defineProperty(exports, 'isErrorType', {
1929
+ enumerable: true,
1930
+ get: function () {
1931
+ return _d9_network_spec.isErrorType;
1932
+ }
1933
+ });
2068
1934
  exports.isEventType = isEventType;
2069
1935
  exports.isLangError = isLangError;
2070
1936
  exports.unwrapInkResult = unwrapInkResult;