starknet 5.7.0 → 5.8.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.
@@ -637,6 +637,7 @@ var starknet = (() => {
637
637
  encode: () => encode_exports,
638
638
  fixProto: () => fixProto,
639
639
  fixStack: () => fixStack,
640
+ getCalldata: () => getCalldata,
640
641
  getChecksumAddress: () => getChecksumAddress,
641
642
  hash: () => hash_exports,
642
643
  isUrl: () => isUrl,
@@ -645,6 +646,7 @@ var starknet = (() => {
645
646
  num: () => num_exports,
646
647
  number: () => number2,
647
648
  shortString: () => shortString_exports,
649
+ splitArgsAndOptions: () => splitArgsAndOptions,
648
650
  stark: () => stark_exports,
649
651
  starknetId: () => starknetId_exports,
650
652
  transaction: () => transaction_exports,
@@ -5560,6 +5562,9 @@ var starknet = (() => {
5560
5562
  if (typeof it === "string" && isStringWholeNumber(it)) {
5561
5563
  return it;
5562
5564
  }
5565
+ if (typeof it === "boolean") {
5566
+ return `${+it}`;
5567
+ }
5563
5568
  throw new Error(`${it} can't be computed by felt()`);
5564
5569
  }
5565
5570
 
@@ -6490,7 +6495,6 @@ var starknet = (() => {
6490
6495
  // src/utils/stark.ts
6491
6496
  var stark_exports = {};
6492
6497
  __export(stark_exports, {
6493
- compileCalldata: () => compileCalldata,
6494
6498
  compressProgram: () => compressProgram,
6495
6499
  estimatedFeeToMaxFee: () => estimatedFeeToMaxFee,
6496
6500
  formatSignature: () => formatSignature,
@@ -10606,21 +10610,6 @@ var starknet = (() => {
10606
10610
  function signatureToHexArray(sig) {
10607
10611
  return bigNumberishArrayToHexadecimalStringArray(formatSignature(sig));
10608
10612
  }
10609
- function compileCalldata(args) {
10610
- const compiledData = Object.values(args).flatMap((value) => {
10611
- if (Array.isArray(value))
10612
- return [toBigInt(value.length).toString(), ...value.map((x) => toBigInt(x).toString())];
10613
- if (typeof value === "object" && "type" in value)
10614
- return Object.entries(value).filter(([k]) => k !== "type").map(([, v]) => toBigInt(v).toString());
10615
- return toBigInt(value).toString();
10616
- });
10617
- Object.defineProperty(compiledData, "compiled", {
10618
- enumerable: false,
10619
- writable: false,
10620
- value: true
10621
- });
10622
- return compiledData;
10623
- }
10624
10613
  function estimatedFeeToMaxFee(estimatedFee, overhead = 0.5) {
10625
10614
  const overHeadPercent = Math.round((1 + overhead) * 100);
10626
10615
  return toBigInt(estimatedFee) * toBigInt(overHeadPercent) / 100n;
@@ -10734,1055 +10723,964 @@ var starknet = (() => {
10734
10723
  }
10735
10724
  };
10736
10725
 
10737
- // src/utils/starknetId.ts
10738
- var starknetId_exports = {};
10739
- __export(starknetId_exports, {
10740
- StarknetIdContract: () => StarknetIdContract,
10741
- getStarknetIdContract: () => getStarknetIdContract,
10742
- useDecoded: () => useDecoded,
10743
- useEncoded: () => useEncoded
10744
- });
10745
- var basicAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789-";
10746
- var basicSizePlusOne = BigInt(basicAlphabet.length + 1);
10747
- var bigAlphabet = "\u8FD9\u6765";
10748
- var basicAlphabetSize = BigInt(basicAlphabet.length);
10749
- var bigAlphabetSize = BigInt(bigAlphabet.length);
10750
- var bigAlphabetSizePlusOne = BigInt(bigAlphabet.length + 1);
10751
- function extractStars(str) {
10752
- let k = 0;
10753
- while (str.endsWith(bigAlphabet[bigAlphabet.length - 1])) {
10754
- str = str.substring(0, str.length - 1);
10755
- k += 1;
10726
+ // src/utils/calldata/formatter.ts
10727
+ var guard = {
10728
+ isBN: (data, type, key) => {
10729
+ if (!isBigInt(data[key]))
10730
+ throw new Error(
10731
+ `Data and formatter mismatch on ${key}:${type[key]}, expected response data ${key}:${data[key]} to be BN instead it is ${typeof data[key]}`
10732
+ );
10733
+ },
10734
+ unknown: (data, type, key) => {
10735
+ throw new Error(`Unhandled formatter type on ${key}:${type[key]} for data ${key}:${data[key]}`);
10756
10736
  }
10757
- return [str, k];
10758
- }
10759
- function useDecoded(encoded) {
10760
- let decoded = "";
10761
- encoded.forEach((subdomain) => {
10762
- while (subdomain !== ZERO) {
10763
- const code = subdomain % basicSizePlusOne;
10764
- subdomain /= basicSizePlusOne;
10765
- if (code === BigInt(basicAlphabet.length)) {
10766
- const nextSubdomain = subdomain / bigAlphabetSizePlusOne;
10767
- if (nextSubdomain === ZERO) {
10768
- const code2 = subdomain % bigAlphabetSizePlusOne;
10769
- subdomain = nextSubdomain;
10770
- if (code2 === ZERO)
10771
- decoded += basicAlphabet[0];
10772
- else
10773
- decoded += bigAlphabet[Number(code2) - 1];
10774
- } else {
10775
- const code2 = subdomain % bigAlphabetSize;
10776
- decoded += bigAlphabet[Number(code2)];
10777
- subdomain /= bigAlphabetSize;
10778
- }
10779
- } else
10780
- decoded += basicAlphabet[Number(code)];
10737
+ };
10738
+ function formatter(data, type, sameType) {
10739
+ return Object.entries(data).reduce((acc, [key, value]) => {
10740
+ const elType = sameType ?? type[key];
10741
+ if (!(key in type) && !sameType) {
10742
+ acc[key] = value;
10743
+ return acc;
10781
10744
  }
10782
- const [str, k] = extractStars(decoded);
10783
- if (k)
10784
- decoded = str + (k % 2 === 0 ? bigAlphabet[bigAlphabet.length - 1].repeat(k / 2 - 1) + bigAlphabet[0] + basicAlphabet[1] : bigAlphabet[bigAlphabet.length - 1].repeat((k - 1) / 2 + 1));
10785
- decoded += ".";
10786
- });
10787
- if (!decoded) {
10788
- return decoded;
10789
- }
10790
- return decoded.concat("stark");
10745
+ if (elType === "string") {
10746
+ if (Array.isArray(data[key])) {
10747
+ const arrayStr = formatter(
10748
+ data[key],
10749
+ data[key].map((_) => elType)
10750
+ );
10751
+ acc[key] = Object.values(arrayStr).join("");
10752
+ return acc;
10753
+ }
10754
+ guard.isBN(data, type, key);
10755
+ acc[key] = decodeShortString(value);
10756
+ return acc;
10757
+ }
10758
+ if (elType === "number") {
10759
+ guard.isBN(data, type, key);
10760
+ acc[key] = Number(value);
10761
+ return acc;
10762
+ }
10763
+ if (typeof elType === "function") {
10764
+ acc[key] = elType(value);
10765
+ return acc;
10766
+ }
10767
+ if (Array.isArray(elType)) {
10768
+ const arrayObj = formatter(data[key], elType, elType[0]);
10769
+ acc[key] = Object.values(arrayObj);
10770
+ return acc;
10771
+ }
10772
+ if (typeof elType === "object") {
10773
+ acc[key] = formatter(data[key], elType);
10774
+ return acc;
10775
+ }
10776
+ guard.unknown(data, type, key);
10777
+ return acc;
10778
+ }, {});
10791
10779
  }
10792
- function useEncoded(decoded) {
10793
- let encoded = BigInt(0);
10794
- let multiplier = BigInt(1);
10795
- if (decoded.endsWith(bigAlphabet[0] + basicAlphabet[1])) {
10796
- const [str, k] = extractStars(decoded.substring(0, decoded.length - 2));
10797
- decoded = str + bigAlphabet[bigAlphabet.length - 1].repeat(2 * (k + 1));
10798
- } else {
10799
- const [str, k] = extractStars(decoded);
10800
- if (k)
10801
- decoded = str + bigAlphabet[bigAlphabet.length - 1].repeat(1 + 2 * (k - 1));
10802
- }
10803
- for (let i = 0; i < decoded.length; i += 1) {
10804
- const char = decoded[i];
10805
- const index = basicAlphabet.indexOf(char);
10806
- const bnIndex = BigInt(basicAlphabet.indexOf(char));
10807
- if (index !== -1) {
10808
- if (i === decoded.length - 1 && decoded[i] === basicAlphabet[0]) {
10809
- encoded += multiplier * basicAlphabetSize;
10810
- multiplier *= basicSizePlusOne;
10811
- multiplier *= basicSizePlusOne;
10812
- } else {
10813
- encoded += multiplier * bnIndex;
10814
- multiplier *= basicSizePlusOne;
10780
+
10781
+ // src/utils/calldata/tuple.ts
10782
+ function parseNamedTuple(namedTuple) {
10783
+ const name = namedTuple.substring(0, namedTuple.indexOf(":"));
10784
+ const type = namedTuple.substring(name.length + ":".length);
10785
+ return { name, type };
10786
+ }
10787
+ function parseSubTuple(s) {
10788
+ if (!s.includes("("))
10789
+ return { subTuple: [], result: s };
10790
+ const subTuple = [];
10791
+ let result = "";
10792
+ let i = 0;
10793
+ while (i < s.length) {
10794
+ if (s[i] === "(") {
10795
+ let counter = 1;
10796
+ const lBracket = i;
10797
+ i++;
10798
+ while (counter) {
10799
+ if (s[i] === ")")
10800
+ counter--;
10801
+ if (s[i] === "(")
10802
+ counter++;
10803
+ i++;
10815
10804
  }
10816
- } else if (bigAlphabet.indexOf(char) !== -1) {
10817
- encoded += multiplier * basicAlphabetSize;
10818
- multiplier *= basicSizePlusOne;
10819
- const newid = (i === decoded.length - 1 ? 1 : 0) + bigAlphabet.indexOf(char);
10820
- encoded += multiplier * BigInt(newid);
10821
- multiplier *= bigAlphabetSize;
10805
+ subTuple.push(s.substring(lBracket, i));
10806
+ result += " ";
10807
+ i--;
10808
+ } else {
10809
+ result += s[i];
10822
10810
  }
10811
+ i++;
10823
10812
  }
10824
- return encoded;
10813
+ return {
10814
+ subTuple,
10815
+ result
10816
+ };
10825
10817
  }
10826
- var StarknetIdContract = /* @__PURE__ */ ((StarknetIdContract2) => {
10827
- StarknetIdContract2["MAINNET"] = "0x6ac597f8116f886fa1c97a23fa4e08299975ecaf6b598873ca6792b9bbfb678";
10828
- StarknetIdContract2["TESTNET"] = "0x3bab268e932d2cecd1946f100ae67ce3dff9fd234119ea2f6da57d16d29fce";
10829
- return StarknetIdContract2;
10830
- })(StarknetIdContract || {});
10831
- function getStarknetIdContract(chainId) {
10832
- switch (chainId) {
10833
- case "0x534e5f4d41494e" /* SN_MAIN */:
10834
- return "0x6ac597f8116f886fa1c97a23fa4e08299975ecaf6b598873ca6792b9bbfb678" /* MAINNET */;
10835
- case "0x534e5f474f45524c49" /* SN_GOERLI */:
10836
- return "0x3bab268e932d2cecd1946f100ae67ce3dff9fd234119ea2f6da57d16d29fce" /* TESTNET */;
10837
- default:
10838
- throw new Error("Starknet.id is not yet deployed on this network");
10818
+ function extractCairo0Tuple(type) {
10819
+ const cleanType = type.replace(/\s/g, "").slice(1, -1);
10820
+ const { subTuple, result } = parseSubTuple(cleanType);
10821
+ let recomposed = result.split(",").map((it) => {
10822
+ return subTuple.length ? it.replace(" ", subTuple.shift()) : it;
10823
+ });
10824
+ if (isTypeNamedTuple(type)) {
10825
+ recomposed = recomposed.reduce((acc, it) => {
10826
+ return acc.concat(parseNamedTuple(it));
10827
+ }, []);
10839
10828
  }
10829
+ return recomposed;
10840
10830
  }
10841
-
10842
- // src/provider/starknetId.ts
10843
- async function getStarkName(provider, address, StarknetIdContract2) {
10844
- const chainId = await provider.getChainId();
10845
- const contract = StarknetIdContract2 ?? getStarknetIdContract(chainId);
10846
- try {
10847
- const hexDomain = await provider.callContract({
10848
- contractAddress: contract,
10849
- entrypoint: "address_to_domain",
10850
- calldata: compileCalldata({
10851
- address
10852
- })
10853
- });
10854
- const decimalDomain = hexDomain.result.map((element) => BigInt(element)).slice(1);
10855
- const stringDomain = useDecoded(decimalDomain);
10856
- if (!stringDomain) {
10857
- throw Error("Starkname not found");
10858
- }
10859
- return stringDomain;
10860
- } catch (e) {
10861
- if (e instanceof Error && e.message === "Starkname not found") {
10862
- throw e;
10863
- }
10864
- throw Error("Could not get stark name");
10865
- }
10831
+ function extractCairo1Tuple(type) {
10832
+ const cleanType = type.replace(/\s/g, "").slice(1, -1);
10833
+ return cleanType.split(",");
10866
10834
  }
10867
- async function getAddressFromStarkName(provider, name, StarknetIdContract2) {
10868
- const chainId = await provider.getChainId();
10869
- const contract = StarknetIdContract2 ?? getStarknetIdContract(chainId);
10870
- try {
10871
- const addressData = await provider.callContract({
10872
- contractAddress: contract,
10873
- entrypoint: "domain_to_address",
10874
- calldata: compileCalldata({
10875
- domain: [useEncoded(name.replace(".stark", "")).toString(10)]
10876
- })
10877
- });
10878
- return addressData.result[0];
10879
- } catch {
10880
- throw Error("Could not get address from stark name");
10835
+ function extractTupleMemberTypes(type) {
10836
+ if (isCairo1Type(type)) {
10837
+ return extractCairo1Tuple(type);
10881
10838
  }
10839
+ return extractCairo0Tuple(type);
10882
10840
  }
10883
10841
 
10884
- // src/provider/utils.ts
10885
- var validBlockTags = ["latest", "pending"];
10886
- var Block = class {
10887
- constructor(_identifier) {
10888
- this.hash = null;
10889
- this.number = null;
10890
- this.tag = null;
10891
- this.valueOf = () => this.number;
10892
- this.toString = () => this.hash;
10893
- this.setIdentifier(_identifier);
10894
- }
10895
- setIdentifier(__identifier) {
10896
- if (typeof __identifier === "string" && isHex(__identifier)) {
10897
- this.hash = __identifier;
10898
- } else if (typeof __identifier === "bigint") {
10899
- this.hash = toHex(__identifier);
10900
- } else if (typeof __identifier === "number") {
10901
- this.number = __identifier;
10902
- } else if (typeof __identifier === "string" && validBlockTags.includes(__identifier)) {
10903
- this.tag = __identifier;
10904
- } else {
10905
- this.tag = "pending";
10906
- }
10907
- }
10908
- get queryIdentifier() {
10909
- if (this.number !== null) {
10910
- return `blockNumber=${this.number}`;
10911
- }
10912
- if (this.hash !== null) {
10913
- return `blockHash=${this.hash}`;
10914
- }
10915
- return `blockNumber=${this.tag}`;
10916
- }
10917
- get identifier() {
10918
- if (this.number !== null) {
10919
- return { block_number: this.number };
10920
- }
10921
- if (this.hash !== null) {
10922
- return { block_hash: this.hash };
10923
- }
10924
- return this.tag;
10925
- }
10926
- set identifier(_identifier) {
10927
- this.setIdentifier(_identifier);
10928
- }
10929
- get sequencerIdentifier() {
10930
- return this.hash !== null ? { blockHash: this.hash } : { blockNumber: this.number ?? this.tag };
10931
- }
10932
- };
10933
-
10934
- // src/provider/rpc.ts
10935
- var defaultOptions = {
10936
- headers: { "Content-Type": "application/json" },
10937
- blockIdentifier: "latest",
10938
- retries: 200
10939
- };
10940
- var RpcProvider = class {
10941
- constructor(optionsOrProvider) {
10942
- this.responseParser = new RPCResponseParser();
10943
- const { nodeUrl, retries, headers, blockIdentifier } = optionsOrProvider;
10944
- this.nodeUrl = nodeUrl;
10945
- this.retries = retries || defaultOptions.retries;
10946
- this.headers = { ...defaultOptions.headers, ...headers };
10947
- this.blockIdentifier = blockIdentifier || defaultOptions.blockIdentifier;
10948
- this.getChainId();
10949
- }
10950
- fetch(method, params) {
10951
- return fetchPonyfill_default(this.nodeUrl, {
10952
- method: "POST",
10953
- body: stringify2({ method, jsonrpc: "2.0", params, id: 0 }),
10954
- headers: this.headers
10955
- });
10956
- }
10957
- errorHandler(error) {
10958
- if (error) {
10959
- const { code, message } = error;
10960
- throw new LibraryError(`${code}: ${message}`);
10961
- }
10962
- }
10963
- async fetchEndpoint(method, params) {
10964
- var _a;
10965
- try {
10966
- const rawResult = await this.fetch(method, params);
10967
- const { error, result } = await rawResult.json();
10968
- this.errorHandler(error);
10969
- return result;
10970
- } catch (error) {
10971
- this.errorHandler((_a = error == null ? void 0 : error.response) == null ? void 0 : _a.data);
10972
- throw error;
10973
- }
10974
- }
10975
- async getChainId() {
10976
- this.chainId ?? (this.chainId = await this.fetchEndpoint("starknet_chainId"));
10977
- return this.chainId;
10978
- }
10979
- async getBlock(blockIdentifier = this.blockIdentifier) {
10980
- return this.getBlockWithTxHashes(blockIdentifier).then(
10981
- this.responseParser.parseGetBlockResponse
10842
+ // src/utils/calldata/requestParser.ts
10843
+ function parseTuple(element, typeStr) {
10844
+ const memberTypes = extractTupleMemberTypes(typeStr);
10845
+ const elements = Object.values(element);
10846
+ if (elements.length !== memberTypes.length) {
10847
+ throw Error(
10848
+ `ParseTuple: provided and expected abi tuple size do not match.
10849
+ provided: ${elements}
10850
+ expected: ${memberTypes}`
10982
10851
  );
10983
10852
  }
10984
- async getBlockHashAndNumber() {
10985
- return this.fetchEndpoint("starknet_blockHashAndNumber");
10986
- }
10987
- async getBlockWithTxHashes(blockIdentifier = this.blockIdentifier) {
10988
- const block_id = new Block(blockIdentifier).identifier;
10989
- return this.fetchEndpoint("starknet_getBlockWithTxHashes", { block_id });
10990
- }
10991
- async getBlockWithTxs(blockIdentifier = this.blockIdentifier) {
10992
- const block_id = new Block(blockIdentifier).identifier;
10993
- return this.fetchEndpoint("starknet_getBlockWithTxs", { block_id });
10853
+ return memberTypes.map((it, dx) => {
10854
+ return {
10855
+ element: elements[dx],
10856
+ type: it.type ?? it
10857
+ };
10858
+ });
10859
+ }
10860
+ function parseCalldataValue(element, type, structs) {
10861
+ if (element === void 0) {
10862
+ throw Error(`Missing parameter for type ${type}`);
10994
10863
  }
10995
- async getClassHashAt(contractAddress, blockIdentifier = this.blockIdentifier) {
10996
- const block_id = new Block(blockIdentifier).identifier;
10997
- return this.fetchEndpoint("starknet_getClassHashAt", {
10998
- block_id,
10999
- contract_address: contractAddress
11000
- });
10864
+ if (Array.isArray(element)) {
10865
+ throw Error(`Array inside array (nD) are not supported by cairo. Element: ${element} ${type}`);
11001
10866
  }
11002
- async getNonceForAddress(contractAddress, blockIdentifier = this.blockIdentifier) {
11003
- const block_id = new Block(blockIdentifier).identifier;
11004
- return this.fetchEndpoint("starknet_getNonce", {
11005
- contract_address: contractAddress,
11006
- block_id
11007
- });
10867
+ if (isTypeUint256(type)) {
10868
+ const el_uint256 = uint256(element);
10869
+ return [felt(el_uint256.low), felt(el_uint256.high)];
11008
10870
  }
11009
- async getPendingTransactions() {
11010
- return this.fetchEndpoint("starknet_pendingTransactions");
10871
+ if (structs[type] && structs[type].members.length) {
10872
+ const { members } = structs[type];
10873
+ const subElement = element;
10874
+ return members.reduce((acc, it) => {
10875
+ return acc.concat(parseCalldataValue(subElement[it.name], it.type, structs));
10876
+ }, []);
11011
10877
  }
11012
- async getProtocolVersion() {
11013
- throw new Error("Pathfinder does not implement this rpc 0.1.0 method");
10878
+ if (isTypeTuple(type)) {
10879
+ const tupled = parseTuple(element, type);
10880
+ return tupled.reduce((acc, it) => {
10881
+ const parsedData = parseCalldataValue(it.element, it.type, structs);
10882
+ return acc.concat(parsedData);
10883
+ }, []);
11014
10884
  }
11015
- async getStateUpdate(blockIdentifier = this.blockIdentifier) {
11016
- const block_id = new Block(blockIdentifier).identifier;
11017
- return this.fetchEndpoint("starknet_getStateUpdate", { block_id });
10885
+ if (typeof element === "object") {
10886
+ throw Error(`Parameter ${element} do not align with abi parameter ${type}`);
11018
10887
  }
11019
- async getStorageAt(contractAddress, key, blockIdentifier = this.blockIdentifier) {
11020
- const parsedKey = toHex(key);
11021
- const block_id = new Block(blockIdentifier).identifier;
11022
- return this.fetchEndpoint("starknet_getStorageAt", {
11023
- contract_address: contractAddress,
11024
- key: parsedKey,
11025
- block_id
11026
- });
10888
+ return felt(element);
10889
+ }
10890
+ function parseCalldataField(argsIterator, input, structs) {
10891
+ const { name, type } = input;
10892
+ let { value } = argsIterator.next();
10893
+ switch (true) {
10894
+ case isTypeArray(type):
10895
+ if (!Array.isArray(value) && !isText(value)) {
10896
+ throw Error(`ABI expected parameter ${name} to be array or long string, got ${value}`);
10897
+ }
10898
+ if (typeof value === "string") {
10899
+ value = splitLongString(value);
10900
+ }
10901
+ const result = [];
10902
+ result.push(felt(value.length));
10903
+ const arrayType = getArrayType(input.type);
10904
+ return value.reduce((acc, el) => {
10905
+ if (isTypeFelt(arrayType) || isTypeUint(arrayType) || isTypeContractAddress(arrayType)) {
10906
+ acc.push(felt(el));
10907
+ } else if (isTypeBool(arrayType) && typeof el === "boolean") {
10908
+ acc.push(el.toString());
10909
+ } else {
10910
+ acc.push(...parseCalldataValue(el, arrayType, structs));
10911
+ }
10912
+ return acc;
10913
+ }, result);
10914
+ case (isTypeStruct(type, structs) || isTypeTuple(type) || isTypeUint256(type)):
10915
+ return parseCalldataValue(value, type, structs);
10916
+ case isTypeBool(type):
10917
+ return `${+value}`;
10918
+ default:
10919
+ return felt(value);
11027
10920
  }
11028
- async getTransaction(txHash) {
11029
- return this.getTransactionByHash(txHash).then(this.responseParser.parseGetTransactionResponse);
10921
+ }
10922
+
10923
+ // src/utils/calldata/responseParser.ts
10924
+ function parseResponseStruct(responseIterator, type, structs) {
10925
+ if (type in structs && structs[type]) {
10926
+ return structs[type].members.reduce((acc, el) => {
10927
+ acc[el.name] = parseResponseStruct(responseIterator, el.type, structs);
10928
+ return acc;
10929
+ }, {});
11030
10930
  }
11031
- async getTransactionByHash(txHash) {
11032
- return this.fetchEndpoint("starknet_getTransactionByHash", { transaction_hash: txHash });
10931
+ if (isTypeTuple(type)) {
10932
+ const memberTypes = extractTupleMemberTypes(type);
10933
+ return memberTypes.reduce((acc, it, idx) => {
10934
+ const tName = (it == null ? void 0 : it.name) ? it.name : idx;
10935
+ const tType = (it == null ? void 0 : it.type) ? it.type : it;
10936
+ acc[tName] = parseResponseStruct(responseIterator, tType, structs);
10937
+ return acc;
10938
+ }, {});
11033
10939
  }
11034
- async getTransactionByBlockIdAndIndex(blockIdentifier, index) {
11035
- const block_id = new Block(blockIdentifier).identifier;
11036
- return this.fetchEndpoint("starknet_getTransactionByBlockIdAndIndex", { block_id, index });
10940
+ const temp = responseIterator.next().value;
10941
+ return BigInt(temp);
10942
+ }
10943
+ function responseParser(responseIterator, output2, structs, parsedResult) {
10944
+ const { name, type } = output2;
10945
+ let temp;
10946
+ switch (true) {
10947
+ case isLen(name):
10948
+ temp = responseIterator.next().value;
10949
+ return BigInt(temp);
10950
+ case isTypeBool(type):
10951
+ temp = responseIterator.next().value;
10952
+ return Boolean(BigInt(temp));
10953
+ case isTypeUint256(type):
10954
+ const low = responseIterator.next().value;
10955
+ const high = responseIterator.next().value;
10956
+ return uint256ToBN({ low, high });
10957
+ case isTypeArray(type):
10958
+ const parsedDataArr = [];
10959
+ if (isCairo1Type(type)) {
10960
+ responseIterator.next();
10961
+ let it = responseIterator.next();
10962
+ while (!it.done) {
10963
+ parsedDataArr.push(BigInt(it.value));
10964
+ it = responseIterator.next();
10965
+ }
10966
+ return parsedDataArr;
10967
+ }
10968
+ if (parsedResult && parsedResult[`${name}_len`]) {
10969
+ const arrLen = parsedResult[`${name}_len`];
10970
+ while (parsedDataArr.length < arrLen) {
10971
+ parsedDataArr.push(
10972
+ parseResponseStruct(responseIterator, output2.type.replace("*", ""), structs)
10973
+ );
10974
+ }
10975
+ }
10976
+ return parsedDataArr;
10977
+ case (type in structs || isTypeTuple(type)):
10978
+ return parseResponseStruct(responseIterator, type, structs);
10979
+ default:
10980
+ temp = responseIterator.next().value;
10981
+ return BigInt(temp);
11037
10982
  }
11038
- async getTransactionReceipt(txHash) {
11039
- return this.fetchEndpoint("starknet_getTransactionReceipt", { transaction_hash: txHash });
11040
- }
11041
- async getClassByHash(classHash) {
11042
- return this.getClass(classHash);
10983
+ }
10984
+
10985
+ // src/utils/calldata/validate.ts
10986
+ var validateFelt = (parameter, input) => {
10987
+ assert2(
10988
+ typeof parameter === "string" || typeof parameter === "number" || typeof parameter === "bigint",
10989
+ `Validate: arg ${input.name} should be a felt typed as (String, Number or BigInt)`
10990
+ );
10991
+ };
10992
+ var validateUint = (parameter, input) => {
10993
+ if (typeof parameter === "number") {
10994
+ assert2(
10995
+ parameter <= Number.MAX_SAFE_INTEGER,
10996
+ `Validation: Parameter is to large to be typed as Number use (BigInt or String)`
10997
+ );
11043
10998
  }
11044
- async getClass(classHash, blockIdentifier = this.blockIdentifier) {
11045
- const block_id = new Block(blockIdentifier).identifier;
11046
- return this.fetchEndpoint("starknet_getClass", { class_hash: classHash, block_id });
10999
+ assert2(
11000
+ typeof parameter === "string" || typeof parameter === "number" || typeof parameter === "bigint",
11001
+ `Validate: arg ${input.name} of cairo type ${input.type} should be type (String, Number or BigInt)`
11002
+ );
11003
+ const param = toBigInt(parameter);
11004
+ switch (input.type) {
11005
+ case "core::integer::u8" /* u8 */:
11006
+ assert2(
11007
+ param >= 0n && param <= 255n,
11008
+ `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0 - 255]`
11009
+ );
11010
+ break;
11011
+ case "core::integer::u16" /* u16 */:
11012
+ assert2(
11013
+ param >= 0n && param <= 65535n,
11014
+ `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 65535]`
11015
+ );
11016
+ break;
11017
+ case "core::integer::u32" /* u32 */:
11018
+ assert2(
11019
+ param >= 0n && param <= 4294967295n,
11020
+ `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 4294967295]`
11021
+ );
11022
+ break;
11023
+ case "core::integer::u64" /* u64 */:
11024
+ assert2(
11025
+ param >= 0n && param <= 2n ** 64n - 1n,
11026
+ `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 2^64-1]`
11027
+ );
11028
+ break;
11029
+ case "core::integer::u128" /* u128 */:
11030
+ assert2(
11031
+ param >= 0n && param <= 2n ** 128n - 1n,
11032
+ `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 2^128-1]`
11033
+ );
11034
+ break;
11035
+ case "core::integer::u256" /* u256 */:
11036
+ assert2(
11037
+ param >= 0n && param <= 2n ** 256n - 1n,
11038
+ `Validate: arg ${input.name} is ${input.type} 0 - 2^256-1`
11039
+ );
11040
+ break;
11041
+ default:
11042
+ break;
11047
11043
  }
11048
- async getClassAt(contractAddress, blockIdentifier = this.blockIdentifier) {
11049
- const block_id = new Block(blockIdentifier).identifier;
11050
- return this.fetchEndpoint("starknet_getClassAt", {
11051
- block_id,
11052
- contract_address: contractAddress
11053
- });
11044
+ };
11045
+ var validateBool = (parameter, input) => {
11046
+ assert2(
11047
+ typeof parameter === "boolean",
11048
+ `Validate: arg ${input.name} of cairo type ${input.type} should be type (Boolean)`
11049
+ );
11050
+ };
11051
+ var validateStruct = (parameter, input, structs) => {
11052
+ assert2(
11053
+ typeof parameter === "object" && !Array.isArray(parameter),
11054
+ `Validate: arg ${input.name} is cairo type struct (${input.type}), and should be defined as js object (not array)`
11055
+ );
11056
+ structs[input.type].members.forEach(({ name }) => {
11057
+ assert2(
11058
+ Object.keys(parameter).includes(name),
11059
+ `Validate: arg ${input.name} should have a property ${name}`
11060
+ );
11061
+ });
11062
+ };
11063
+ var validateTuple = (parameter, input) => {
11064
+ assert2(
11065
+ typeof parameter === "object" && !Array.isArray(parameter),
11066
+ `Validate: arg ${input.name} should be a tuple (defined as object)`
11067
+ );
11068
+ };
11069
+ var validateArray = (parameter, input, structs) => {
11070
+ const baseType = getArrayType(input.type);
11071
+ if (isTypeFelt(baseType) && isLongText(parameter))
11072
+ return;
11073
+ assert2(Array.isArray(parameter), `Validate: arg ${input.name} should be an Array`);
11074
+ switch (true) {
11075
+ case isTypeFelt(baseType):
11076
+ parameter.forEach((param) => validateFelt(param, input));
11077
+ break;
11078
+ case isTypeTuple(baseType):
11079
+ parameter.forEach((it) => validateTuple(it, { name: input.name, type: baseType }));
11080
+ break;
11081
+ case isTypeStruct(baseType, structs):
11082
+ parameter.forEach(
11083
+ (it) => validateStruct(it, { name: input.name, type: baseType }, structs)
11084
+ );
11085
+ break;
11086
+ case isTypeUint(baseType):
11087
+ parameter.forEach((param) => validateUint(param, input));
11088
+ break;
11089
+ case isTypeBool(baseType):
11090
+ parameter.forEach((param) => validateBool(param, input));
11091
+ break;
11092
+ default:
11093
+ throw new Error(
11094
+ `Validate Unhandled: argument ${input.name}, type ${input.type}, value ${parameter}`
11095
+ );
11054
11096
  }
11055
- async getCode(_contractAddress, _blockIdentifier) {
11056
- throw new Error("RPC does not implement getCode function");
11097
+ };
11098
+ function validateFields(abiMethod, args, structs) {
11099
+ abiMethod.inputs.reduce((acc, input) => {
11100
+ const parameter = args[acc];
11101
+ switch (true) {
11102
+ case isLen(input.name):
11103
+ return acc;
11104
+ case isTypeFelt(input.type):
11105
+ validateFelt(parameter, input);
11106
+ break;
11107
+ case isTypeUint(input.type):
11108
+ validateUint(parameter, input);
11109
+ break;
11110
+ case isTypeBool(input.type):
11111
+ validateBool(parameter, input);
11112
+ break;
11113
+ case isTypeContractAddress(input.type):
11114
+ break;
11115
+ case isTypeStruct(input.type, structs):
11116
+ validateStruct(parameter, input, structs);
11117
+ break;
11118
+ case isTypeTuple(input.type):
11119
+ validateTuple(parameter, input);
11120
+ break;
11121
+ case isTypeArray(input.type):
11122
+ validateArray(parameter, input, structs);
11123
+ break;
11124
+ default:
11125
+ throw new Error(
11126
+ `Validate Unhandled: argument ${input.name}, type ${input.type}, value ${parameter}`
11127
+ );
11128
+ }
11129
+ return acc + 1;
11130
+ }, 0);
11131
+ }
11132
+
11133
+ // src/utils/calldata/index.ts
11134
+ var CallData = class {
11135
+ constructor(abi) {
11136
+ this.abi = abi;
11137
+ this.structs = CallData.getAbiStruct(abi);
11057
11138
  }
11058
- async getEstimateFee(invocation, invocationDetails, blockIdentifier = this.blockIdentifier) {
11059
- return this.getInvokeEstimateFee(invocation, invocationDetails, blockIdentifier);
11139
+ validate(type, method, args = []) {
11140
+ if (type !== "DEPLOY") {
11141
+ const invocableFunctionNames = this.abi.filter((abi) => {
11142
+ if (abi.type !== "function")
11143
+ return false;
11144
+ const isView = abi.stateMutability === "view" || abi.state_mutability === "view";
11145
+ return type === "INVOKE" ? !isView : isView;
11146
+ }).map((abi) => abi.name);
11147
+ assert2(
11148
+ invocableFunctionNames.includes(method),
11149
+ `${type === "INVOKE" ? "invocable" : "viewable"} method not found in abi`
11150
+ );
11151
+ }
11152
+ const abiMethod = this.abi.find(
11153
+ (abi) => type === "DEPLOY" ? abi.name === method && abi.type === method : abi.name === method && abi.type === "function"
11154
+ );
11155
+ const inputsLength = CallData.abiInputsLength(abiMethod.inputs);
11156
+ if (args.length !== inputsLength) {
11157
+ throw Error(
11158
+ `Invalid number of arguments, expected ${inputsLength} arguments, but got ${args.length}`
11159
+ );
11160
+ }
11161
+ validateFields(abiMethod, args, this.structs);
11060
11162
  }
11061
- async getInvokeEstimateFee(invocation, invocationDetails, blockIdentifier = this.blockIdentifier) {
11062
- const block_id = new Block(blockIdentifier).identifier;
11063
- return this.fetchEndpoint("starknet_estimateFee", {
11064
- request: {
11065
- type: RPC.TransactionType.INVOKE,
11066
- sender_address: invocation.contractAddress,
11067
- calldata: parseCalldata(invocation.calldata),
11068
- signature: signatureToHexArray(invocation.signature),
11069
- version: toHex((invocationDetails == null ? void 0 : invocationDetails.version) || 0),
11070
- nonce: toHex(invocationDetails.nonce),
11071
- max_fee: toHex((invocationDetails == null ? void 0 : invocationDetails.maxFee) || 0)
11072
- },
11073
- block_id
11074
- }).then(this.responseParser.parseFeeEstimateResponse);
11163
+ compile(method, args) {
11164
+ const argsIterator = args[Symbol.iterator]();
11165
+ const { inputs } = this.abi.find((abi) => abi.name === method);
11166
+ return inputs.reduce(
11167
+ (acc, input) => isLen(input.name) ? acc : acc.concat(parseCalldataField(argsIterator, input, this.structs)),
11168
+ []
11169
+ );
11075
11170
  }
11076
- async getDeclareEstimateFee({ senderAddress, contractDefinition, signature }, details, blockIdentifier = this.blockIdentifier) {
11077
- const block_id = new Block(blockIdentifier).identifier;
11078
- if ("program" in contractDefinition) {
11079
- return this.fetchEndpoint("starknet_estimateFee", {
11080
- request: {
11081
- type: RPC.TransactionType.DECLARE,
11082
- contract_class: {
11083
- program: contractDefinition.program,
11084
- entry_points_by_type: contractDefinition.entry_points_by_type,
11085
- abi: contractDefinition.abi
11086
- },
11087
- sender_address: senderAddress,
11088
- signature: signatureToHexArray(signature),
11089
- version: toHex((details == null ? void 0 : details.version) || 0),
11090
- nonce: toHex(details.nonce),
11091
- max_fee: toHex((details == null ? void 0 : details.maxFee) || 0)
11092
- },
11093
- block_id
11094
- }).then(this.responseParser.parseFeeEstimateResponse);
11171
+ static compile(rawArgs) {
11172
+ const createTree = (obj) => {
11173
+ const getEntries = (o, prefix = "") => {
11174
+ const oe = Array.isArray(o) ? [o.length.toString(), ...o] : o;
11175
+ return Object.entries(oe).flatMap(([k, v]) => {
11176
+ let value = v;
11177
+ if (isLongText(value))
11178
+ value = splitLongString(value);
11179
+ const kk = Array.isArray(oe) && k === "0" ? "$$len" : k;
11180
+ if (isBigInt(value))
11181
+ return [[`${prefix}${kk}`, felt(value)]];
11182
+ return Object(value) === value ? getEntries(value, `${prefix}${kk}.`) : [[`${prefix}${kk}`, felt(value)]];
11183
+ });
11184
+ };
11185
+ return Object.fromEntries(getEntries(obj));
11186
+ };
11187
+ let callTreeArray;
11188
+ if (!Array.isArray(rawArgs)) {
11189
+ const callTree = createTree(rawArgs);
11190
+ callTreeArray = Object.values(callTree);
11191
+ } else {
11192
+ const callObj = { ...rawArgs };
11193
+ const callTree = createTree(callObj);
11194
+ callTreeArray = Object.values(callTree);
11095
11195
  }
11096
- throw new Error("RPC do not support Sierra Contracts yet");
11196
+ Object.defineProperty(callTreeArray, "__compiled__", {
11197
+ enumerable: false,
11198
+ writable: false,
11199
+ value: true
11200
+ });
11201
+ return callTreeArray;
11097
11202
  }
11098
- async getDeployAccountEstimateFee({ classHash, constructorCalldata, addressSalt, signature }, details, blockIdentifier = this.blockIdentifier) {
11099
- const block_id = new Block(blockIdentifier).identifier;
11100
- return this.fetchEndpoint("starknet_estimateFee", {
11101
- request: {
11102
- type: RPC.TransactionType.DEPLOY_ACCOUNT,
11103
- constructor_calldata: bigNumberishArrayToHexadecimalStringArray(constructorCalldata || []),
11104
- class_hash: toHex(classHash),
11105
- contract_address_salt: toHex(addressSalt || 0),
11106
- signature: signatureToHexArray(signature),
11107
- version: toHex((details == null ? void 0 : details.version) || 0),
11108
- nonce: toHex(details.nonce),
11109
- max_fee: toHex((details == null ? void 0 : details.maxFee) || 0)
11110
- },
11111
- block_id
11112
- }).then(this.responseParser.parseFeeEstimateResponse);
11113
- }
11114
- async getEstimateFeeBulk(_invocations, _blockIdentifier = this.blockIdentifier) {
11115
- throw new Error("RPC does not implement getInvokeEstimateFeeBulk function");
11116
- }
11117
- async declareContract({ contractDefinition, signature, senderAddress }, details) {
11118
- if ("program" in contractDefinition) {
11119
- return this.fetchEndpoint("starknet_addDeclareTransaction", {
11120
- declare_transaction: {
11121
- contract_class: {
11122
- program: contractDefinition.program,
11123
- entry_points_by_type: contractDefinition.entry_points_by_type,
11124
- abi: contractDefinition.abi
11125
- },
11126
- type: RPC.TransactionType.DECLARE,
11127
- version: "0x1",
11128
- max_fee: toHex(details.maxFee || 0),
11129
- signature: signatureToHexArray(signature),
11130
- sender_address: senderAddress,
11131
- nonce: toHex(details.nonce)
11132
- }
11133
- });
11134
- }
11135
- throw new Error("RPC do not support Sierra Contracts yet");
11136
- }
11137
- async deployAccountContract({ classHash, constructorCalldata, addressSalt, signature }, details) {
11138
- return this.fetchEndpoint("starknet_addDeployAccountTransaction", {
11139
- deploy_account_transaction: {
11140
- constructor_calldata: bigNumberishArrayToHexadecimalStringArray(constructorCalldata || []),
11141
- class_hash: toHex(classHash),
11142
- contract_address_salt: toHex(addressSalt || 0),
11143
- type: RPC.TransactionType.DEPLOY_ACCOUNT,
11144
- max_fee: toHex(details.maxFee || 0),
11145
- version: toHex(details.version || 0),
11146
- signature: signatureToHexArray(signature),
11147
- nonce: toHex(details.nonce)
11203
+ parse(method, response) {
11204
+ const { outputs } = this.abi.find((abi) => abi.name === method);
11205
+ const responseIterator = response.flat()[Symbol.iterator]();
11206
+ const parsed = outputs.flat().reduce((acc, output2, idx) => {
11207
+ const propName = output2.name ?? idx;
11208
+ acc[propName] = responseParser(responseIterator, output2, this.structs, acc);
11209
+ if (acc[propName] && acc[`${propName}_len`]) {
11210
+ delete acc[`${propName}_len`];
11148
11211
  }
11149
- });
11212
+ return acc;
11213
+ }, {});
11214
+ return Object.keys(parsed).length === 1 && 0 in parsed ? parsed[0] : parsed;
11150
11215
  }
11151
- async invokeFunction(functionInvocation, details) {
11152
- return this.fetchEndpoint("starknet_addInvokeTransaction", {
11153
- invoke_transaction: {
11154
- sender_address: functionInvocation.contractAddress,
11155
- calldata: parseCalldata(functionInvocation.calldata),
11156
- type: RPC.TransactionType.INVOKE,
11157
- max_fee: toHex(details.maxFee || 0),
11158
- version: "0x1",
11159
- signature: signatureToHexArray(functionInvocation.signature),
11160
- nonce: toHex(details.nonce)
11161
- }
11162
- });
11216
+ format(method, response, format) {
11217
+ const parsed = this.parse(method, response);
11218
+ return formatter(parsed, format);
11163
11219
  }
11164
- async callContract(call, blockIdentifier = this.blockIdentifier) {
11165
- const block_id = new Block(blockIdentifier).identifier;
11166
- const result = await this.fetchEndpoint("starknet_call", {
11167
- request: {
11168
- contract_address: call.contractAddress,
11169
- entry_point_selector: getSelectorFromName(call.entrypoint),
11170
- calldata: parseCalldata(call.calldata)
11171
- },
11172
- block_id
11173
- });
11174
- return this.responseParser.parseCallContractResponse(result);
11220
+ static abiInputsLength(inputs) {
11221
+ return inputs.reduce((acc, input) => !isLen(input.name) ? acc + 1 : acc, 0);
11175
11222
  }
11176
- async traceTransaction(transactionHash) {
11177
- return this.fetchEndpoint("starknet_traceTransaction", { transaction_hash: transactionHash });
11223
+ static getAbiStruct(abi) {
11224
+ return abi.filter((abiEntry) => abiEntry.type === "struct").reduce(
11225
+ (acc, abiEntry) => ({
11226
+ ...acc,
11227
+ [abiEntry.name]: abiEntry
11228
+ }),
11229
+ {}
11230
+ );
11178
11231
  }
11179
- async traceBlockTransactions(blockHash) {
11180
- return this.fetchEndpoint("starknet_traceBlockTransactions", { block_hash: blockHash });
11232
+ };
11233
+
11234
+ // src/utils/starknetId.ts
11235
+ var starknetId_exports = {};
11236
+ __export(starknetId_exports, {
11237
+ StarknetIdContract: () => StarknetIdContract,
11238
+ getStarknetIdContract: () => getStarknetIdContract,
11239
+ useDecoded: () => useDecoded,
11240
+ useEncoded: () => useEncoded
11241
+ });
11242
+ var basicAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789-";
11243
+ var basicSizePlusOne = BigInt(basicAlphabet.length + 1);
11244
+ var bigAlphabet = "\u8FD9\u6765";
11245
+ var basicAlphabetSize = BigInt(basicAlphabet.length);
11246
+ var bigAlphabetSize = BigInt(bigAlphabet.length);
11247
+ var bigAlphabetSizePlusOne = BigInt(bigAlphabet.length + 1);
11248
+ function extractStars(str) {
11249
+ let k = 0;
11250
+ while (str.endsWith(bigAlphabet[bigAlphabet.length - 1])) {
11251
+ str = str.substring(0, str.length - 1);
11252
+ k += 1;
11181
11253
  }
11182
- async waitForTransaction(txHash, options) {
11183
- const errorStates = ["REJECTED" /* REJECTED */, "NOT_RECEIVED" /* NOT_RECEIVED */];
11184
- let { retries } = this;
11185
- let onchain = false;
11186
- let txReceipt = {};
11187
- const retryInterval = (options == null ? void 0 : options.retryInterval) ?? 8e3;
11188
- const successStates = (options == null ? void 0 : options.successStates) ?? [
11189
- "ACCEPTED_ON_L1" /* ACCEPTED_ON_L1 */,
11190
- "ACCEPTED_ON_L2" /* ACCEPTED_ON_L2 */,
11191
- "PENDING" /* PENDING */
11192
- ];
11193
- while (!onchain) {
11194
- await wait(retryInterval);
11195
- try {
11196
- txReceipt = await this.getTransactionReceipt(txHash);
11197
- if (!("status" in txReceipt)) {
11198
- const error = new Error("pending transaction");
11199
- throw error;
11200
- }
11201
- if (txReceipt.status && successStates.includes(txReceipt.status)) {
11202
- onchain = true;
11203
- } else if (txReceipt.status && errorStates.includes(txReceipt.status)) {
11204
- const message = txReceipt.status;
11205
- const error = new Error(message);
11206
- error.response = txReceipt;
11207
- throw error;
11208
- }
11209
- } catch (error) {
11210
- if (error instanceof Error && errorStates.includes(error.message)) {
11211
- throw error;
11212
- }
11213
- if (retries === 0) {
11214
- throw new Error(`waitForTransaction timed-out with retries ${this.retries}`);
11254
+ return [str, k];
11255
+ }
11256
+ function useDecoded(encoded) {
11257
+ let decoded = "";
11258
+ encoded.forEach((subdomain) => {
11259
+ while (subdomain !== ZERO) {
11260
+ const code = subdomain % basicSizePlusOne;
11261
+ subdomain /= basicSizePlusOne;
11262
+ if (code === BigInt(basicAlphabet.length)) {
11263
+ const nextSubdomain = subdomain / bigAlphabetSizePlusOne;
11264
+ if (nextSubdomain === ZERO) {
11265
+ const code2 = subdomain % bigAlphabetSizePlusOne;
11266
+ subdomain = nextSubdomain;
11267
+ if (code2 === ZERO)
11268
+ decoded += basicAlphabet[0];
11269
+ else
11270
+ decoded += bigAlphabet[Number(code2) - 1];
11271
+ } else {
11272
+ const code2 = subdomain % bigAlphabetSize;
11273
+ decoded += bigAlphabet[Number(code2)];
11274
+ subdomain /= bigAlphabetSize;
11215
11275
  }
11216
- }
11217
- retries -= 1;
11276
+ } else
11277
+ decoded += basicAlphabet[Number(code)];
11218
11278
  }
11219
- await wait(retryInterval);
11220
- return txReceipt;
11221
- }
11222
- async getTransactionCount(blockIdentifier = this.blockIdentifier) {
11223
- const block_id = new Block(blockIdentifier).identifier;
11224
- return this.fetchEndpoint("starknet_getBlockTransactionCount", { block_id });
11225
- }
11226
- async getBlockNumber() {
11227
- return this.fetchEndpoint("starknet_blockNumber");
11228
- }
11229
- async getSyncingStats() {
11230
- return this.fetchEndpoint("starknet_syncing");
11231
- }
11232
- async getEvents(eventFilter) {
11233
- return this.fetchEndpoint("starknet_getEvents", { filter: eventFilter });
11279
+ const [str, k] = extractStars(decoded);
11280
+ if (k)
11281
+ decoded = str + (k % 2 === 0 ? bigAlphabet[bigAlphabet.length - 1].repeat(k / 2 - 1) + bigAlphabet[0] + basicAlphabet[1] : bigAlphabet[bigAlphabet.length - 1].repeat((k - 1) / 2 + 1));
11282
+ decoded += ".";
11283
+ });
11284
+ if (!decoded) {
11285
+ return decoded;
11234
11286
  }
11235
- async getSimulateTransaction(_invocation, _invocationDetails, _blockIdentifier) {
11236
- throw new Error("RPC does not implement simulateTransaction function");
11287
+ return decoded.concat("stark");
11288
+ }
11289
+ function useEncoded(decoded) {
11290
+ let encoded = BigInt(0);
11291
+ let multiplier = BigInt(1);
11292
+ if (decoded.endsWith(bigAlphabet[0] + basicAlphabet[1])) {
11293
+ const [str, k] = extractStars(decoded.substring(0, decoded.length - 2));
11294
+ decoded = str + bigAlphabet[bigAlphabet.length - 1].repeat(2 * (k + 1));
11295
+ } else {
11296
+ const [str, k] = extractStars(decoded);
11297
+ if (k)
11298
+ decoded = str + bigAlphabet[bigAlphabet.length - 1].repeat(1 + 2 * (k - 1));
11237
11299
  }
11238
- async getStarkName(address, StarknetIdContract2) {
11239
- return getStarkName(this, address, StarknetIdContract2);
11300
+ for (let i = 0; i < decoded.length; i += 1) {
11301
+ const char = decoded[i];
11302
+ const index = basicAlphabet.indexOf(char);
11303
+ const bnIndex = BigInt(basicAlphabet.indexOf(char));
11304
+ if (index !== -1) {
11305
+ if (i === decoded.length - 1 && decoded[i] === basicAlphabet[0]) {
11306
+ encoded += multiplier * basicAlphabetSize;
11307
+ multiplier *= basicSizePlusOne;
11308
+ multiplier *= basicSizePlusOne;
11309
+ } else {
11310
+ encoded += multiplier * bnIndex;
11311
+ multiplier *= basicSizePlusOne;
11312
+ }
11313
+ } else if (bigAlphabet.indexOf(char) !== -1) {
11314
+ encoded += multiplier * basicAlphabetSize;
11315
+ multiplier *= basicSizePlusOne;
11316
+ const newid = (i === decoded.length - 1 ? 1 : 0) + bigAlphabet.indexOf(char);
11317
+ encoded += multiplier * BigInt(newid);
11318
+ multiplier *= bigAlphabetSize;
11319
+ }
11240
11320
  }
11241
- async getAddressFromStarkName(name, StarknetIdContract2) {
11242
- return getAddressFromStarkName(this, name, StarknetIdContract2);
11321
+ return encoded;
11322
+ }
11323
+ var StarknetIdContract = /* @__PURE__ */ ((StarknetIdContract2) => {
11324
+ StarknetIdContract2["MAINNET"] = "0x6ac597f8116f886fa1c97a23fa4e08299975ecaf6b598873ca6792b9bbfb678";
11325
+ StarknetIdContract2["TESTNET"] = "0x3bab268e932d2cecd1946f100ae67ce3dff9fd234119ea2f6da57d16d29fce";
11326
+ return StarknetIdContract2;
11327
+ })(StarknetIdContract || {});
11328
+ function getStarknetIdContract(chainId) {
11329
+ switch (chainId) {
11330
+ case "0x534e5f4d41494e" /* SN_MAIN */:
11331
+ return "0x6ac597f8116f886fa1c97a23fa4e08299975ecaf6b598873ca6792b9bbfb678" /* MAINNET */;
11332
+ case "0x534e5f474f45524c49" /* SN_GOERLI */:
11333
+ return "0x3bab268e932d2cecd1946f100ae67ce3dff9fd234119ea2f6da57d16d29fce" /* TESTNET */;
11334
+ default:
11335
+ throw new Error("Starknet.id is not yet deployed on this network");
11243
11336
  }
11244
- };
11245
-
11246
- // src/provider/sequencer.ts
11247
- var import_url_join2 = __toESM(require_url_join());
11337
+ }
11248
11338
 
11249
- // src/utils/responseParser/index.ts
11250
- var ResponseParser = class {
11251
- };
11339
+ // src/provider/starknetId.ts
11340
+ async function getStarkName(provider, address, StarknetIdContract2) {
11341
+ const chainId = await provider.getChainId();
11342
+ const contract = StarknetIdContract2 ?? getStarknetIdContract(chainId);
11343
+ try {
11344
+ const hexDomain = await provider.callContract({
11345
+ contractAddress: contract,
11346
+ entrypoint: "address_to_domain",
11347
+ calldata: CallData.compile({
11348
+ address
11349
+ })
11350
+ });
11351
+ const decimalDomain = hexDomain.result.map((element) => BigInt(element)).slice(1);
11352
+ const stringDomain = useDecoded(decimalDomain);
11353
+ if (!stringDomain) {
11354
+ throw Error("Starkname not found");
11355
+ }
11356
+ return stringDomain;
11357
+ } catch (e) {
11358
+ if (e instanceof Error && e.message === "Starkname not found") {
11359
+ throw e;
11360
+ }
11361
+ throw Error("Could not get stark name");
11362
+ }
11363
+ }
11364
+ async function getAddressFromStarkName(provider, name, StarknetIdContract2) {
11365
+ const chainId = await provider.getChainId();
11366
+ const contract = StarknetIdContract2 ?? getStarknetIdContract(chainId);
11367
+ try {
11368
+ const addressData = await provider.callContract({
11369
+ contractAddress: contract,
11370
+ entrypoint: "domain_to_address",
11371
+ calldata: CallData.compile({
11372
+ domain: [useEncoded(name.replace(".stark", "")).toString(10)]
11373
+ })
11374
+ });
11375
+ return addressData.result[0];
11376
+ } catch {
11377
+ throw Error("Could not get address from stark name");
11378
+ }
11379
+ }
11252
11380
 
11253
- // src/utils/responseParser/sequencer.ts
11254
- var SequencerAPIResponseParser = class extends ResponseParser {
11255
- parseGetBlockResponse(res) {
11256
- return {
11257
- ...res,
11258
- new_root: res.state_root,
11259
- parent_hash: res.parent_block_hash,
11260
- transactions: Object.values(res.transactions).map((value) => "transaction_hash" in value && value.transaction_hash).filter(Boolean)
11261
- };
11381
+ // src/provider/utils.ts
11382
+ var validBlockTags = ["latest", "pending"];
11383
+ var Block = class {
11384
+ constructor(_identifier) {
11385
+ this.hash = null;
11386
+ this.number = null;
11387
+ this.tag = null;
11388
+ this.valueOf = () => this.number;
11389
+ this.toString = () => this.hash;
11390
+ this.setIdentifier(_identifier);
11262
11391
  }
11263
- parseGetTransactionResponse(res) {
11264
- return {
11265
- ...res,
11266
- calldata: "calldata" in res.transaction ? res.transaction.calldata : [],
11267
- contract_class: "contract_class" in res.transaction ? res.transaction.contract_class : void 0,
11268
- entry_point_selector: "entry_point_selector" in res.transaction ? res.transaction.entry_point_selector : void 0,
11269
- max_fee: "max_fee" in res.transaction ? res.transaction.max_fee : void 0,
11270
- nonce: res.transaction.nonce,
11271
- sender_address: "sender_address" in res.transaction ? res.transaction.sender_address : void 0,
11272
- signature: "signature" in res.transaction ? res.transaction.signature : void 0,
11273
- transaction_hash: "transaction_hash" in res.transaction ? res.transaction.transaction_hash : void 0,
11274
- version: "version" in res.transaction ? res.transaction.version : void 0
11275
- };
11392
+ setIdentifier(__identifier) {
11393
+ if (typeof __identifier === "string" && isHex(__identifier)) {
11394
+ this.hash = __identifier;
11395
+ } else if (typeof __identifier === "bigint") {
11396
+ this.hash = toHex(__identifier);
11397
+ } else if (typeof __identifier === "number") {
11398
+ this.number = __identifier;
11399
+ } else if (typeof __identifier === "string" && validBlockTags.includes(__identifier)) {
11400
+ this.tag = __identifier;
11401
+ } else {
11402
+ this.tag = "pending";
11403
+ }
11276
11404
  }
11277
- parseGetTransactionReceiptResponse(res) {
11278
- return {
11279
- transaction_hash: res.transaction_hash,
11280
- status: res.status,
11281
- messages_sent: res.l2_to_l1_messages,
11282
- events: res.events,
11283
- ..."block_hash" in res && { block_hash: res.block_hash },
11284
- ..."block_number" in res && { block_number: res.block_number },
11285
- ..."actual_fee" in res && { actual_fee: res.actual_fee },
11286
- ..."transaction_index" in res && { transaction_index: res.transaction_index },
11287
- ..."execution_resources" in res && { execution_resources: res.execution_resources },
11288
- ..."l1_to_l2_consumed_message" in res && {
11289
- l1_to_l2_consumed_message: res["l1_to_l2_consumed_message"]
11290
- },
11291
- ..."transaction_failure_reason" in res && {
11292
- transaction_failure_reason: res.transaction_failure_reason
11293
- }
11294
- };
11405
+ get queryIdentifier() {
11406
+ if (this.number !== null) {
11407
+ return `blockNumber=${this.number}`;
11408
+ }
11409
+ if (this.hash !== null) {
11410
+ return `blockHash=${this.hash}`;
11411
+ }
11412
+ return `blockNumber=${this.tag}`;
11295
11413
  }
11296
- parseFeeEstimateResponse(res) {
11297
- if ("overall_fee" in res) {
11298
- let gasInfo = {};
11299
- try {
11300
- gasInfo = {
11301
- gas_consumed: toBigInt(res.gas_usage),
11302
- gas_price: toBigInt(res.gas_price)
11303
- };
11304
- } catch {
11305
- }
11306
- return {
11307
- overall_fee: toBigInt(res.overall_fee),
11308
- ...gasInfo
11309
- };
11414
+ get identifier() {
11415
+ if (this.number !== null) {
11416
+ return { block_number: this.number };
11310
11417
  }
11311
- return {
11312
- overall_fee: toBigInt(res.amount)
11313
- };
11418
+ if (this.hash !== null) {
11419
+ return { block_hash: this.hash };
11420
+ }
11421
+ return this.tag;
11314
11422
  }
11315
- parseFeeEstimateBulkResponse(res) {
11316
- return [].concat(res).map((item) => {
11317
- if ("overall_fee" in item) {
11318
- let gasInfo = {};
11319
- try {
11320
- gasInfo = {
11321
- gas_consumed: toBigInt(item.gas_usage),
11322
- gas_price: toBigInt(item.gas_price)
11323
- };
11324
- } catch {
11325
- }
11326
- return {
11327
- overall_fee: toBigInt(item.overall_fee),
11328
- ...gasInfo
11329
- };
11330
- }
11331
- return {
11332
- overall_fee: toBigInt(item.amount)
11333
- };
11423
+ set identifier(_identifier) {
11424
+ this.setIdentifier(_identifier);
11425
+ }
11426
+ get sequencerIdentifier() {
11427
+ return this.hash !== null ? { blockHash: this.hash } : { blockNumber: this.number ?? this.tag };
11428
+ }
11429
+ };
11430
+
11431
+ // src/provider/rpc.ts
11432
+ var defaultOptions = {
11433
+ headers: { "Content-Type": "application/json" },
11434
+ blockIdentifier: "latest",
11435
+ retries: 200
11436
+ };
11437
+ var RpcProvider = class {
11438
+ constructor(optionsOrProvider) {
11439
+ this.responseParser = new RPCResponseParser();
11440
+ const { nodeUrl, retries, headers, blockIdentifier } = optionsOrProvider;
11441
+ this.nodeUrl = nodeUrl;
11442
+ this.retries = retries || defaultOptions.retries;
11443
+ this.headers = { ...defaultOptions.headers, ...headers };
11444
+ this.blockIdentifier = blockIdentifier || defaultOptions.blockIdentifier;
11445
+ this.getChainId();
11446
+ }
11447
+ fetch(method, params) {
11448
+ return fetchPonyfill_default(this.nodeUrl, {
11449
+ method: "POST",
11450
+ body: stringify2({ method, jsonrpc: "2.0", params, id: 0 }),
11451
+ headers: this.headers
11334
11452
  });
11335
11453
  }
11336
- parseFeeSimulateTransactionResponse(res) {
11337
- if ("overall_fee" in res.fee_estimation) {
11338
- let gasInfo = {};
11339
- try {
11340
- gasInfo = {
11341
- gas_consumed: toBigInt(res.fee_estimation.gas_usage),
11342
- gas_price: toBigInt(res.fee_estimation.gas_price)
11343
- };
11344
- } catch {
11345
- }
11346
- return {
11347
- trace: res.trace,
11348
- fee_estimation: {
11349
- ...gasInfo,
11350
- overall_fee: toBigInt(res.fee_estimation.overall_fee)
11351
- }
11352
- };
11454
+ errorHandler(error) {
11455
+ if (error) {
11456
+ const { code, message } = error;
11457
+ throw new LibraryError(`${code}: ${message}`);
11353
11458
  }
11354
- return {
11355
- trace: res.trace,
11356
- fee_estimation: {
11357
- overall_fee: toBigInt(res.fee_estimation.amount)
11358
- }
11359
- };
11360
11459
  }
11361
- parseCallContractResponse(res) {
11362
- return {
11363
- result: res.result
11364
- };
11460
+ async fetchEndpoint(method, params) {
11461
+ var _a;
11462
+ try {
11463
+ const rawResult = await this.fetch(method, params);
11464
+ const { error, result } = await rawResult.json();
11465
+ this.errorHandler(error);
11466
+ return result;
11467
+ } catch (error) {
11468
+ this.errorHandler((_a = error == null ? void 0 : error.response) == null ? void 0 : _a.data);
11469
+ throw error;
11470
+ }
11365
11471
  }
11366
- parseInvokeFunctionResponse(res) {
11367
- return {
11368
- transaction_hash: res.transaction_hash
11369
- };
11472
+ async getChainId() {
11473
+ this.chainId ?? (this.chainId = await this.fetchEndpoint("starknet_chainId"));
11474
+ return this.chainId;
11370
11475
  }
11371
- parseDeployContractResponse(res) {
11372
- return {
11373
- transaction_hash: res.transaction_hash,
11374
- contract_address: res.address
11375
- };
11476
+ async getBlock(blockIdentifier = this.blockIdentifier) {
11477
+ return this.getBlockWithTxHashes(blockIdentifier).then(
11478
+ this.responseParser.parseGetBlockResponse
11479
+ );
11376
11480
  }
11377
- parseDeclareContractResponse(res) {
11378
- return {
11379
- transaction_hash: res.transaction_hash,
11380
- class_hash: res.class_hash
11381
- };
11481
+ async getBlockHashAndNumber() {
11482
+ return this.fetchEndpoint("starknet_blockHashAndNumber");
11382
11483
  }
11383
- parseGetStateUpdateResponse(res) {
11384
- const nonces = Object.entries(res.state_diff.nonces).map(([contract_address, nonce]) => ({
11385
- contract_address,
11386
- nonce
11387
- }));
11388
- const storage_diffs = Object.entries(res.state_diff.storage_diffs).map(
11389
- ([address, storage_entries]) => ({ address, storage_entries })
11390
- );
11391
- return {
11392
- ...res,
11393
- state_diff: {
11394
- ...res.state_diff,
11395
- storage_diffs,
11396
- nonces
11397
- }
11398
- };
11484
+ async getBlockWithTxHashes(blockIdentifier = this.blockIdentifier) {
11485
+ const block_id = new Block(blockIdentifier).identifier;
11486
+ return this.fetchEndpoint("starknet_getBlockWithTxHashes", { block_id });
11399
11487
  }
11400
- parseSierraContractClassResponse(res) {
11401
- return {
11402
- ...res,
11403
- abi: JSON.parse(res.abi)
11404
- };
11488
+ async getBlockWithTxs(blockIdentifier = this.blockIdentifier) {
11489
+ const block_id = new Block(blockIdentifier).identifier;
11490
+ return this.fetchEndpoint("starknet_getBlockWithTxs", { block_id });
11405
11491
  }
11406
- };
11407
-
11408
- // src/utils/url.ts
11409
- var import_url_join = __toESM(require_url_join());
11410
- var protocolAndDomainRE = /^(?:\w+:)?\/\/(\S+)$/;
11411
- var localhostDomainRE = /^localhost[:?\d]*(?:[^:?\d]\S*)?$/;
11412
- var nonLocalhostDomainRE = /^[^\s.]+\.\S{2,}$/;
11413
- function isUrl(s) {
11414
- if (!s) {
11415
- return false;
11492
+ async getClassHashAt(contractAddress, blockIdentifier = this.blockIdentifier) {
11493
+ const block_id = new Block(blockIdentifier).identifier;
11494
+ return this.fetchEndpoint("starknet_getClassHashAt", {
11495
+ block_id,
11496
+ contract_address: contractAddress
11497
+ });
11416
11498
  }
11417
- if (typeof s !== "string") {
11418
- return false;
11499
+ async getNonceForAddress(contractAddress, blockIdentifier = this.blockIdentifier) {
11500
+ const block_id = new Block(blockIdentifier).identifier;
11501
+ return this.fetchEndpoint("starknet_getNonce", {
11502
+ contract_address: contractAddress,
11503
+ block_id
11504
+ });
11419
11505
  }
11420
- const match = s.match(protocolAndDomainRE);
11421
- if (!match) {
11422
- return false;
11506
+ async getPendingTransactions() {
11507
+ return this.fetchEndpoint("starknet_pendingTransactions");
11423
11508
  }
11424
- const everythingAfterProtocol = match[1];
11425
- if (!everythingAfterProtocol) {
11426
- return false;
11509
+ async getProtocolVersion() {
11510
+ throw new Error("Pathfinder does not implement this rpc 0.1.0 method");
11427
11511
  }
11428
- if (localhostDomainRE.test(everythingAfterProtocol) || nonLocalhostDomainRE.test(everythingAfterProtocol)) {
11429
- return true;
11512
+ async getStateUpdate(blockIdentifier = this.blockIdentifier) {
11513
+ const block_id = new Block(blockIdentifier).identifier;
11514
+ return this.fetchEndpoint("starknet_getStateUpdate", { block_id });
11430
11515
  }
11431
- return false;
11432
- }
11433
- function buildUrl(baseUrl, defaultPath, urlOrPath) {
11434
- return isUrl(urlOrPath) ? urlOrPath : (0, import_url_join.default)(baseUrl, urlOrPath ?? defaultPath);
11435
- }
11436
-
11437
- // src/provider/sequencer.ts
11438
- function isEmptyQueryObject(obj) {
11439
- return obj === void 0 || Object.keys(obj).length === 0 || Object.keys(obj).length === 1 && Object.entries(obj).every(([k, v]) => k === "blockIdentifier" && v === null);
11440
- }
11441
- var defaultOptions2 = {
11442
- network: "SN_GOERLI2" /* SN_GOERLI2 */,
11443
- blockIdentifier: "pending"
11444
- };
11445
- var SequencerProvider = class {
11446
- constructor(optionsOrProvider = defaultOptions2) {
11447
- this.responseParser = new SequencerAPIResponseParser();
11448
- if ("network" in optionsOrProvider) {
11449
- this.baseUrl = SequencerProvider.getNetworkFromName(optionsOrProvider.network);
11450
- this.feederGatewayUrl = buildUrl(this.baseUrl, "feeder_gateway");
11451
- this.gatewayUrl = buildUrl(this.baseUrl, "gateway");
11452
- } else {
11453
- this.baseUrl = optionsOrProvider.baseUrl;
11454
- this.feederGatewayUrl = buildUrl(
11455
- this.baseUrl,
11456
- "feeder_gateway",
11457
- optionsOrProvider.feederGatewayUrl
11458
- );
11459
- this.gatewayUrl = buildUrl(this.baseUrl, "gateway", optionsOrProvider.gatewayUrl);
11460
- }
11461
- this.chainId = (optionsOrProvider == null ? void 0 : optionsOrProvider.chainId) ?? SequencerProvider.getChainIdFromBaseUrl(this.baseUrl);
11462
- this.headers = optionsOrProvider.headers;
11463
- this.blockIdentifier = (optionsOrProvider == null ? void 0 : optionsOrProvider.blockIdentifier) || defaultOptions2.blockIdentifier;
11516
+ async getStorageAt(contractAddress, key, blockIdentifier = this.blockIdentifier) {
11517
+ const parsedKey = toHex(key);
11518
+ const block_id = new Block(blockIdentifier).identifier;
11519
+ return this.fetchEndpoint("starknet_getStorageAt", {
11520
+ contract_address: contractAddress,
11521
+ key: parsedKey,
11522
+ block_id
11523
+ });
11464
11524
  }
11465
- static getNetworkFromName(name) {
11466
- switch (name) {
11467
- case ("SN_MAIN" /* SN_MAIN */ || "0x534e5f4d41494e" /* SN_MAIN */):
11468
- return "https://alpha-mainnet.starknet.io" /* SN_MAIN */;
11469
- case ("SN_GOERLI" /* SN_GOERLI */ || "0x534e5f474f45524c49" /* SN_GOERLI */):
11470
- return "https://alpha4.starknet.io" /* SN_GOERLI */;
11471
- case ("SN_GOERLI2" /* SN_GOERLI2 */ || "0x534e5f474f45524c4932" /* SN_GOERLI2 */):
11472
- return "https://alpha4-2.starknet.io" /* SN_GOERLI2 */;
11473
- default:
11474
- throw new Error("Could not detect base url from NetworkName");
11475
- }
11525
+ async getTransaction(txHash) {
11526
+ return this.getTransactionByHash(txHash).then(this.responseParser.parseGetTransactionResponse);
11476
11527
  }
11477
- static getChainIdFromBaseUrl(baseUrl) {
11478
- try {
11479
- const url = new URL(baseUrl);
11480
- if (url.host.includes("mainnet.starknet.io")) {
11481
- return "0x534e5f4d41494e" /* SN_MAIN */;
11482
- }
11483
- if (url.host.includes("alpha4-2.starknet.io")) {
11484
- return "0x534e5f474f45524c4932" /* SN_GOERLI2 */;
11485
- }
11486
- return "0x534e5f474f45524c49" /* SN_GOERLI */;
11487
- } catch {
11488
- console.error(`Could not parse baseUrl: ${baseUrl}`);
11489
- return "0x534e5f474f45524c49" /* SN_GOERLI */;
11490
- }
11528
+ async getTransactionByHash(txHash) {
11529
+ return this.fetchEndpoint("starknet_getTransactionByHash", { transaction_hash: txHash });
11491
11530
  }
11492
- getFetchUrl(endpoint) {
11493
- const gatewayUrlEndpoints = ["add_transaction"];
11494
- return gatewayUrlEndpoints.includes(endpoint) ? this.gatewayUrl : this.feederGatewayUrl;
11531
+ async getTransactionByBlockIdAndIndex(blockIdentifier, index) {
11532
+ const block_id = new Block(blockIdentifier).identifier;
11533
+ return this.fetchEndpoint("starknet_getTransactionByBlockIdAndIndex", { block_id, index });
11495
11534
  }
11496
- getFetchMethod(endpoint) {
11497
- const postMethodEndpoints = [
11498
- "add_transaction",
11499
- "call_contract",
11500
- "estimate_fee",
11501
- "estimate_message_fee",
11502
- "estimate_fee_bulk",
11503
- "simulate_transaction"
11504
- ];
11505
- return postMethodEndpoints.includes(endpoint) ? "POST" : "GET";
11535
+ async getTransactionReceipt(txHash) {
11536
+ return this.fetchEndpoint("starknet_getTransactionReceipt", { transaction_hash: txHash });
11506
11537
  }
11507
- getQueryString(query) {
11508
- if (isEmptyQueryObject(query)) {
11509
- return "";
11510
- }
11511
- const queryString = Object.entries(query).map(([key, value]) => {
11512
- if (key === "blockIdentifier") {
11513
- const block = new Block(value);
11514
- return `${block.queryIdentifier}`;
11515
- }
11516
- return `${key}=${value}`;
11517
- }).join("&");
11518
- return `?${queryString}`;
11538
+ async getClassByHash(classHash) {
11539
+ return this.getClass(classHash);
11519
11540
  }
11520
- getHeaders(method) {
11521
- if (method === "POST") {
11522
- return {
11523
- "Content-Type": "application/json",
11524
- ...this.headers
11525
- };
11526
- }
11527
- return this.headers;
11541
+ async getClass(classHash, blockIdentifier = this.blockIdentifier) {
11542
+ const block_id = new Block(blockIdentifier).identifier;
11543
+ return this.fetchEndpoint("starknet_getClass", { class_hash: classHash, block_id });
11528
11544
  }
11529
- async fetchEndpoint(endpoint, ...[query, request]) {
11530
- const baseUrl = this.getFetchUrl(endpoint);
11531
- const method = this.getFetchMethod(endpoint);
11532
- const queryString = this.getQueryString(query);
11533
- const url = (0, import_url_join2.default)(baseUrl, endpoint, queryString);
11534
- return this.fetch(url, {
11535
- method,
11536
- body: request
11545
+ async getClassAt(contractAddress, blockIdentifier = this.blockIdentifier) {
11546
+ const block_id = new Block(blockIdentifier).identifier;
11547
+ return this.fetchEndpoint("starknet_getClassAt", {
11548
+ block_id,
11549
+ contract_address: contractAddress
11537
11550
  });
11538
11551
  }
11539
- async fetch(endpoint, options) {
11540
- const url = buildUrl(this.baseUrl, "", endpoint);
11541
- const method = (options == null ? void 0 : options.method) ?? "GET";
11542
- const headers = this.getHeaders(method);
11543
- const body = stringify2(options == null ? void 0 : options.body);
11544
- try {
11545
- const response = await fetchPonyfill_default(url, {
11546
- method,
11547
- body,
11548
- headers
11549
- });
11550
- const textResponse = await response.text();
11551
- if (!response.ok) {
11552
- let responseBody;
11553
- try {
11554
- responseBody = parse2(textResponse);
11555
- } catch {
11556
- throw new HttpError(response.statusText, response.status);
11557
- }
11558
- throw new GatewayError(responseBody.message, responseBody.code);
11559
- }
11560
- const parseChoice = (options == null ? void 0 : options.parseAlwaysAsBigInt) ? parseAlwaysAsBig : parse2;
11561
- return parseChoice(textResponse);
11562
- } catch (error) {
11563
- if (error instanceof Error && !(error instanceof LibraryError))
11564
- throw Error(`Could not ${method} from endpoint \`${url}\`: ${error.message}`);
11565
- throw error;
11566
- }
11567
- }
11568
- async getChainId() {
11569
- return Promise.resolve(this.chainId);
11570
- }
11571
- async callContract({ contractAddress, entrypoint: entryPointSelector, calldata = [] }, blockIdentifier = this.blockIdentifier) {
11572
- return this.fetchEndpoint(
11573
- "call_contract",
11574
- { blockIdentifier },
11575
- {
11576
- contract_address: contractAddress,
11577
- entry_point_selector: getSelectorFromName(entryPointSelector),
11578
- calldata
11579
- }
11580
- ).then(this.responseParser.parseCallContractResponse);
11552
+ async getCode(_contractAddress, _blockIdentifier) {
11553
+ throw new Error("RPC does not implement getCode function");
11581
11554
  }
11582
- async getBlock(blockIdentifier = this.blockIdentifier) {
11583
- return this.fetchEndpoint("get_block", { blockIdentifier }).then(
11584
- this.responseParser.parseGetBlockResponse
11585
- );
11555
+ async getEstimateFee(invocation, invocationDetails, blockIdentifier = this.blockIdentifier) {
11556
+ return this.getInvokeEstimateFee(invocation, invocationDetails, blockIdentifier);
11586
11557
  }
11587
- async getNonceForAddress(contractAddress, blockIdentifier = this.blockIdentifier) {
11588
- return this.fetchEndpoint("get_nonce", { contractAddress, blockIdentifier });
11558
+ async getInvokeEstimateFee(invocation, invocationDetails, blockIdentifier = this.blockIdentifier) {
11559
+ const block_id = new Block(blockIdentifier).identifier;
11560
+ return this.fetchEndpoint("starknet_estimateFee", {
11561
+ request: {
11562
+ type: RPC.TransactionType.INVOKE,
11563
+ sender_address: invocation.contractAddress,
11564
+ calldata: parseCalldata(invocation.calldata),
11565
+ signature: signatureToHexArray(invocation.signature),
11566
+ version: toHex((invocationDetails == null ? void 0 : invocationDetails.version) || 0),
11567
+ nonce: toHex(invocationDetails.nonce),
11568
+ max_fee: toHex((invocationDetails == null ? void 0 : invocationDetails.maxFee) || 0)
11569
+ },
11570
+ block_id
11571
+ }).then(this.responseParser.parseFeeEstimateResponse);
11589
11572
  }
11590
- async getStorageAt(contractAddress, key, blockIdentifier = this.blockIdentifier) {
11591
- const parsedKey = toBigInt(key).toString(10);
11592
- return this.fetchEndpoint("get_storage_at", {
11593
- blockIdentifier,
11594
- contractAddress,
11595
- key: parsedKey
11596
- });
11597
- }
11598
- async getTransaction(txHash) {
11599
- const txHashHex = toHex(txHash);
11600
- return this.fetchEndpoint("get_transaction", { transactionHash: txHashHex }).then((result) => {
11601
- if (Object.values(result).length === 1)
11602
- throw new LibraryError(result.status);
11603
- return this.responseParser.parseGetTransactionResponse(result);
11604
- });
11605
- }
11606
- async getTransactionReceipt(txHash) {
11607
- const txHashHex = toHex(txHash);
11608
- return this.fetchEndpoint("get_transaction_receipt", { transactionHash: txHashHex }).then(
11609
- this.responseParser.parseGetTransactionReceiptResponse
11610
- );
11611
- }
11612
- async getClassAt(contractAddress, blockIdentifier = this.blockIdentifier) {
11613
- return this.fetchEndpoint("get_full_contract", { blockIdentifier, contractAddress }).then(
11614
- (res) => {
11615
- if (isSierra(res)) {
11616
- return this.responseParser.parseSierraContractClassResponse(res);
11617
- }
11618
- return parseContract(res);
11619
- }
11620
- );
11621
- }
11622
- async getClassHashAt(contractAddress, blockIdentifier = this.blockIdentifier) {
11623
- return this.fetchEndpoint("get_class_hash_at", { blockIdentifier, contractAddress });
11624
- }
11625
- async getClassByHash(classHash, blockIdentifier = this.blockIdentifier) {
11626
- return this.fetchEndpoint("get_class_by_hash", { classHash, blockIdentifier }).then((res) => {
11627
- if (isSierra(res)) {
11628
- return this.responseParser.parseSierraContractClassResponse(res);
11629
- }
11630
- return parseContract(res);
11631
- });
11632
- }
11633
- async getCompiledClassByClassHash(classHash, blockIdentifier = this.blockIdentifier) {
11634
- return this.fetchEndpoint("get_compiled_class_by_class_hash", { classHash, blockIdentifier });
11635
- }
11636
- async invokeFunction(functionInvocation, details) {
11637
- return this.fetchEndpoint("add_transaction", void 0, {
11638
- type: "INVOKE_FUNCTION" /* INVOKE */,
11639
- sender_address: functionInvocation.contractAddress,
11640
- calldata: bigNumberishArrayToDecimalStringArray(functionInvocation.calldata ?? []),
11641
- signature: signatureToDecimalArray(functionInvocation.signature),
11642
- nonce: toHex(details.nonce),
11643
- max_fee: toHex(details.maxFee || 0),
11644
- version: "0x1"
11645
- }).then(this.responseParser.parseInvokeFunctionResponse);
11646
- }
11647
- async deployAccountContract({ classHash, constructorCalldata, addressSalt, signature }, details) {
11648
- return this.fetchEndpoint("add_transaction", void 0, {
11649
- type: "DEPLOY_ACCOUNT" /* DEPLOY_ACCOUNT */,
11650
- contract_address_salt: addressSalt ?? randomAddress(),
11651
- constructor_calldata: bigNumberishArrayToDecimalStringArray(constructorCalldata ?? []),
11652
- class_hash: toHex(classHash),
11653
- max_fee: toHex(details.maxFee || 0),
11654
- version: toHex(details.version || 0),
11655
- nonce: toHex(details.nonce),
11656
- signature: signatureToDecimalArray(signature)
11657
- }).then(this.responseParser.parseDeployContractResponse);
11658
- }
11659
- async declareContract({ senderAddress, contractDefinition, signature, compiledClassHash }, details) {
11660
- if (!isSierra(contractDefinition)) {
11661
- return this.fetchEndpoint("add_transaction", void 0, {
11662
- type: "DECLARE" /* DECLARE */,
11663
- contract_class: contractDefinition,
11664
- nonce: toHex(details.nonce),
11665
- signature: signatureToDecimalArray(signature),
11666
- sender_address: senderAddress,
11667
- max_fee: toHex(details.maxFee || 0),
11668
- version: "0x1"
11669
- }).then(this.responseParser.parseDeclareContractResponse);
11573
+ async getDeclareEstimateFee({ senderAddress, contractDefinition, signature }, details, blockIdentifier = this.blockIdentifier) {
11574
+ const block_id = new Block(blockIdentifier).identifier;
11575
+ if ("program" in contractDefinition) {
11576
+ return this.fetchEndpoint("starknet_estimateFee", {
11577
+ request: {
11578
+ type: RPC.TransactionType.DECLARE,
11579
+ contract_class: {
11580
+ program: contractDefinition.program,
11581
+ entry_points_by_type: contractDefinition.entry_points_by_type,
11582
+ abi: contractDefinition.abi
11583
+ },
11584
+ sender_address: senderAddress,
11585
+ signature: signatureToHexArray(signature),
11586
+ version: toHex((details == null ? void 0 : details.version) || 0),
11587
+ nonce: toHex(details.nonce),
11588
+ max_fee: toHex((details == null ? void 0 : details.maxFee) || 0)
11589
+ },
11590
+ block_id
11591
+ }).then(this.responseParser.parseFeeEstimateResponse);
11670
11592
  }
11671
- return this.fetchEndpoint("add_transaction", void 0, {
11672
- type: "DECLARE" /* DECLARE */,
11673
- sender_address: senderAddress,
11674
- compiled_class_hash: compiledClassHash,
11675
- contract_class: contractDefinition,
11676
- nonce: toHex(details.nonce),
11677
- signature: signatureToDecimalArray(signature),
11678
- max_fee: toHex(details.maxFee || 0),
11679
- version: "0x2"
11680
- }).then(this.responseParser.parseDeclareContractResponse);
11593
+ throw new Error("RPC do not support Sierra Contracts yet");
11681
11594
  }
11682
- async getEstimateFee(invocation, invocationDetails, blockIdentifier = this.blockIdentifier, skipValidate = false) {
11683
- return this.getInvokeEstimateFee(invocation, invocationDetails, blockIdentifier, skipValidate);
11595
+ async getDeployAccountEstimateFee({ classHash, constructorCalldata, addressSalt, signature }, details, blockIdentifier = this.blockIdentifier) {
11596
+ const block_id = new Block(blockIdentifier).identifier;
11597
+ return this.fetchEndpoint("starknet_estimateFee", {
11598
+ request: {
11599
+ type: RPC.TransactionType.DEPLOY_ACCOUNT,
11600
+ constructor_calldata: bigNumberishArrayToHexadecimalStringArray(constructorCalldata || []),
11601
+ class_hash: toHex(classHash),
11602
+ contract_address_salt: toHex(addressSalt || 0),
11603
+ signature: signatureToHexArray(signature),
11604
+ version: toHex((details == null ? void 0 : details.version) || 0),
11605
+ nonce: toHex(details.nonce),
11606
+ max_fee: toHex((details == null ? void 0 : details.maxFee) || 0)
11607
+ },
11608
+ block_id
11609
+ }).then(this.responseParser.parseFeeEstimateResponse);
11684
11610
  }
11685
- async getInvokeEstimateFee(invocation, invocationDetails, blockIdentifier = this.blockIdentifier, skipValidate = false) {
11686
- return this.fetchEndpoint(
11687
- "estimate_fee",
11688
- { blockIdentifier, skipValidate },
11689
- {
11690
- type: "INVOKE_FUNCTION" /* INVOKE */,
11691
- sender_address: invocation.contractAddress,
11692
- calldata: invocation.calldata ?? [],
11693
- signature: signatureToDecimalArray(invocation.signature),
11694
- version: toHex((invocationDetails == null ? void 0 : invocationDetails.version) || 1),
11695
- nonce: toHex(invocationDetails.nonce)
11696
- }
11697
- ).then(this.responseParser.parseFeeEstimateResponse);
11611
+ async getEstimateFeeBulk(_invocations, _blockIdentifier = this.blockIdentifier) {
11612
+ throw new Error("RPC does not implement getInvokeEstimateFeeBulk function");
11698
11613
  }
11699
- async getDeclareEstimateFee({ senderAddress, contractDefinition, signature, compiledClassHash }, details, blockIdentifier = this.blockIdentifier, skipValidate = false) {
11700
- if (!isSierra(contractDefinition)) {
11701
- return this.fetchEndpoint(
11702
- "estimate_fee",
11703
- { blockIdentifier, skipValidate },
11704
- {
11705
- type: "DECLARE" /* DECLARE */,
11614
+ async declareContract({ contractDefinition, signature, senderAddress }, details) {
11615
+ if ("program" in contractDefinition) {
11616
+ return this.fetchEndpoint("starknet_addDeclareTransaction", {
11617
+ declare_transaction: {
11618
+ contract_class: {
11619
+ program: contractDefinition.program,
11620
+ entry_points_by_type: contractDefinition.entry_points_by_type,
11621
+ abi: contractDefinition.abi
11622
+ },
11623
+ type: RPC.TransactionType.DECLARE,
11624
+ version: "0x1",
11625
+ max_fee: toHex(details.maxFee || 0),
11626
+ signature: signatureToHexArray(signature),
11706
11627
  sender_address: senderAddress,
11707
- contract_class: contractDefinition,
11708
- signature: signatureToDecimalArray(signature),
11709
- version: toHex((details == null ? void 0 : details.version) || toBigInt(feeTransactionVersion)),
11710
11628
  nonce: toHex(details.nonce)
11711
11629
  }
11712
- ).then(this.responseParser.parseFeeEstimateResponse);
11630
+ });
11713
11631
  }
11714
- return this.fetchEndpoint(
11715
- "estimate_fee",
11716
- { blockIdentifier, skipValidate },
11717
- {
11718
- type: "DECLARE" /* DECLARE */,
11719
- sender_address: senderAddress,
11720
- compiled_class_hash: compiledClassHash,
11721
- contract_class: contractDefinition,
11722
- nonce: toHex(details.nonce),
11723
- signature: signatureToDecimalArray(signature),
11724
- version: "0x2"
11725
- }
11726
- ).then(this.responseParser.parseFeeEstimateResponse);
11632
+ throw new Error("RPC do not support Sierra Contracts yet");
11727
11633
  }
11728
- async getDeployAccountEstimateFee({ classHash, addressSalt, constructorCalldata, signature }, details, blockIdentifier = this.blockIdentifier, skipValidate = false) {
11729
- return this.fetchEndpoint(
11730
- "estimate_fee",
11731
- { blockIdentifier, skipValidate },
11732
- {
11733
- type: "DEPLOY_ACCOUNT" /* DEPLOY_ACCOUNT */,
11634
+ async deployAccountContract({ classHash, constructorCalldata, addressSalt, signature }, details) {
11635
+ return this.fetchEndpoint("starknet_addDeployAccountTransaction", {
11636
+ deploy_account_transaction: {
11637
+ constructor_calldata: bigNumberishArrayToHexadecimalStringArray(constructorCalldata || []),
11734
11638
  class_hash: toHex(classHash),
11735
- constructor_calldata: bigNumberishArrayToDecimalStringArray(constructorCalldata || []),
11736
11639
  contract_address_salt: toHex(addressSalt || 0),
11737
- signature: signatureToDecimalArray(signature),
11738
- version: toHex((details == null ? void 0 : details.version) || 0),
11640
+ type: RPC.TransactionType.DEPLOY_ACCOUNT,
11641
+ max_fee: toHex(details.maxFee || 0),
11642
+ version: toHex(details.version || 0),
11643
+ signature: signatureToHexArray(signature),
11739
11644
  nonce: toHex(details.nonce)
11740
11645
  }
11741
- ).then(this.responseParser.parseFeeEstimateResponse);
11646
+ });
11742
11647
  }
11743
- async getEstimateFeeBulk(invocations, blockIdentifier = this.blockIdentifier) {
11744
- const params = invocations.map((invocation) => {
11745
- let res;
11746
- if (invocation.type === "INVOKE_FUNCTION") {
11747
- res = {
11748
- type: invocation.type,
11749
- sender_address: invocation.contractAddress,
11750
- calldata: invocation.calldata ?? []
11751
- };
11752
- } else if (invocation.type === "DECLARE") {
11753
- res = {
11754
- type: invocation.type,
11755
- sender_address: invocation.senderAddress,
11756
- contract_class: invocation.contractDefinition
11757
- };
11758
- } else {
11759
- res = {
11760
- type: invocation.type,
11761
- class_hash: toHex(toBigInt(invocation.classHash)),
11762
- constructor_calldata: bigNumberishArrayToDecimalStringArray(
11763
- invocation.constructorCalldata || []
11764
- ),
11765
- contract_address_salt: toHex(toBigInt(invocation.addressSalt || 0))
11766
- };
11648
+ async invokeFunction(functionInvocation, details) {
11649
+ return this.fetchEndpoint("starknet_addInvokeTransaction", {
11650
+ invoke_transaction: {
11651
+ sender_address: functionInvocation.contractAddress,
11652
+ calldata: parseCalldata(functionInvocation.calldata),
11653
+ type: RPC.TransactionType.INVOKE,
11654
+ max_fee: toHex(details.maxFee || 0),
11655
+ version: "0x1",
11656
+ signature: signatureToHexArray(functionInvocation.signature),
11657
+ nonce: toHex(details.nonce)
11767
11658
  }
11768
- return {
11769
- ...res,
11770
- signature: bigNumberishArrayToDecimalStringArray(formatSignature(invocation.signature)),
11771
- version: toHex(toBigInt((invocation == null ? void 0 : invocation.version) || 1)),
11772
- nonce: toHex(toBigInt(invocation.nonce))
11773
- };
11774
11659
  });
11775
- return this.fetchEndpoint("estimate_fee_bulk", { blockIdentifier }, params).then(
11776
- this.responseParser.parseFeeEstimateBulkResponse
11777
- );
11778
11660
  }
11779
- async getCode(contractAddress, blockIdentifier = this.blockIdentifier) {
11780
- return this.fetchEndpoint("get_code", { contractAddress, blockIdentifier });
11661
+ async callContract(call, blockIdentifier = this.blockIdentifier) {
11662
+ const block_id = new Block(blockIdentifier).identifier;
11663
+ const result = await this.fetchEndpoint("starknet_call", {
11664
+ request: {
11665
+ contract_address: call.contractAddress,
11666
+ entry_point_selector: getSelectorFromName(call.entrypoint),
11667
+ calldata: parseCalldata(call.calldata)
11668
+ },
11669
+ block_id
11670
+ });
11671
+ return this.responseParser.parseCallContractResponse(result);
11781
11672
  }
11782
- async waitForTransaction(txHash, options) {
11673
+ async traceTransaction(transactionHash) {
11674
+ return this.fetchEndpoint("starknet_traceTransaction", { transaction_hash: transactionHash });
11675
+ }
11676
+ async traceBlockTransactions(blockHash) {
11677
+ return this.fetchEndpoint("starknet_traceBlockTransactions", { block_hash: blockHash });
11678
+ }
11679
+ async waitForTransaction(txHash, options) {
11783
11680
  const errorStates = ["REJECTED" /* REJECTED */, "NOT_RECEIVED" /* NOT_RECEIVED */];
11681
+ let { retries } = this;
11784
11682
  let onchain = false;
11785
- let res;
11683
+ let txReceipt = {};
11786
11684
  const retryInterval = (options == null ? void 0 : options.retryInterval) ?? 8e3;
11787
11685
  const successStates = (options == null ? void 0 : options.successStates) ?? [
11788
11686
  "ACCEPTED_ON_L1" /* ACCEPTED_ON_L1 */,
@@ -11791,64 +11689,48 @@ var starknet = (() => {
11791
11689
  ];
11792
11690
  while (!onchain) {
11793
11691
  await wait(retryInterval);
11794
- res = await this.getTransactionStatus(txHash);
11795
- if (successStates.includes(res.tx_status)) {
11796
- onchain = true;
11797
- } else if (errorStates.includes(res.tx_status)) {
11798
- const message = res.tx_failure_reason ? `${res.tx_status}: ${res.tx_failure_reason.code}
11799
- ${res.tx_failure_reason.error_message}` : res.tx_status;
11800
- const error = new Error(message);
11801
- error.response = res;
11802
- throw error;
11692
+ try {
11693
+ txReceipt = await this.getTransactionReceipt(txHash);
11694
+ if (!("status" in txReceipt)) {
11695
+ const error = new Error("pending transaction");
11696
+ throw error;
11697
+ }
11698
+ if (txReceipt.status && successStates.includes(txReceipt.status)) {
11699
+ onchain = true;
11700
+ } else if (txReceipt.status && errorStates.includes(txReceipt.status)) {
11701
+ const message = txReceipt.status;
11702
+ const error = new Error(message);
11703
+ error.response = txReceipt;
11704
+ throw error;
11705
+ }
11706
+ } catch (error) {
11707
+ if (error instanceof Error && errorStates.includes(error.message)) {
11708
+ throw error;
11709
+ }
11710
+ if (retries === 0) {
11711
+ throw new Error(`waitForTransaction timed-out with retries ${this.retries}`);
11712
+ }
11803
11713
  }
11714
+ retries -= 1;
11804
11715
  }
11805
- const txReceipt = await this.getTransactionReceipt(txHash);
11716
+ await wait(retryInterval);
11806
11717
  return txReceipt;
11807
11718
  }
11808
- async getTransactionStatus(txHash) {
11809
- const txHashHex = toHex(txHash);
11810
- return this.fetchEndpoint("get_transaction_status", { transactionHash: txHashHex });
11811
- }
11812
- async getContractAddresses() {
11813
- return this.fetchEndpoint("get_contract_addresses");
11814
- }
11815
- async getTransactionTrace(txHash) {
11816
- const txHashHex = toHex(txHash);
11817
- return this.fetchEndpoint("get_transaction_trace", { transactionHash: txHashHex });
11719
+ async getTransactionCount(blockIdentifier = this.blockIdentifier) {
11720
+ const block_id = new Block(blockIdentifier).identifier;
11721
+ return this.fetchEndpoint("starknet_getBlockTransactionCount", { block_id });
11818
11722
  }
11819
- async estimateMessageFee({ from_address, to_address, entry_point_selector, payload }, blockIdentifier = this.blockIdentifier) {
11820
- const validCallL1Handler = {
11821
- from_address: getDecimalString(from_address),
11822
- to_address: getHexString(to_address),
11823
- entry_point_selector: getSelector(entry_point_selector),
11824
- payload: getHexStringArray(payload)
11825
- };
11826
- return this.fetchEndpoint("estimate_message_fee", { blockIdentifier }, validCallL1Handler);
11723
+ async getBlockNumber() {
11724
+ return this.fetchEndpoint("starknet_blockNumber");
11827
11725
  }
11828
- async getSimulateTransaction(invocation, invocationDetails, blockIdentifier = this.blockIdentifier, skipValidate = false) {
11829
- return this.fetchEndpoint(
11830
- "simulate_transaction",
11831
- { blockIdentifier, skipValidate },
11832
- {
11833
- type: "INVOKE_FUNCTION",
11834
- sender_address: invocation.contractAddress,
11835
- calldata: invocation.calldata ?? [],
11836
- signature: signatureToDecimalArray(invocation.signature),
11837
- version: toHex((invocationDetails == null ? void 0 : invocationDetails.version) || 1),
11838
- nonce: toHex(invocationDetails.nonce),
11839
- max_fee: toHex((invocationDetails == null ? void 0 : invocationDetails.maxFee) || 0)
11840
- }
11841
- ).then(this.responseParser.parseFeeSimulateTransactionResponse);
11726
+ async getSyncingStats() {
11727
+ return this.fetchEndpoint("starknet_syncing");
11842
11728
  }
11843
- async getStateUpdate(blockIdentifier = this.blockIdentifier) {
11844
- const args = new Block(blockIdentifier).sequencerIdentifier;
11845
- return this.fetchEndpoint("get_state_update", { ...args }).then(
11846
- this.responseParser.parseGetStateUpdateResponse
11847
- );
11729
+ async getEvents(eventFilter) {
11730
+ return this.fetchEndpoint("starknet_getEvents", { filter: eventFilter });
11848
11731
  }
11849
- async getBlockTraces(blockIdentifier = this.blockIdentifier) {
11850
- const args = new Block(blockIdentifier).sequencerIdentifier;
11851
- return this.fetchEndpoint("get_block_traces", { ...args });
11732
+ async getSimulateTransaction(_invocation, _invocationDetails, _blockIdentifier) {
11733
+ throw new Error("RPC does not implement simulateTransaction function");
11852
11734
  }
11853
11735
  async getStarkName(address, StarknetIdContract2) {
11854
11736
  return getStarkName(this, address, StarknetIdContract2);
@@ -11858,622 +11740,732 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
11858
11740
  }
11859
11741
  };
11860
11742
 
11861
- // src/provider/default.ts
11862
- var Provider = class {
11863
- constructor(providerOrOptions) {
11864
- if (providerOrOptions instanceof Provider) {
11865
- this.provider = providerOrOptions.provider;
11866
- } else if (providerOrOptions instanceof RpcProvider || providerOrOptions instanceof SequencerProvider) {
11867
- this.provider = providerOrOptions;
11868
- } else if (providerOrOptions && "rpc" in providerOrOptions) {
11869
- this.provider = new RpcProvider(providerOrOptions.rpc);
11870
- } else if (providerOrOptions && "sequencer" in providerOrOptions) {
11871
- this.provider = new SequencerProvider(providerOrOptions.sequencer);
11872
- } else {
11873
- this.provider = new SequencerProvider();
11874
- }
11875
- }
11876
- async getChainId() {
11877
- return this.provider.getChainId();
11743
+ // src/provider/sequencer.ts
11744
+ var import_url_join2 = __toESM(require_url_join());
11745
+
11746
+ // src/utils/responseParser/index.ts
11747
+ var ResponseParser = class {
11748
+ };
11749
+
11750
+ // src/utils/responseParser/sequencer.ts
11751
+ var SequencerAPIResponseParser = class extends ResponseParser {
11752
+ parseGetBlockResponse(res) {
11753
+ return {
11754
+ ...res,
11755
+ new_root: res.state_root,
11756
+ parent_hash: res.parent_block_hash,
11757
+ transactions: Object.values(res.transactions).map((value) => "transaction_hash" in value && value.transaction_hash).filter(Boolean)
11758
+ };
11878
11759
  }
11879
- async getBlock(blockIdentifier) {
11880
- return this.provider.getBlock(blockIdentifier);
11760
+ parseGetTransactionResponse(res) {
11761
+ return {
11762
+ ...res,
11763
+ calldata: "calldata" in res.transaction ? res.transaction.calldata : [],
11764
+ contract_class: "contract_class" in res.transaction ? res.transaction.contract_class : void 0,
11765
+ entry_point_selector: "entry_point_selector" in res.transaction ? res.transaction.entry_point_selector : void 0,
11766
+ max_fee: "max_fee" in res.transaction ? res.transaction.max_fee : void 0,
11767
+ nonce: res.transaction.nonce,
11768
+ sender_address: "sender_address" in res.transaction ? res.transaction.sender_address : void 0,
11769
+ signature: "signature" in res.transaction ? res.transaction.signature : void 0,
11770
+ transaction_hash: "transaction_hash" in res.transaction ? res.transaction.transaction_hash : void 0,
11771
+ version: "version" in res.transaction ? res.transaction.version : void 0
11772
+ };
11881
11773
  }
11882
- async getClassAt(contractAddress, blockIdentifier) {
11883
- return this.provider.getClassAt(contractAddress, blockIdentifier);
11774
+ parseGetTransactionReceiptResponse(res) {
11775
+ return {
11776
+ transaction_hash: res.transaction_hash,
11777
+ status: res.status,
11778
+ messages_sent: res.l2_to_l1_messages,
11779
+ events: res.events,
11780
+ ..."block_hash" in res && { block_hash: res.block_hash },
11781
+ ..."block_number" in res && { block_number: res.block_number },
11782
+ ..."actual_fee" in res && { actual_fee: res.actual_fee },
11783
+ ..."transaction_index" in res && { transaction_index: res.transaction_index },
11784
+ ..."execution_resources" in res && { execution_resources: res.execution_resources },
11785
+ ..."l1_to_l2_consumed_message" in res && {
11786
+ l1_to_l2_consumed_message: res["l1_to_l2_consumed_message"]
11787
+ },
11788
+ ..."transaction_failure_reason" in res && {
11789
+ transaction_failure_reason: res.transaction_failure_reason
11790
+ }
11791
+ };
11884
11792
  }
11885
- async getClassHashAt(contractAddress, blockIdentifier) {
11886
- return this.provider.getClassHashAt(contractAddress, blockIdentifier);
11793
+ parseFeeEstimateResponse(res) {
11794
+ if ("overall_fee" in res) {
11795
+ let gasInfo = {};
11796
+ try {
11797
+ gasInfo = {
11798
+ gas_consumed: toBigInt(res.gas_usage),
11799
+ gas_price: toBigInt(res.gas_price)
11800
+ };
11801
+ } catch {
11802
+ }
11803
+ return {
11804
+ overall_fee: toBigInt(res.overall_fee),
11805
+ ...gasInfo
11806
+ };
11807
+ }
11808
+ return {
11809
+ overall_fee: toBigInt(res.amount)
11810
+ };
11887
11811
  }
11888
- getClassByHash(classHash) {
11889
- return this.provider.getClassByHash(classHash);
11812
+ parseFeeEstimateBulkResponse(res) {
11813
+ return [].concat(res).map((item) => {
11814
+ if ("overall_fee" in item) {
11815
+ let gasInfo = {};
11816
+ try {
11817
+ gasInfo = {
11818
+ gas_consumed: toBigInt(item.gas_usage),
11819
+ gas_price: toBigInt(item.gas_price)
11820
+ };
11821
+ } catch {
11822
+ }
11823
+ return {
11824
+ overall_fee: toBigInt(item.overall_fee),
11825
+ ...gasInfo
11826
+ };
11827
+ }
11828
+ return {
11829
+ overall_fee: toBigInt(item.amount)
11830
+ };
11831
+ });
11890
11832
  }
11891
- async getEstimateFee(invocationWithTxType, invocationDetails, blockIdentifier) {
11892
- return this.provider.getEstimateFee(invocationWithTxType, invocationDetails, blockIdentifier);
11833
+ parseFeeSimulateTransactionResponse(res) {
11834
+ if ("overall_fee" in res.fee_estimation) {
11835
+ let gasInfo = {};
11836
+ try {
11837
+ gasInfo = {
11838
+ gas_consumed: toBigInt(res.fee_estimation.gas_usage),
11839
+ gas_price: toBigInt(res.fee_estimation.gas_price)
11840
+ };
11841
+ } catch {
11842
+ }
11843
+ return {
11844
+ trace: res.trace,
11845
+ fee_estimation: {
11846
+ ...gasInfo,
11847
+ overall_fee: toBigInt(res.fee_estimation.overall_fee)
11848
+ }
11849
+ };
11850
+ }
11851
+ return {
11852
+ trace: res.trace,
11853
+ fee_estimation: {
11854
+ overall_fee: toBigInt(res.fee_estimation.amount)
11855
+ }
11856
+ };
11893
11857
  }
11894
- async getInvokeEstimateFee(invocationWithTxType, invocationDetails, blockIdentifier, skipValidate) {
11895
- return this.provider.getInvokeEstimateFee(
11896
- invocationWithTxType,
11897
- invocationDetails,
11898
- blockIdentifier,
11899
- skipValidate
11900
- );
11858
+ parseCallContractResponse(res) {
11859
+ return {
11860
+ result: res.result
11861
+ };
11901
11862
  }
11902
- async getEstimateFeeBulk(invocations, blockIdentifier) {
11903
- return this.provider.getEstimateFeeBulk(invocations, blockIdentifier);
11863
+ parseInvokeFunctionResponse(res) {
11864
+ return {
11865
+ transaction_hash: res.transaction_hash
11866
+ };
11904
11867
  }
11905
- async getNonceForAddress(contractAddress, blockIdentifier) {
11906
- return this.provider.getNonceForAddress(contractAddress, blockIdentifier);
11868
+ parseDeployContractResponse(res) {
11869
+ return {
11870
+ transaction_hash: res.transaction_hash,
11871
+ contract_address: res.address
11872
+ };
11907
11873
  }
11908
- async getStorageAt(contractAddress, key, blockIdentifier) {
11909
- return this.provider.getStorageAt(contractAddress, key, blockIdentifier);
11910
- }
11911
- async getTransaction(txHash) {
11912
- return this.provider.getTransaction(txHash);
11913
- }
11914
- async getTransactionReceipt(txHash) {
11915
- return this.provider.getTransactionReceipt(txHash);
11916
- }
11917
- async callContract(request, blockIdentifier) {
11918
- return this.provider.callContract(request, blockIdentifier);
11919
- }
11920
- async invokeFunction(functionInvocation, details) {
11921
- return this.provider.invokeFunction(functionInvocation, details);
11922
- }
11923
- async deployAccountContract(payload, details) {
11924
- return this.provider.deployAccountContract(payload, details);
11925
- }
11926
- async declareContract(transaction, details) {
11927
- return this.provider.declareContract(transaction, details);
11928
- }
11929
- async getDeclareEstimateFee(transaction, details, blockIdentifier, skipValidate) {
11930
- return this.provider.getDeclareEstimateFee(transaction, details, blockIdentifier, skipValidate);
11874
+ parseDeclareContractResponse(res) {
11875
+ return {
11876
+ transaction_hash: res.transaction_hash,
11877
+ class_hash: res.class_hash
11878
+ };
11931
11879
  }
11932
- getDeployAccountEstimateFee(transaction, details, blockIdentifier, skipValidate) {
11933
- return this.provider.getDeployAccountEstimateFee(
11934
- transaction,
11935
- details,
11936
- blockIdentifier,
11937
- skipValidate
11880
+ parseGetStateUpdateResponse(res) {
11881
+ const nonces = Object.entries(res.state_diff.nonces).map(([contract_address, nonce]) => ({
11882
+ contract_address,
11883
+ nonce
11884
+ }));
11885
+ const storage_diffs = Object.entries(res.state_diff.storage_diffs).map(
11886
+ ([address, storage_entries]) => ({ address, storage_entries })
11938
11887
  );
11888
+ return {
11889
+ ...res,
11890
+ state_diff: {
11891
+ ...res.state_diff,
11892
+ storage_diffs,
11893
+ nonces
11894
+ }
11895
+ };
11939
11896
  }
11940
- async getCode(contractAddress, blockIdentifier) {
11941
- return this.provider.getCode(contractAddress, blockIdentifier);
11897
+ parseSierraContractClassResponse(res) {
11898
+ return {
11899
+ ...res,
11900
+ abi: JSON.parse(res.abi)
11901
+ };
11942
11902
  }
11943
- async waitForTransaction(txHash, options) {
11944
- return this.provider.waitForTransaction(txHash, options);
11903
+ };
11904
+
11905
+ // src/utils/url.ts
11906
+ var import_url_join = __toESM(require_url_join());
11907
+ var protocolAndDomainRE = /^(?:\w+:)?\/\/(\S+)$/;
11908
+ var localhostDomainRE = /^localhost[:?\d]*(?:[^:?\d]\S*)?$/;
11909
+ var nonLocalhostDomainRE = /^[^\s.]+\.\S{2,}$/;
11910
+ function isUrl(s) {
11911
+ if (!s) {
11912
+ return false;
11945
11913
  }
11946
- async getSimulateTransaction(invocation, invocationDetails, blockIdentifier, skipValidate) {
11947
- return this.provider.getSimulateTransaction(
11948
- invocation,
11949
- invocationDetails,
11950
- blockIdentifier,
11951
- skipValidate
11952
- );
11914
+ if (typeof s !== "string") {
11915
+ return false;
11953
11916
  }
11954
- async getStateUpdate(blockIdentifier) {
11955
- return this.provider.getStateUpdate(blockIdentifier);
11917
+ const match = s.match(protocolAndDomainRE);
11918
+ if (!match) {
11919
+ return false;
11956
11920
  }
11957
- async getStarkName(address, StarknetIdContract2) {
11958
- return getStarkName(this, address, StarknetIdContract2);
11921
+ const everythingAfterProtocol = match[1];
11922
+ if (!everythingAfterProtocol) {
11923
+ return false;
11959
11924
  }
11960
- async getAddressFromStarkName(name, StarknetIdContract2) {
11961
- return getAddressFromStarkName(this, name, StarknetIdContract2);
11925
+ if (localhostDomainRE.test(everythingAfterProtocol) || nonLocalhostDomainRE.test(everythingAfterProtocol)) {
11926
+ return true;
11962
11927
  }
11963
- };
11928
+ return false;
11929
+ }
11930
+ function buildUrl(baseUrl, defaultPath, urlOrPath) {
11931
+ return isUrl(urlOrPath) ? urlOrPath : (0, import_url_join.default)(baseUrl, urlOrPath ?? defaultPath);
11932
+ }
11964
11933
 
11965
- // src/provider/interface.ts
11966
- var ProviderInterface = class {
11934
+ // src/provider/sequencer.ts
11935
+ function isEmptyQueryObject(obj) {
11936
+ return obj === void 0 || Object.keys(obj).length === 0 || Object.keys(obj).length === 1 && Object.entries(obj).every(([k, v]) => k === "blockIdentifier" && v === null);
11937
+ }
11938
+ var defaultOptions2 = {
11939
+ network: "SN_GOERLI2" /* SN_GOERLI2 */,
11940
+ blockIdentifier: "pending"
11967
11941
  };
11968
-
11969
- // src/provider/index.ts
11970
- var defaultProvider = new Provider();
11971
-
11972
- // src/utils/calldata/formatter.ts
11973
- var guard = {
11974
- isBN: (data, type, key) => {
11975
- if (!isBigInt(data[key]))
11976
- throw new Error(
11977
- `Data and formatter mismatch on ${key}:${type[key]}, expected response data ${key}:${data[key]} to be BN instead it is ${typeof data[key]}`
11942
+ var SequencerProvider = class {
11943
+ constructor(optionsOrProvider = defaultOptions2) {
11944
+ this.responseParser = new SequencerAPIResponseParser();
11945
+ if ("network" in optionsOrProvider) {
11946
+ this.baseUrl = SequencerProvider.getNetworkFromName(optionsOrProvider.network);
11947
+ this.feederGatewayUrl = buildUrl(this.baseUrl, "feeder_gateway");
11948
+ this.gatewayUrl = buildUrl(this.baseUrl, "gateway");
11949
+ } else {
11950
+ this.baseUrl = optionsOrProvider.baseUrl;
11951
+ this.feederGatewayUrl = buildUrl(
11952
+ this.baseUrl,
11953
+ "feeder_gateway",
11954
+ optionsOrProvider.feederGatewayUrl
11978
11955
  );
11979
- },
11980
- unknown: (data, type, key) => {
11981
- throw new Error(`Unhandled formatter type on ${key}:${type[key]} for data ${key}:${data[key]}`);
11956
+ this.gatewayUrl = buildUrl(this.baseUrl, "gateway", optionsOrProvider.gatewayUrl);
11957
+ }
11958
+ this.chainId = (optionsOrProvider == null ? void 0 : optionsOrProvider.chainId) ?? SequencerProvider.getChainIdFromBaseUrl(this.baseUrl);
11959
+ this.headers = optionsOrProvider.headers;
11960
+ this.blockIdentifier = (optionsOrProvider == null ? void 0 : optionsOrProvider.blockIdentifier) || defaultOptions2.blockIdentifier;
11982
11961
  }
11983
- };
11984
- function formatter(data, type, sameType) {
11985
- return Object.entries(data).reduce((acc, [key, value]) => {
11986
- const elType = sameType ?? type[key];
11987
- if (!(key in type) && !sameType) {
11988
- acc[key] = value;
11989
- return acc;
11962
+ static getNetworkFromName(name) {
11963
+ switch (name) {
11964
+ case ("SN_MAIN" /* SN_MAIN */ || "0x534e5f4d41494e" /* SN_MAIN */):
11965
+ return "https://alpha-mainnet.starknet.io" /* SN_MAIN */;
11966
+ case ("SN_GOERLI" /* SN_GOERLI */ || "0x534e5f474f45524c49" /* SN_GOERLI */):
11967
+ return "https://alpha4.starknet.io" /* SN_GOERLI */;
11968
+ case ("SN_GOERLI2" /* SN_GOERLI2 */ || "0x534e5f474f45524c4932" /* SN_GOERLI2 */):
11969
+ return "https://alpha4-2.starknet.io" /* SN_GOERLI2 */;
11970
+ default:
11971
+ throw new Error("Could not detect base url from NetworkName");
11990
11972
  }
11991
- if (elType === "string") {
11992
- if (Array.isArray(data[key])) {
11993
- const arrayStr = formatter(
11994
- data[key],
11995
- data[key].map((_) => elType)
11996
- );
11997
- acc[key] = Object.values(arrayStr).join("");
11998
- return acc;
11973
+ }
11974
+ static getChainIdFromBaseUrl(baseUrl) {
11975
+ try {
11976
+ const url = new URL(baseUrl);
11977
+ if (url.host.includes("mainnet.starknet.io")) {
11978
+ return "0x534e5f4d41494e" /* SN_MAIN */;
11999
11979
  }
12000
- guard.isBN(data, type, key);
12001
- acc[key] = decodeShortString(value);
12002
- return acc;
12003
- }
12004
- if (elType === "number") {
12005
- guard.isBN(data, type, key);
12006
- acc[key] = Number(value);
12007
- return acc;
12008
- }
12009
- if (typeof elType === "function") {
12010
- acc[key] = elType(value);
12011
- return acc;
12012
- }
12013
- if (Array.isArray(elType)) {
12014
- const arrayObj = formatter(data[key], elType, elType[0]);
12015
- acc[key] = Object.values(arrayObj);
12016
- return acc;
12017
- }
12018
- if (typeof elType === "object") {
12019
- acc[key] = formatter(data[key], elType);
12020
- return acc;
12021
- }
12022
- guard.unknown(data, type, key);
12023
- return acc;
12024
- }, {});
12025
- }
12026
-
12027
- // src/utils/calldata/tuple.ts
12028
- function parseNamedTuple(namedTuple) {
12029
- const name = namedTuple.substring(0, namedTuple.indexOf(":"));
12030
- const type = namedTuple.substring(name.length + ":".length);
12031
- return { name, type };
12032
- }
12033
- function parseSubTuple(s) {
12034
- if (!s.includes("("))
12035
- return { subTuple: [], result: s };
12036
- const subTuple = [];
12037
- let result = "";
12038
- let i = 0;
12039
- while (i < s.length) {
12040
- if (s[i] === "(") {
12041
- let counter = 1;
12042
- const lBracket = i;
12043
- i++;
12044
- while (counter) {
12045
- if (s[i] === ")")
12046
- counter--;
12047
- if (s[i] === "(")
12048
- counter++;
12049
- i++;
11980
+ if (url.host.includes("alpha4-2.starknet.io")) {
11981
+ return "0x534e5f474f45524c4932" /* SN_GOERLI2 */;
12050
11982
  }
12051
- subTuple.push(s.substring(lBracket, i));
12052
- result += " ";
12053
- i--;
12054
- } else {
12055
- result += s[i];
11983
+ return "0x534e5f474f45524c49" /* SN_GOERLI */;
11984
+ } catch {
11985
+ console.error(`Could not parse baseUrl: ${baseUrl}`);
11986
+ return "0x534e5f474f45524c49" /* SN_GOERLI */;
12056
11987
  }
12057
- i++;
12058
- }
12059
- return {
12060
- subTuple,
12061
- result
12062
- };
12063
- }
12064
- function extractCairo0Tuple(type) {
12065
- const cleanType = type.replace(/\s/g, "").slice(1, -1);
12066
- const { subTuple, result } = parseSubTuple(cleanType);
12067
- let recomposed = result.split(",").map((it) => {
12068
- return subTuple.length ? it.replace(" ", subTuple.shift()) : it;
12069
- });
12070
- if (isTypeNamedTuple(type)) {
12071
- recomposed = recomposed.reduce((acc, it) => {
12072
- return acc.concat(parseNamedTuple(it));
12073
- }, []);
12074
11988
  }
12075
- return recomposed;
12076
- }
12077
- function extractCairo1Tuple(type) {
12078
- const cleanType = type.replace(/\s/g, "").slice(1, -1);
12079
- return cleanType.split(",");
12080
- }
12081
- function extractTupleMemberTypes(type) {
12082
- if (isCairo1Type(type)) {
12083
- return extractCairo1Tuple(type);
11989
+ getFetchUrl(endpoint) {
11990
+ const gatewayUrlEndpoints = ["add_transaction"];
11991
+ return gatewayUrlEndpoints.includes(endpoint) ? this.gatewayUrl : this.feederGatewayUrl;
12084
11992
  }
12085
- return extractCairo0Tuple(type);
12086
- }
12087
-
12088
- // src/utils/calldata/requestParser.ts
12089
- function parseTuple(element, typeStr) {
12090
- const memberTypes = extractTupleMemberTypes(typeStr);
12091
- const elements = Object.values(element);
12092
- if (elements.length !== memberTypes.length) {
12093
- throw Error(
12094
- `ParseTuple: provided and expected abi tuple size do not match.
12095
- provided: ${elements}
12096
- expected: ${memberTypes}`
12097
- );
12098
- }
12099
- return memberTypes.map((it, dx) => {
12100
- return {
12101
- element: elements[dx],
12102
- type: it.type ?? it
12103
- };
12104
- });
12105
- }
12106
- function parseCalldataValue(element, type, structs) {
12107
- if (element === void 0) {
12108
- throw Error(`Missing parameter for type ${type}`);
11993
+ getFetchMethod(endpoint) {
11994
+ const postMethodEndpoints = [
11995
+ "add_transaction",
11996
+ "call_contract",
11997
+ "estimate_fee",
11998
+ "estimate_message_fee",
11999
+ "estimate_fee_bulk",
12000
+ "simulate_transaction"
12001
+ ];
12002
+ return postMethodEndpoints.includes(endpoint) ? "POST" : "GET";
12109
12003
  }
12110
- if (Array.isArray(element)) {
12111
- throw Error(`Array inside array (nD) are not supported by cairo. Element: ${element} ${type}`);
12004
+ getQueryString(query) {
12005
+ if (isEmptyQueryObject(query)) {
12006
+ return "";
12007
+ }
12008
+ const queryString = Object.entries(query).map(([key, value]) => {
12009
+ if (key === "blockIdentifier") {
12010
+ const block = new Block(value);
12011
+ return `${block.queryIdentifier}`;
12012
+ }
12013
+ return `${key}=${value}`;
12014
+ }).join("&");
12015
+ return `?${queryString}`;
12112
12016
  }
12113
- if (isTypeUint256(type)) {
12114
- const el_uint256 = uint256(element);
12115
- return [felt(el_uint256.low), felt(el_uint256.high)];
12017
+ getHeaders(method) {
12018
+ if (method === "POST") {
12019
+ return {
12020
+ "Content-Type": "application/json",
12021
+ ...this.headers
12022
+ };
12023
+ }
12024
+ return this.headers;
12116
12025
  }
12117
- if (structs[type] && structs[type].members.length) {
12118
- const { members } = structs[type];
12119
- const subElement = element;
12120
- return members.reduce((acc, it) => {
12121
- return acc.concat(parseCalldataValue(subElement[it.name], it.type, structs));
12122
- }, []);
12026
+ async fetchEndpoint(endpoint, ...[query, request]) {
12027
+ const baseUrl = this.getFetchUrl(endpoint);
12028
+ const method = this.getFetchMethod(endpoint);
12029
+ const queryString = this.getQueryString(query);
12030
+ const url = (0, import_url_join2.default)(baseUrl, endpoint, queryString);
12031
+ return this.fetch(url, {
12032
+ method,
12033
+ body: request
12034
+ });
12123
12035
  }
12124
- if (isTypeTuple(type)) {
12125
- const tupled = parseTuple(element, type);
12126
- return tupled.reduce((acc, it) => {
12127
- const parsedData = parseCalldataValue(it.element, it.type, structs);
12128
- return acc.concat(parsedData);
12129
- }, []);
12036
+ async fetch(endpoint, options) {
12037
+ const url = buildUrl(this.baseUrl, "", endpoint);
12038
+ const method = (options == null ? void 0 : options.method) ?? "GET";
12039
+ const headers = this.getHeaders(method);
12040
+ const body = stringify2(options == null ? void 0 : options.body);
12041
+ try {
12042
+ const response = await fetchPonyfill_default(url, {
12043
+ method,
12044
+ body,
12045
+ headers
12046
+ });
12047
+ const textResponse = await response.text();
12048
+ if (!response.ok) {
12049
+ let responseBody;
12050
+ try {
12051
+ responseBody = parse2(textResponse);
12052
+ } catch {
12053
+ throw new HttpError(response.statusText, response.status);
12054
+ }
12055
+ throw new GatewayError(responseBody.message, responseBody.code);
12056
+ }
12057
+ const parseChoice = (options == null ? void 0 : options.parseAlwaysAsBigInt) ? parseAlwaysAsBig : parse2;
12058
+ return parseChoice(textResponse);
12059
+ } catch (error) {
12060
+ if (error instanceof Error && !(error instanceof LibraryError))
12061
+ throw Error(`Could not ${method} from endpoint \`${url}\`: ${error.message}`);
12062
+ throw error;
12063
+ }
12130
12064
  }
12131
- if (typeof element === "object") {
12132
- throw Error(`Parameter ${element} do not align with abi parameter ${type}`);
12065
+ async getChainId() {
12066
+ return Promise.resolve(this.chainId);
12133
12067
  }
12134
- return felt(element);
12135
- }
12136
- function parseCalldataField(argsIterator, input, structs) {
12137
- const { name, type } = input;
12138
- let { value } = argsIterator.next();
12139
- switch (true) {
12140
- case isTypeArray(type):
12141
- if (!Array.isArray(value) && !isText(value)) {
12142
- throw Error(`ABI expected parameter ${name} to be array or long string, got ${value}`);
12143
- }
12144
- if (typeof value === "string") {
12145
- value = splitLongString(value);
12068
+ async callContract({ contractAddress, entrypoint: entryPointSelector, calldata = [] }, blockIdentifier = this.blockIdentifier) {
12069
+ return this.fetchEndpoint(
12070
+ "call_contract",
12071
+ { blockIdentifier },
12072
+ {
12073
+ contract_address: contractAddress,
12074
+ entry_point_selector: getSelectorFromName(entryPointSelector),
12075
+ calldata
12146
12076
  }
12147
- const result = [];
12148
- result.push(felt(value.length));
12149
- const arrayType = getArrayType(input.type);
12150
- return value.reduce((acc, el) => {
12151
- if (isTypeFelt(arrayType) || isTypeUint(arrayType) || isTypeContractAddress(arrayType)) {
12152
- acc.push(felt(el));
12153
- } else if (isTypeBool(arrayType) && typeof el === "boolean") {
12154
- acc.push(el.toString());
12155
- } else {
12156
- acc.push(...parseCalldataValue(el, arrayType, structs));
12157
- }
12158
- return acc;
12159
- }, result);
12160
- case (isTypeStruct(type, structs) || isTypeTuple(type) || isTypeUint256(type)):
12161
- return parseCalldataValue(value, type, structs);
12162
- case isTypeBool(type):
12163
- return `${+value}`;
12164
- default:
12165
- return felt(value);
12077
+ ).then(this.responseParser.parseCallContractResponse);
12166
12078
  }
12167
- }
12168
-
12169
- // src/utils/calldata/responseParser.ts
12170
- function parseResponseStruct(responseIterator, type, structs) {
12171
- if (type in structs && structs[type]) {
12172
- return structs[type].members.reduce((acc, el) => {
12173
- acc[el.name] = parseResponseStruct(responseIterator, el.type, structs);
12174
- return acc;
12175
- }, {});
12079
+ async getBlock(blockIdentifier = this.blockIdentifier) {
12080
+ return this.fetchEndpoint("get_block", { blockIdentifier }).then(
12081
+ this.responseParser.parseGetBlockResponse
12082
+ );
12176
12083
  }
12177
- if (isTypeTuple(type)) {
12178
- const memberTypes = extractTupleMemberTypes(type);
12179
- return memberTypes.reduce((acc, it, idx) => {
12180
- const tName = (it == null ? void 0 : it.name) ? it.name : idx;
12181
- const tType = (it == null ? void 0 : it.type) ? it.type : it;
12182
- acc[tName] = parseResponseStruct(responseIterator, tType, structs);
12183
- return acc;
12184
- }, {});
12084
+ async getNonceForAddress(contractAddress, blockIdentifier = this.blockIdentifier) {
12085
+ return this.fetchEndpoint("get_nonce", { contractAddress, blockIdentifier });
12185
12086
  }
12186
- const temp = responseIterator.next().value;
12187
- return BigInt(temp);
12188
- }
12189
- function responseParser(responseIterator, output2, structs, parsedResult) {
12190
- const { name, type } = output2;
12191
- let temp;
12192
- switch (true) {
12193
- case isLen(name):
12194
- temp = responseIterator.next().value;
12195
- return BigInt(temp);
12196
- case isTypeBool(type):
12197
- temp = responseIterator.next().value;
12198
- return Boolean(BigInt(temp));
12199
- case isTypeUint256(type):
12200
- const low = responseIterator.next().value;
12201
- const high = responseIterator.next().value;
12202
- return uint256ToBN({ low, high });
12203
- case isTypeArray(type):
12204
- const parsedDataArr = [];
12205
- if (isCairo1Type(type)) {
12206
- responseIterator.next();
12207
- let it = responseIterator.next();
12208
- while (!it.done) {
12209
- parsedDataArr.push(BigInt(it.value));
12210
- it = responseIterator.next();
12087
+ async getStorageAt(contractAddress, key, blockIdentifier = this.blockIdentifier) {
12088
+ const parsedKey = toBigInt(key).toString(10);
12089
+ return this.fetchEndpoint("get_storage_at", {
12090
+ blockIdentifier,
12091
+ contractAddress,
12092
+ key: parsedKey
12093
+ });
12094
+ }
12095
+ async getTransaction(txHash) {
12096
+ const txHashHex = toHex(txHash);
12097
+ return this.fetchEndpoint("get_transaction", { transactionHash: txHashHex }).then((result) => {
12098
+ if (Object.values(result).length === 1)
12099
+ throw new LibraryError(result.status);
12100
+ return this.responseParser.parseGetTransactionResponse(result);
12101
+ });
12102
+ }
12103
+ async getTransactionReceipt(txHash) {
12104
+ const txHashHex = toHex(txHash);
12105
+ return this.fetchEndpoint("get_transaction_receipt", { transactionHash: txHashHex }).then(
12106
+ this.responseParser.parseGetTransactionReceiptResponse
12107
+ );
12108
+ }
12109
+ async getClassAt(contractAddress, blockIdentifier = this.blockIdentifier) {
12110
+ return this.fetchEndpoint("get_full_contract", { blockIdentifier, contractAddress }).then(
12111
+ (res) => {
12112
+ if (isSierra(res)) {
12113
+ return this.responseParser.parseSierraContractClassResponse(res);
12211
12114
  }
12212
- return parsedDataArr;
12115
+ return parseContract(res);
12213
12116
  }
12214
- if (parsedResult && parsedResult[`${name}_len`]) {
12215
- const arrLen = parsedResult[`${name}_len`];
12216
- while (parsedDataArr.length < arrLen) {
12217
- parsedDataArr.push(
12218
- parseResponseStruct(responseIterator, output2.type.replace("*", ""), structs)
12219
- );
12220
- }
12117
+ );
12118
+ }
12119
+ async getClassHashAt(contractAddress, blockIdentifier = this.blockIdentifier) {
12120
+ return this.fetchEndpoint("get_class_hash_at", { blockIdentifier, contractAddress });
12121
+ }
12122
+ async getClassByHash(classHash, blockIdentifier = this.blockIdentifier) {
12123
+ return this.fetchEndpoint("get_class_by_hash", { classHash, blockIdentifier }).then((res) => {
12124
+ if (isSierra(res)) {
12125
+ return this.responseParser.parseSierraContractClassResponse(res);
12221
12126
  }
12222
- return parsedDataArr;
12223
- case (type in structs || isTypeTuple(type)):
12224
- return parseResponseStruct(responseIterator, type, structs);
12225
- default:
12226
- temp = responseIterator.next().value;
12227
- return BigInt(temp);
12127
+ return parseContract(res);
12128
+ });
12228
12129
  }
12229
- }
12230
-
12231
- // src/utils/calldata/validate.ts
12232
- var validateFelt = (parameter, input) => {
12233
- assert2(
12234
- typeof parameter === "string" || typeof parameter === "number" || typeof parameter === "bigint",
12235
- `Validate: arg ${input.name} should be a felt typed as (String, Number or BigInt)`
12236
- );
12237
- };
12238
- var validateUint = (parameter, input) => {
12239
- if (typeof parameter === "number") {
12240
- assert2(
12241
- parameter <= Number.MAX_SAFE_INTEGER,
12242
- `Validation: Parameter is to large to be typed as Number use (BigInt or String)`
12243
- );
12130
+ async getCompiledClassByClassHash(classHash, blockIdentifier = this.blockIdentifier) {
12131
+ return this.fetchEndpoint("get_compiled_class_by_class_hash", { classHash, blockIdentifier });
12244
12132
  }
12245
- assert2(
12246
- typeof parameter === "string" || typeof parameter === "number" || typeof parameter === "bigint",
12247
- `Validate: arg ${input.name} of cairo type ${input.type} should be type (String, Number or BigInt)`
12248
- );
12249
- const param = toBigInt(parameter);
12250
- switch (input.type) {
12251
- case "core::integer::u8" /* u8 */:
12252
- assert2(
12253
- param >= 0n && param <= 255n,
12254
- `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0 - 255]`
12255
- );
12256
- break;
12257
- case "core::integer::u16" /* u16 */:
12258
- assert2(
12259
- param >= 0n && param <= 65535n,
12260
- `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 65535]`
12261
- );
12262
- break;
12263
- case "core::integer::u32" /* u32 */:
12264
- assert2(
12265
- param >= 0n && param <= 4294967295n,
12266
- `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 4294967295]`
12267
- );
12268
- break;
12269
- case "core::integer::u64" /* u64 */:
12270
- assert2(
12271
- param >= 0n && param <= 2n ** 64n - 1n,
12272
- `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 2^64-1]`
12273
- );
12274
- break;
12275
- case "core::integer::u128" /* u128 */:
12276
- assert2(
12277
- param >= 0n && param <= 2n ** 128n - 1n,
12278
- `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 2^128-1]`
12279
- );
12280
- break;
12281
- case "core::integer::u256" /* u256 */:
12282
- assert2(
12283
- param >= 0n && param <= 2n ** 256n - 1n,
12284
- `Validate: arg ${input.name} is ${input.type} 0 - 2^256-1`
12285
- );
12286
- break;
12287
- default:
12288
- break;
12133
+ async invokeFunction(functionInvocation, details) {
12134
+ return this.fetchEndpoint("add_transaction", void 0, {
12135
+ type: "INVOKE_FUNCTION" /* INVOKE */,
12136
+ sender_address: functionInvocation.contractAddress,
12137
+ calldata: bigNumberishArrayToDecimalStringArray(functionInvocation.calldata ?? []),
12138
+ signature: signatureToDecimalArray(functionInvocation.signature),
12139
+ nonce: toHex(details.nonce),
12140
+ max_fee: toHex(details.maxFee || 0),
12141
+ version: "0x1"
12142
+ }).then(this.responseParser.parseInvokeFunctionResponse);
12289
12143
  }
12290
- };
12291
- var validateBool = (parameter, input) => {
12292
- assert2(
12293
- typeof parameter === "boolean",
12294
- `Validate: arg ${input.name} of cairo type ${input.type} should be type (Boolean)`
12295
- );
12296
- };
12297
- var validateStruct = (parameter, input, structs) => {
12298
- assert2(
12299
- typeof parameter === "object" && !Array.isArray(parameter),
12300
- `Validate: arg ${input.name} is cairo type struct (${input.type}), and should be defined as js object (not array)`
12301
- );
12302
- structs[input.type].members.forEach(({ name }) => {
12303
- assert2(
12304
- Object.keys(parameter).includes(name),
12305
- `Validate: arg ${input.name} should have a property ${name}`
12144
+ async deployAccountContract({ classHash, constructorCalldata, addressSalt, signature }, details) {
12145
+ return this.fetchEndpoint("add_transaction", void 0, {
12146
+ type: "DEPLOY_ACCOUNT" /* DEPLOY_ACCOUNT */,
12147
+ contract_address_salt: addressSalt ?? randomAddress(),
12148
+ constructor_calldata: bigNumberishArrayToDecimalStringArray(constructorCalldata ?? []),
12149
+ class_hash: toHex(classHash),
12150
+ max_fee: toHex(details.maxFee || 0),
12151
+ version: toHex(details.version || 0),
12152
+ nonce: toHex(details.nonce),
12153
+ signature: signatureToDecimalArray(signature)
12154
+ }).then(this.responseParser.parseDeployContractResponse);
12155
+ }
12156
+ async declareContract({ senderAddress, contractDefinition, signature, compiledClassHash }, details) {
12157
+ if (!isSierra(contractDefinition)) {
12158
+ return this.fetchEndpoint("add_transaction", void 0, {
12159
+ type: "DECLARE" /* DECLARE */,
12160
+ contract_class: contractDefinition,
12161
+ nonce: toHex(details.nonce),
12162
+ signature: signatureToDecimalArray(signature),
12163
+ sender_address: senderAddress,
12164
+ max_fee: toHex(details.maxFee || 0),
12165
+ version: "0x1"
12166
+ }).then(this.responseParser.parseDeclareContractResponse);
12167
+ }
12168
+ return this.fetchEndpoint("add_transaction", void 0, {
12169
+ type: "DECLARE" /* DECLARE */,
12170
+ sender_address: senderAddress,
12171
+ compiled_class_hash: compiledClassHash,
12172
+ contract_class: contractDefinition,
12173
+ nonce: toHex(details.nonce),
12174
+ signature: signatureToDecimalArray(signature),
12175
+ max_fee: toHex(details.maxFee || 0),
12176
+ version: "0x2"
12177
+ }).then(this.responseParser.parseDeclareContractResponse);
12178
+ }
12179
+ async getEstimateFee(invocation, invocationDetails, blockIdentifier = this.blockIdentifier, skipValidate = false) {
12180
+ return this.getInvokeEstimateFee(invocation, invocationDetails, blockIdentifier, skipValidate);
12181
+ }
12182
+ async getInvokeEstimateFee(invocation, invocationDetails, blockIdentifier = this.blockIdentifier, skipValidate = false) {
12183
+ return this.fetchEndpoint(
12184
+ "estimate_fee",
12185
+ { blockIdentifier, skipValidate },
12186
+ {
12187
+ type: "INVOKE_FUNCTION" /* INVOKE */,
12188
+ sender_address: invocation.contractAddress,
12189
+ calldata: invocation.calldata ?? [],
12190
+ signature: signatureToDecimalArray(invocation.signature),
12191
+ version: toHex((invocationDetails == null ? void 0 : invocationDetails.version) || 1),
12192
+ nonce: toHex(invocationDetails.nonce)
12193
+ }
12194
+ ).then(this.responseParser.parseFeeEstimateResponse);
12195
+ }
12196
+ async getDeclareEstimateFee({ senderAddress, contractDefinition, signature, compiledClassHash }, details, blockIdentifier = this.blockIdentifier, skipValidate = false) {
12197
+ if (!isSierra(contractDefinition)) {
12198
+ return this.fetchEndpoint(
12199
+ "estimate_fee",
12200
+ { blockIdentifier, skipValidate },
12201
+ {
12202
+ type: "DECLARE" /* DECLARE */,
12203
+ sender_address: senderAddress,
12204
+ contract_class: contractDefinition,
12205
+ signature: signatureToDecimalArray(signature),
12206
+ version: toHex((details == null ? void 0 : details.version) || toBigInt(feeTransactionVersion)),
12207
+ nonce: toHex(details.nonce)
12208
+ }
12209
+ ).then(this.responseParser.parseFeeEstimateResponse);
12210
+ }
12211
+ return this.fetchEndpoint(
12212
+ "estimate_fee",
12213
+ { blockIdentifier, skipValidate },
12214
+ {
12215
+ type: "DECLARE" /* DECLARE */,
12216
+ sender_address: senderAddress,
12217
+ compiled_class_hash: compiledClassHash,
12218
+ contract_class: contractDefinition,
12219
+ nonce: toHex(details.nonce),
12220
+ signature: signatureToDecimalArray(signature),
12221
+ version: "0x2"
12222
+ }
12223
+ ).then(this.responseParser.parseFeeEstimateResponse);
12224
+ }
12225
+ async getDeployAccountEstimateFee({ classHash, addressSalt, constructorCalldata, signature }, details, blockIdentifier = this.blockIdentifier, skipValidate = false) {
12226
+ return this.fetchEndpoint(
12227
+ "estimate_fee",
12228
+ { blockIdentifier, skipValidate },
12229
+ {
12230
+ type: "DEPLOY_ACCOUNT" /* DEPLOY_ACCOUNT */,
12231
+ class_hash: toHex(classHash),
12232
+ constructor_calldata: bigNumberishArrayToDecimalStringArray(constructorCalldata || []),
12233
+ contract_address_salt: toHex(addressSalt || 0),
12234
+ signature: signatureToDecimalArray(signature),
12235
+ version: toHex((details == null ? void 0 : details.version) || 0),
12236
+ nonce: toHex(details.nonce)
12237
+ }
12238
+ ).then(this.responseParser.parseFeeEstimateResponse);
12239
+ }
12240
+ async getEstimateFeeBulk(invocations, blockIdentifier = this.blockIdentifier) {
12241
+ const params = invocations.map((invocation) => {
12242
+ let res;
12243
+ if (invocation.type === "INVOKE_FUNCTION") {
12244
+ res = {
12245
+ type: invocation.type,
12246
+ sender_address: invocation.contractAddress,
12247
+ calldata: invocation.calldata ?? []
12248
+ };
12249
+ } else if (invocation.type === "DECLARE") {
12250
+ res = {
12251
+ type: invocation.type,
12252
+ sender_address: invocation.senderAddress,
12253
+ contract_class: invocation.contractDefinition
12254
+ };
12255
+ } else {
12256
+ res = {
12257
+ type: invocation.type,
12258
+ class_hash: toHex(toBigInt(invocation.classHash)),
12259
+ constructor_calldata: bigNumberishArrayToDecimalStringArray(
12260
+ invocation.constructorCalldata || []
12261
+ ),
12262
+ contract_address_salt: toHex(toBigInt(invocation.addressSalt || 0))
12263
+ };
12264
+ }
12265
+ return {
12266
+ ...res,
12267
+ signature: bigNumberishArrayToDecimalStringArray(formatSignature(invocation.signature)),
12268
+ version: toHex(toBigInt((invocation == null ? void 0 : invocation.version) || 1)),
12269
+ nonce: toHex(toBigInt(invocation.nonce))
12270
+ };
12271
+ });
12272
+ return this.fetchEndpoint("estimate_fee_bulk", { blockIdentifier }, params).then(
12273
+ this.responseParser.parseFeeEstimateBulkResponse
12306
12274
  );
12307
- });
12308
- };
12309
- var validateTuple = (parameter, input) => {
12310
- assert2(
12311
- typeof parameter === "object" && !Array.isArray(parameter),
12312
- `Validate: arg ${input.name} should be a tuple (defined as object)`
12313
- );
12314
- };
12315
- var validateArray = (parameter, input, structs) => {
12316
- const baseType = getArrayType(input.type);
12317
- if (isTypeFelt(baseType) && isLongText(parameter))
12318
- return;
12319
- assert2(Array.isArray(parameter), `Validate: arg ${input.name} should be an Array`);
12320
- switch (true) {
12321
- case isTypeFelt(baseType):
12322
- parameter.forEach((param) => validateFelt(param, input));
12323
- break;
12324
- case isTypeTuple(baseType):
12325
- parameter.forEach((it) => validateTuple(it, { name: input.name, type: baseType }));
12326
- break;
12327
- case isTypeStruct(baseType, structs):
12328
- parameter.forEach(
12329
- (it) => validateStruct(it, { name: input.name, type: baseType }, structs)
12330
- );
12331
- break;
12332
- case isTypeUint(baseType):
12333
- parameter.forEach((param) => validateUint(param, input));
12334
- break;
12335
- case isTypeBool(baseType):
12336
- parameter.forEach((param) => validateBool(param, input));
12337
- break;
12338
- default:
12339
- throw new Error(
12340
- `Validate Unhandled: argument ${input.name}, type ${input.type}, value ${parameter}`
12341
- );
12275
+ }
12276
+ async getCode(contractAddress, blockIdentifier = this.blockIdentifier) {
12277
+ return this.fetchEndpoint("get_code", { contractAddress, blockIdentifier });
12278
+ }
12279
+ async waitForTransaction(txHash, options) {
12280
+ const errorStates = ["REJECTED" /* REJECTED */, "NOT_RECEIVED" /* NOT_RECEIVED */];
12281
+ let onchain = false;
12282
+ let res;
12283
+ const retryInterval = (options == null ? void 0 : options.retryInterval) ?? 8e3;
12284
+ const successStates = (options == null ? void 0 : options.successStates) ?? [
12285
+ "ACCEPTED_ON_L1" /* ACCEPTED_ON_L1 */,
12286
+ "ACCEPTED_ON_L2" /* ACCEPTED_ON_L2 */,
12287
+ "PENDING" /* PENDING */
12288
+ ];
12289
+ while (!onchain) {
12290
+ await wait(retryInterval);
12291
+ res = await this.getTransactionStatus(txHash);
12292
+ if (successStates.includes(res.tx_status)) {
12293
+ onchain = true;
12294
+ } else if (errorStates.includes(res.tx_status)) {
12295
+ const message = res.tx_failure_reason ? `${res.tx_status}: ${res.tx_failure_reason.code}
12296
+ ${res.tx_failure_reason.error_message}` : res.tx_status;
12297
+ const error = new Error(message);
12298
+ error.response = res;
12299
+ throw error;
12300
+ }
12301
+ }
12302
+ const txReceipt = await this.getTransactionReceipt(txHash);
12303
+ return txReceipt;
12304
+ }
12305
+ async getTransactionStatus(txHash) {
12306
+ const txHashHex = toHex(txHash);
12307
+ return this.fetchEndpoint("get_transaction_status", { transactionHash: txHashHex });
12308
+ }
12309
+ async getContractAddresses() {
12310
+ return this.fetchEndpoint("get_contract_addresses");
12311
+ }
12312
+ async getTransactionTrace(txHash) {
12313
+ const txHashHex = toHex(txHash);
12314
+ return this.fetchEndpoint("get_transaction_trace", { transactionHash: txHashHex });
12315
+ }
12316
+ async estimateMessageFee({ from_address, to_address, entry_point_selector, payload }, blockIdentifier = this.blockIdentifier) {
12317
+ const validCallL1Handler = {
12318
+ from_address: getDecimalString(from_address),
12319
+ to_address: getHexString(to_address),
12320
+ entry_point_selector: getSelector(entry_point_selector),
12321
+ payload: getHexStringArray(payload)
12322
+ };
12323
+ return this.fetchEndpoint("estimate_message_fee", { blockIdentifier }, validCallL1Handler);
12324
+ }
12325
+ async getSimulateTransaction(invocation, invocationDetails, blockIdentifier = this.blockIdentifier, skipValidate = false) {
12326
+ return this.fetchEndpoint(
12327
+ "simulate_transaction",
12328
+ { blockIdentifier, skipValidate },
12329
+ {
12330
+ type: "INVOKE_FUNCTION",
12331
+ sender_address: invocation.contractAddress,
12332
+ calldata: invocation.calldata ?? [],
12333
+ signature: signatureToDecimalArray(invocation.signature),
12334
+ version: toHex((invocationDetails == null ? void 0 : invocationDetails.version) || 1),
12335
+ nonce: toHex(invocationDetails.nonce),
12336
+ max_fee: toHex((invocationDetails == null ? void 0 : invocationDetails.maxFee) || 0)
12337
+ }
12338
+ ).then(this.responseParser.parseFeeSimulateTransactionResponse);
12339
+ }
12340
+ async getStateUpdate(blockIdentifier = this.blockIdentifier) {
12341
+ const args = new Block(blockIdentifier).sequencerIdentifier;
12342
+ return this.fetchEndpoint("get_state_update", { ...args }).then(
12343
+ this.responseParser.parseGetStateUpdateResponse
12344
+ );
12345
+ }
12346
+ async getBlockTraces(blockIdentifier = this.blockIdentifier) {
12347
+ const args = new Block(blockIdentifier).sequencerIdentifier;
12348
+ return this.fetchEndpoint("get_block_traces", { ...args });
12349
+ }
12350
+ async getStarkName(address, StarknetIdContract2) {
12351
+ return getStarkName(this, address, StarknetIdContract2);
12352
+ }
12353
+ async getAddressFromStarkName(name, StarknetIdContract2) {
12354
+ return getAddressFromStarkName(this, name, StarknetIdContract2);
12342
12355
  }
12343
12356
  };
12344
- function validateFields(abiMethod, args, structs) {
12345
- abiMethod.inputs.reduce((acc, input) => {
12346
- const parameter = args[acc];
12347
- switch (true) {
12348
- case isLen(input.name):
12349
- return acc;
12350
- case isTypeFelt(input.type):
12351
- validateFelt(parameter, input);
12352
- break;
12353
- case isTypeUint(input.type):
12354
- validateUint(parameter, input);
12355
- break;
12356
- case isTypeBool(input.type):
12357
- validateBool(parameter, input);
12358
- break;
12359
- case isTypeContractAddress(input.type):
12360
- break;
12361
- case isTypeStruct(input.type, structs):
12362
- validateStruct(parameter, input, structs);
12363
- break;
12364
- case isTypeTuple(input.type):
12365
- validateTuple(parameter, input);
12366
- break;
12367
- case isTypeArray(input.type):
12368
- validateArray(parameter, input, structs);
12369
- break;
12370
- default:
12371
- throw new Error(
12372
- `Validate Unhandled: argument ${input.name}, type ${input.type}, value ${parameter}`
12373
- );
12374
- }
12375
- return acc + 1;
12376
- }, 0);
12377
- }
12378
12357
 
12379
- // src/utils/calldata/index.ts
12380
- var CallData = class {
12381
- constructor(abi) {
12382
- this.abi = abi;
12383
- this.structs = CallData.getAbiStruct(abi);
12384
- }
12385
- validate(type, method, args = []) {
12386
- if (type !== "DEPLOY") {
12387
- const invocableFunctionNames = this.abi.filter((abi) => {
12388
- if (abi.type !== "function")
12389
- return false;
12390
- const isView = abi.stateMutability === "view" || abi.state_mutability === "view";
12391
- return type === "INVOKE" ? !isView : isView;
12392
- }).map((abi) => abi.name);
12393
- assert2(
12394
- invocableFunctionNames.includes(method),
12395
- `${type === "INVOKE" ? "invocable" : "viewable"} method not found in abi`
12396
- );
12397
- }
12398
- const abiMethod = this.abi.find(
12399
- (abi) => type === "DEPLOY" ? abi.name === method && abi.type === method : abi.name === method && abi.type === "function"
12400
- );
12401
- const inputsLength = CallData.abiInputsLength(abiMethod.inputs);
12402
- if (args.length !== inputsLength) {
12403
- throw Error(
12404
- `Invalid number of arguments, expected ${inputsLength} arguments, but got ${args.length}`
12405
- );
12358
+ // src/provider/default.ts
12359
+ var Provider = class {
12360
+ constructor(providerOrOptions) {
12361
+ if (providerOrOptions instanceof Provider) {
12362
+ this.provider = providerOrOptions.provider;
12363
+ } else if (providerOrOptions instanceof RpcProvider || providerOrOptions instanceof SequencerProvider) {
12364
+ this.provider = providerOrOptions;
12365
+ } else if (providerOrOptions && "rpc" in providerOrOptions) {
12366
+ this.provider = new RpcProvider(providerOrOptions.rpc);
12367
+ } else if (providerOrOptions && "sequencer" in providerOrOptions) {
12368
+ this.provider = new SequencerProvider(providerOrOptions.sequencer);
12369
+ } else {
12370
+ this.provider = new SequencerProvider();
12406
12371
  }
12407
- validateFields(abiMethod, args, this.structs);
12408
12372
  }
12409
- compile(args, inputs) {
12410
- const argsIterator = args[Symbol.iterator]();
12411
- return inputs.reduce(
12412
- (acc, input) => isLen(input.name) ? acc : acc.concat(parseCalldataField(argsIterator, input, this.structs)),
12413
- []
12373
+ async getChainId() {
12374
+ return this.provider.getChainId();
12375
+ }
12376
+ async getBlock(blockIdentifier) {
12377
+ return this.provider.getBlock(blockIdentifier);
12378
+ }
12379
+ async getClassAt(contractAddress, blockIdentifier) {
12380
+ return this.provider.getClassAt(contractAddress, blockIdentifier);
12381
+ }
12382
+ async getClassHashAt(contractAddress, blockIdentifier) {
12383
+ return this.provider.getClassHashAt(contractAddress, blockIdentifier);
12384
+ }
12385
+ getClassByHash(classHash) {
12386
+ return this.provider.getClassByHash(classHash);
12387
+ }
12388
+ async getEstimateFee(invocationWithTxType, invocationDetails, blockIdentifier) {
12389
+ return this.provider.getEstimateFee(invocationWithTxType, invocationDetails, blockIdentifier);
12390
+ }
12391
+ async getInvokeEstimateFee(invocationWithTxType, invocationDetails, blockIdentifier, skipValidate) {
12392
+ return this.provider.getInvokeEstimateFee(
12393
+ invocationWithTxType,
12394
+ invocationDetails,
12395
+ blockIdentifier,
12396
+ skipValidate
12414
12397
  );
12415
12398
  }
12416
- static compile(data) {
12417
- const createTree = (obj) => {
12418
- const getEntries = (o, prefix = "") => {
12419
- const oe = Array.isArray(o) ? [o.length.toString(), ...o] : o;
12420
- return Object.entries(oe).flatMap(([k, v]) => {
12421
- let value = v;
12422
- if (isLongText(value))
12423
- value = splitLongString(value);
12424
- const kk = Array.isArray(oe) && k === "0" ? "$$len" : k;
12425
- if (isBigInt(value))
12426
- return [[`${prefix}${kk}`, felt(value)]];
12427
- return Object(value) === value ? getEntries(value, `${prefix}${kk}.`) : [[`${prefix}${kk}`, felt(value)]];
12428
- });
12429
- };
12430
- return Object.fromEntries(getEntries(obj));
12431
- };
12432
- let callTreeArray;
12433
- if (!Array.isArray(data)) {
12434
- const callTree = createTree(data);
12435
- callTreeArray = Object.values(callTree);
12436
- } else {
12437
- callTreeArray = data;
12438
- }
12439
- Object.defineProperty(callTreeArray, "compiled", {
12440
- enumerable: false,
12441
- writable: false,
12442
- value: true
12443
- });
12444
- return callTreeArray;
12399
+ async getEstimateFeeBulk(invocations, blockIdentifier) {
12400
+ return this.provider.getEstimateFeeBulk(invocations, blockIdentifier);
12445
12401
  }
12446
- parse(method, response) {
12447
- const { outputs } = this.abi.find((abi) => abi.name === method);
12448
- const responseIterator = response.flat()[Symbol.iterator]();
12449
- const parsed = outputs.flat().reduce((acc, output2, idx) => {
12450
- const propName = output2.name ?? idx;
12451
- acc[propName] = responseParser(responseIterator, output2, this.structs, acc);
12452
- if (acc[propName] && acc[`${propName}_len`]) {
12453
- delete acc[`${propName}_len`];
12454
- }
12455
- return acc;
12456
- }, {});
12457
- return Object.keys(parsed).length === 1 && 0 in parsed ? parsed[0] : parsed;
12402
+ async getNonceForAddress(contractAddress, blockIdentifier) {
12403
+ return this.provider.getNonceForAddress(contractAddress, blockIdentifier);
12458
12404
  }
12459
- format(method, response, format) {
12460
- const parsed = this.parse(method, response);
12461
- return formatter(parsed, format);
12405
+ async getStorageAt(contractAddress, key, blockIdentifier) {
12406
+ return this.provider.getStorageAt(contractAddress, key, blockIdentifier);
12462
12407
  }
12463
- static abiInputsLength(inputs) {
12464
- return inputs.reduce((acc, input) => !isLen(input.name) ? acc + 1 : acc, 0);
12408
+ async getTransaction(txHash) {
12409
+ return this.provider.getTransaction(txHash);
12465
12410
  }
12466
- static getAbiStruct(abi) {
12467
- return abi.filter((abiEntry) => abiEntry.type === "struct").reduce(
12468
- (acc, abiEntry) => ({
12469
- ...acc,
12470
- [abiEntry.name]: abiEntry
12471
- }),
12472
- {}
12411
+ async getTransactionReceipt(txHash) {
12412
+ return this.provider.getTransactionReceipt(txHash);
12413
+ }
12414
+ async callContract(request, blockIdentifier) {
12415
+ return this.provider.callContract(request, blockIdentifier);
12416
+ }
12417
+ async invokeFunction(functionInvocation, details) {
12418
+ return this.provider.invokeFunction(functionInvocation, details);
12419
+ }
12420
+ async deployAccountContract(payload, details) {
12421
+ return this.provider.deployAccountContract(payload, details);
12422
+ }
12423
+ async declareContract(transaction, details) {
12424
+ return this.provider.declareContract(transaction, details);
12425
+ }
12426
+ async getDeclareEstimateFee(transaction, details, blockIdentifier, skipValidate) {
12427
+ return this.provider.getDeclareEstimateFee(transaction, details, blockIdentifier, skipValidate);
12428
+ }
12429
+ getDeployAccountEstimateFee(transaction, details, blockIdentifier, skipValidate) {
12430
+ return this.provider.getDeployAccountEstimateFee(
12431
+ transaction,
12432
+ details,
12433
+ blockIdentifier,
12434
+ skipValidate
12435
+ );
12436
+ }
12437
+ async getCode(contractAddress, blockIdentifier) {
12438
+ return this.provider.getCode(contractAddress, blockIdentifier);
12439
+ }
12440
+ async waitForTransaction(txHash, options) {
12441
+ return this.provider.waitForTransaction(txHash, options);
12442
+ }
12443
+ async getSimulateTransaction(invocation, invocationDetails, blockIdentifier, skipValidate) {
12444
+ return this.provider.getSimulateTransaction(
12445
+ invocation,
12446
+ invocationDetails,
12447
+ blockIdentifier,
12448
+ skipValidate
12473
12449
  );
12474
12450
  }
12451
+ async getStateUpdate(blockIdentifier) {
12452
+ return this.provider.getStateUpdate(blockIdentifier);
12453
+ }
12454
+ async getStarkName(address, StarknetIdContract2) {
12455
+ return getStarkName(this, address, StarknetIdContract2);
12456
+ }
12457
+ async getAddressFromStarkName(name, StarknetIdContract2) {
12458
+ return getAddressFromStarkName(this, name, StarknetIdContract2);
12459
+ }
12460
+ };
12461
+
12462
+ // src/provider/interface.ts
12463
+ var ProviderInterface = class {
12475
12464
  };
12476
12465
 
12466
+ // src/provider/index.ts
12467
+ var defaultProvider = new Provider();
12468
+
12477
12469
  // src/contract/default.ts
12478
12470
  var splitArgsAndOptions = (args) => {
12479
12471
  const options = [
@@ -12483,13 +12475,14 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12483
12475
  "formatResponse",
12484
12476
  "maxFee",
12485
12477
  "nonce",
12486
- "signature"
12478
+ "signature",
12479
+ "addressSalt"
12487
12480
  ];
12488
12481
  const lastArg = args[args.length - 1];
12489
12482
  if (typeof lastArg === "object" && options.some((x) => x in lastArg)) {
12490
12483
  return { args, options: args.pop() };
12491
12484
  }
12492
- return { args, options: {} };
12485
+ return { args };
12493
12486
  };
12494
12487
  function buildCall(contract, functionAbi) {
12495
12488
  return async function(...args) {
@@ -12526,20 +12519,20 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12526
12519
  return contract.estimate(functionAbi.name, args);
12527
12520
  };
12528
12521
  }
12529
- var detectCairoVersion = (abi) => {
12530
- if (!abi)
12531
- return "0";
12532
- return abi.find((it) => "state_mutability" in it) ? "1" : "0";
12533
- };
12522
+ function getCalldata(args, callback) {
12523
+ if ("__compiled__" in args)
12524
+ return args;
12525
+ if (Array.isArray(args[0]) && "__compiled__" in args[0])
12526
+ return args[0];
12527
+ return callback();
12528
+ }
12534
12529
  var Contract = class {
12535
- constructor(abi, address, providerOrAccount = defaultProvider, cairoVersion = detectCairoVersion(abi)) {
12536
- this.version = "0";
12530
+ constructor(abi, address, providerOrAccount = defaultProvider) {
12537
12531
  this.address = address && address.toLowerCase();
12538
12532
  this.providerOrAccount = providerOrAccount;
12539
12533
  this.callData = new CallData(abi);
12540
12534
  this.structs = CallData.getAbiStruct(abi);
12541
12535
  this.abi = abi;
12542
- this.version = cairoVersion;
12543
12536
  const options = { enumerable: true, value: {}, writable: false };
12544
12537
  Object.defineProperties(this, {
12545
12538
  functions: { enumerable: true, value: {}, writable: false },
@@ -12596,15 +12589,21 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12596
12589
  }
12597
12590
  return this;
12598
12591
  }
12599
- async call(method, args = [], options = { parseRequest: true, parseResponse: true, formatResponse: void 0 }) {
12592
+ async call(method, args = [], {
12593
+ parseRequest = true,
12594
+ parseResponse = true,
12595
+ formatResponse = void 0,
12596
+ blockIdentifier = void 0
12597
+ } = {}) {
12600
12598
  assert2(this.address !== null, "contract is not connected to an address");
12601
- const blockIdentifier = (options == null ? void 0 : options.blockIdentifier) || void 0;
12602
- let calldata = "compiled" in args ? args : args[0];
12603
- if (options.parseRequest && !(calldata == null ? void 0 : calldata.compiled)) {
12604
- const { inputs } = this.abi.find((abi) => abi.name === method);
12605
- this.callData.validate("CALL", method, args);
12606
- calldata = this.callData.compile(args, inputs);
12607
- }
12599
+ const calldata = getCalldata(args, () => {
12600
+ if (parseRequest) {
12601
+ this.callData.validate("CALL", method, args);
12602
+ return this.callData.compile(method, args);
12603
+ }
12604
+ console.warn("Call skipped parsing but provided rawArgs, possible malfunction request");
12605
+ return args;
12606
+ });
12608
12607
  return this.providerOrAccount.callContract(
12609
12608
  {
12610
12609
  contractAddress: this.address,
@@ -12613,25 +12612,25 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12613
12612
  },
12614
12613
  blockIdentifier
12615
12614
  ).then((x) => {
12616
- if (!options.parseResponse) {
12615
+ if (!parseResponse) {
12617
12616
  return x.result;
12618
12617
  }
12619
- if (options.formatResponse) {
12620
- return this.callData.format(method, x.result, options.formatResponse);
12618
+ if (formatResponse) {
12619
+ return this.callData.format(method, x.result, formatResponse);
12621
12620
  }
12622
12621
  return this.callData.parse(method, x.result);
12623
12622
  });
12624
12623
  }
12625
- invoke(method, args = [], options = {
12626
- parseRequest: true
12627
- }) {
12624
+ invoke(method, args = [], { parseRequest = true, maxFee, nonce, signature } = {}) {
12628
12625
  assert2(this.address !== null, "contract is not connected to an address");
12629
- let calldata = "compiled" in args ? args : args[0];
12630
- if (options.parseRequest && !(calldata == null ? void 0 : calldata.compiled)) {
12631
- const { inputs } = this.abi.find((abi) => abi.name === method);
12632
- this.callData.validate("INVOKE", method, args);
12633
- calldata = this.callData.compile(args, inputs);
12634
- }
12626
+ const calldata = getCalldata(args, () => {
12627
+ if (parseRequest) {
12628
+ this.callData.validate("INVOKE", method, args);
12629
+ return this.callData.compile(method, args);
12630
+ }
12631
+ console.warn("Invoke skipped parsing but provided rawArgs, possible malfunction request");
12632
+ return args;
12633
+ });
12635
12634
  const invocation = {
12636
12635
  contractAddress: this.address,
12637
12636
  calldata,
@@ -12639,40 +12638,36 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12639
12638
  };
12640
12639
  if ("execute" in this.providerOrAccount) {
12641
12640
  return this.providerOrAccount.execute(invocation, void 0, {
12642
- maxFee: options.maxFee,
12643
- nonce: options.nonce
12641
+ maxFee,
12642
+ nonce
12644
12643
  });
12645
12644
  }
12646
- if (!options.nonce) {
12645
+ if (!nonce)
12647
12646
  throw new Error(`Nonce is required when invoking a function without an account`);
12648
- }
12649
12647
  console.warn(`Invoking ${method} without an account. This will not work on a public node.`);
12650
12648
  return this.providerOrAccount.invokeFunction(
12651
12649
  {
12652
12650
  ...invocation,
12653
- signature: options.signature
12651
+ signature
12654
12652
  },
12655
12653
  {
12656
- nonce: options.nonce
12654
+ nonce
12657
12655
  }
12658
12656
  );
12659
12657
  }
12660
12658
  async estimate(method, args = []) {
12661
- var _a;
12662
12659
  assert2(this.address !== null, "contract is not connected to an address");
12663
- if (!((_a = args[0]) == null ? void 0 : _a.compiled)) {
12660
+ if (!getCalldata(args, () => false)) {
12664
12661
  this.callData.validate("INVOKE", method, args);
12665
12662
  }
12666
- const invocation = this.populateTransaction[method](...args);
12663
+ const invocation = this.populate(method, args);
12667
12664
  if ("estimateInvokeFee" in this.providerOrAccount) {
12668
12665
  return this.providerOrAccount.estimateInvokeFee(invocation);
12669
12666
  }
12670
12667
  throw Error("Contract must be connected to the account contract to estimate");
12671
12668
  }
12672
12669
  populate(method, args = []) {
12673
- var _a;
12674
- const { inputs } = this.abi.find((abi) => abi.name === method);
12675
- const calldata = ((_a = args == null ? void 0 : args[0]) == null ? void 0 : _a.compiled) ? args == null ? void 0 : args[0] : this.callData.compile(args, inputs);
12670
+ const calldata = getCalldata(args, () => this.callData.compile(method, args));
12676
12671
  return {
12677
12672
  contractAddress: this.address,
12678
12673
  entrypoint: method,
@@ -12692,36 +12687,24 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12692
12687
  this.compiledContract = compiledContract;
12693
12688
  this.account = account;
12694
12689
  this.classHash = classHash;
12695
- this.callData = new CallData(abi);
12690
+ this.CallData = new CallData(abi);
12696
12691
  }
12697
12692
  async deploy(...args) {
12698
- var _a;
12699
- let constructorCalldata;
12700
- let parseRequest = true;
12701
- let addressSalt;
12702
- args.forEach((arg) => {
12703
- if (typeof arg !== "object")
12704
- return;
12705
- if ("addressSalt" in arg) {
12706
- addressSalt = arg.addressSalt;
12707
- }
12708
- if ("parseRequest" in arg) {
12709
- parseRequest = arg.parseRequest;
12710
- }
12693
+ const { args: param, options = { parseRequest: true } } = splitArgsAndOptions(args);
12694
+ const constructorCalldata = getCalldata(param, () => {
12695
+ if (options.parseRequest) {
12696
+ this.CallData.validate("DEPLOY", "constructor", param);
12697
+ return this.CallData.compile("constructor", param);
12698
+ }
12699
+ console.warn("Call skipped parsing but provided rawArgs, possible malfunction request");
12700
+ return param;
12711
12701
  });
12712
- if (!parseRequest || ((_a = args[0]) == null ? void 0 : _a.compiled)) {
12713
- constructorCalldata = args[0];
12714
- } else {
12715
- this.callData.validate("DEPLOY", "constructor", args);
12716
- const { inputs } = this.abi.find((abi) => abi.type === "constructor");
12717
- constructorCalldata = this.callData.compile(args, inputs);
12718
- }
12719
12702
  const {
12720
12703
  deploy: { contract_address, transaction_hash }
12721
12704
  } = await this.account.declareAndDeploy({
12722
12705
  contract: this.compiledContract,
12723
12706
  constructorCalldata,
12724
- salt: addressSalt
12707
+ salt: options.addressSalt
12725
12708
  });
12726
12709
  assert2(Boolean(contract_address), "Deployment of the contract failed");
12727
12710
  const contractInstance = new Contract(
@@ -13349,7 +13332,7 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
13349
13332
  unique = true,
13350
13333
  constructorCalldata = []
13351
13334
  } = it;
13352
- const compiledConstructorCallData = compileCalldata(constructorCalldata);
13335
+ const compiledConstructorCallData = CallData.compile(constructorCalldata);
13353
13336
  const deploySalt = salt ?? randomAddress();
13354
13337
  return {
13355
13338
  call: {
@@ -13373,7 +13356,10 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
13373
13356
  });
13374
13357
  const calls = params.map((it) => it.call);
13375
13358
  const addresses = params.map((it) => it.address);
13376
- const invokeResponse = await this.execute(calls, void 0, details);
13359
+ const invokeResponse = await this.execute(calls, void 0, {
13360
+ ...details,
13361
+ cairoVersion: "0"
13362
+ });
13377
13363
  return {
13378
13364
  ...invokeResponse,
13379
13365
  contract_address: addresses
@@ -13445,7 +13431,7 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
13445
13431
  await this.callContract({
13446
13432
  contractAddress: this.address,
13447
13433
  entrypoint: "isValidSignature",
13448
- calldata: compileCalldata({
13434
+ calldata: CallData.compile({
13449
13435
  hash: toBigInt(hash2).toString(),
13450
13436
  signature: formatSignature(signature)
13451
13437
  })
@@ -13531,7 +13517,7 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
13531
13517
  unique = true,
13532
13518
  constructorCalldata = []
13533
13519
  } = it;
13534
- const compiledConstructorCallData = compileCalldata(constructorCalldata);
13520
+ const compiledConstructorCallData = CallData.compile(constructorCalldata);
13535
13521
  return {
13536
13522
  contractAddress: UDC.ADDRESS,
13537
13523
  entrypoint: UDC.ENTRYPOINT,