starknet 5.6.1 → 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,7 +646,9 @@ var starknet = (() => {
645
646
  num: () => num_exports,
646
647
  number: () => number2,
647
648
  shortString: () => shortString_exports,
649
+ splitArgsAndOptions: () => splitArgsAndOptions,
648
650
  stark: () => stark_exports,
651
+ starknetId: () => starknetId_exports,
649
652
  transaction: () => transaction_exports,
650
653
  typedData: () => typedData_exports,
651
654
  uint256: () => uint256_exports,
@@ -5559,6 +5562,9 @@ var starknet = (() => {
5559
5562
  if (typeof it === "string" && isStringWholeNumber(it)) {
5560
5563
  return it;
5561
5564
  }
5565
+ if (typeof it === "boolean") {
5566
+ return `${+it}`;
5567
+ }
5562
5568
  throw new Error(`${it} can't be computed by felt()`);
5563
5569
  }
5564
5570
 
@@ -6489,7 +6495,6 @@ var starknet = (() => {
6489
6495
  // src/utils/stark.ts
6490
6496
  var stark_exports = {};
6491
6497
  __export(stark_exports, {
6492
- compileCalldata: () => compileCalldata,
6493
6498
  compressProgram: () => compressProgram,
6494
6499
  estimatedFeeToMaxFee: () => estimatedFeeToMaxFee,
6495
6500
  formatSignature: () => formatSignature,
@@ -10605,21 +10610,6 @@ var starknet = (() => {
10605
10610
  function signatureToHexArray(sig) {
10606
10611
  return bigNumberishArrayToHexadecimalStringArray(formatSignature(sig));
10607
10612
  }
10608
- function compileCalldata(args) {
10609
- const compiledData = Object.values(args).flatMap((value) => {
10610
- if (Array.isArray(value))
10611
- return [toBigInt(value.length).toString(), ...value.map((x) => toBigInt(x).toString())];
10612
- if (typeof value === "object" && "type" in value)
10613
- return Object.entries(value).filter(([k]) => k !== "type").map(([, v]) => toBigInt(v).toString());
10614
- return toBigInt(value).toString();
10615
- });
10616
- Object.defineProperty(compiledData, "compiled", {
10617
- enumerable: false,
10618
- writable: false,
10619
- value: true
10620
- });
10621
- return compiledData;
10622
- }
10623
10613
  function estimatedFeeToMaxFee(estimatedFee, overhead = 0.5) {
10624
10614
  const overHeadPercent = Math.round((1 + overhead) * 100);
10625
10615
  return toBigInt(estimatedFee) * toBigInt(overHeadPercent) / 100n;
@@ -10733,308 +10723,826 @@ var starknet = (() => {
10733
10723
  }
10734
10724
  };
10735
10725
 
10736
- // src/utils/starknetId.ts
10737
- var basicAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789-";
10738
- var basicSizePlusOne = BigInt(basicAlphabet.length + 1);
10739
- var bigAlphabet = "\u8FD9\u6765";
10740
- var basicAlphabetSize = BigInt(basicAlphabet.length);
10741
- var bigAlphabetSize = BigInt(bigAlphabet.length);
10742
- var bigAlphabetSizePlusOne = BigInt(bigAlphabet.length + 1);
10743
- function extractStars(str) {
10744
- let k = 0;
10745
- while (str.endsWith(bigAlphabet[bigAlphabet.length - 1])) {
10746
- str = str.substring(0, str.length - 1);
10747
- 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]}`);
10748
10736
  }
10749
- return [str, k];
10750
- }
10751
- function useDecoded(encoded) {
10752
- let decoded = "";
10753
- encoded.forEach((subdomain) => {
10754
- while (subdomain !== ZERO) {
10755
- const code = subdomain % basicSizePlusOne;
10756
- subdomain /= basicSizePlusOne;
10757
- if (code === BigInt(basicAlphabet.length)) {
10758
- const nextSubdomain = subdomain / bigAlphabetSizePlusOne;
10759
- if (nextSubdomain === ZERO) {
10760
- const code2 = subdomain % bigAlphabetSizePlusOne;
10761
- subdomain = nextSubdomain;
10762
- if (code2 === ZERO)
10763
- decoded += basicAlphabet[0];
10764
- else
10765
- decoded += bigAlphabet[Number(code2) - 1];
10766
- } else {
10767
- const code2 = subdomain % bigAlphabetSize;
10768
- decoded += bigAlphabet[Number(code2)];
10769
- subdomain /= bigAlphabetSize;
10770
- }
10771
- } else
10772
- 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;
10773
10744
  }
10774
- const [str, k] = extractStars(decoded);
10775
- if (k)
10776
- 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));
10777
- decoded += ".";
10778
- });
10779
- if (!decoded) {
10780
- return decoded;
10781
- }
10782
- 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
+ }, {});
10783
10779
  }
10784
- function useEncoded(decoded) {
10785
- let encoded = BigInt(0);
10786
- let multiplier = BigInt(1);
10787
- if (decoded.endsWith(bigAlphabet[0] + basicAlphabet[1])) {
10788
- const [str, k] = extractStars(decoded.substring(0, decoded.length - 2));
10789
- decoded = str + bigAlphabet[bigAlphabet.length - 1].repeat(2 * (k + 1));
10790
- } else {
10791
- const [str, k] = extractStars(decoded);
10792
- if (k)
10793
- decoded = str + bigAlphabet[bigAlphabet.length - 1].repeat(1 + 2 * (k - 1));
10794
- }
10795
- for (let i = 0; i < decoded.length; i += 1) {
10796
- const char = decoded[i];
10797
- const index = basicAlphabet.indexOf(char);
10798
- const bnIndex = BigInt(basicAlphabet.indexOf(char));
10799
- if (index !== -1) {
10800
- if (i === decoded.length - 1 && decoded[i] === basicAlphabet[0]) {
10801
- encoded += multiplier * basicAlphabetSize;
10802
- multiplier *= basicSizePlusOne;
10803
- multiplier *= basicSizePlusOne;
10804
- } else {
10805
- encoded += multiplier * bnIndex;
10806
- 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++;
10807
10804
  }
10808
- } else if (bigAlphabet.indexOf(char) !== -1) {
10809
- encoded += multiplier * basicAlphabetSize;
10810
- multiplier *= basicSizePlusOne;
10811
- const newid = (i === decoded.length - 1 ? 1 : 0) + bigAlphabet.indexOf(char);
10812
- encoded += multiplier * BigInt(newid);
10813
- multiplier *= bigAlphabetSize;
10805
+ subTuple.push(s.substring(lBracket, i));
10806
+ result += " ";
10807
+ i--;
10808
+ } else {
10809
+ result += s[i];
10814
10810
  }
10811
+ i++;
10815
10812
  }
10816
- return encoded;
10813
+ return {
10814
+ subTuple,
10815
+ result
10816
+ };
10817
10817
  }
10818
- function getStarknetIdContract(chainId) {
10819
- const starknetIdMainnetContract = "0x6ac597f8116f886fa1c97a23fa4e08299975ecaf6b598873ca6792b9bbfb678";
10820
- const starknetIdTestnetContract = "0x3bab268e932d2cecd1946f100ae67ce3dff9fd234119ea2f6da57d16d29fce";
10821
- switch (chainId) {
10822
- case "0x534e5f4d41494e" /* SN_MAIN */:
10823
- return starknetIdMainnetContract;
10824
- case "0x534e5f474f45524c49" /* SN_GOERLI */:
10825
- return starknetIdTestnetContract;
10826
- default:
10827
- 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
+ }, []);
10828
10828
  }
10829
+ return recomposed;
10829
10830
  }
10830
-
10831
- // src/provider/starknetId.ts
10832
- async function getStarkName(provider, address, StarknetIdContract) {
10833
- const chainId = await provider.getChainId();
10834
- const contract = StarknetIdContract ?? getStarknetIdContract(chainId);
10835
- try {
10836
- const hexDomain = await provider.callContract({
10837
- contractAddress: contract,
10838
- entrypoint: "address_to_domain",
10839
- calldata: compileCalldata({
10840
- address
10841
- })
10842
- });
10843
- const decimalDomain = hexDomain.result.map((element) => BigInt(element)).slice(1);
10844
- const stringDomain = useDecoded(decimalDomain);
10845
- if (!stringDomain) {
10846
- throw Error("Starkname not found");
10847
- }
10848
- return stringDomain;
10849
- } catch (e) {
10850
- if (e instanceof Error && e.message === "Starkname not found") {
10851
- throw e;
10852
- }
10853
- throw Error("Could not get stark name");
10854
- }
10831
+ function extractCairo1Tuple(type) {
10832
+ const cleanType = type.replace(/\s/g, "").slice(1, -1);
10833
+ return cleanType.split(",");
10855
10834
  }
10856
- async function getAddressFromStarkName(provider, name, StarknetIdContract) {
10857
- const chainId = await provider.getChainId();
10858
- const contract = StarknetIdContract ?? getStarknetIdContract(chainId);
10859
- try {
10860
- const addressData = await provider.callContract({
10861
- contractAddress: contract,
10862
- entrypoint: "domain_to_address",
10863
- calldata: compileCalldata({
10864
- domain: [useEncoded(name.replace(".stark", "")).toString(10)]
10865
- })
10866
- });
10867
- return addressData.result[0];
10868
- } catch {
10869
- throw Error("Could not get address from stark name");
10835
+ function extractTupleMemberTypes(type) {
10836
+ if (isCairo1Type(type)) {
10837
+ return extractCairo1Tuple(type);
10870
10838
  }
10839
+ return extractCairo0Tuple(type);
10871
10840
  }
10872
10841
 
10873
- // src/provider/utils.ts
10874
- var validBlockTags = ["latest", "pending"];
10875
- var Block = class {
10876
- constructor(_identifier) {
10877
- this.hash = null;
10878
- this.number = null;
10879
- this.tag = null;
10880
- this.valueOf = () => this.number;
10881
- this.toString = () => this.hash;
10882
- this.setIdentifier(_identifier);
10883
- }
10884
- setIdentifier(__identifier) {
10885
- if (typeof __identifier === "string" && isHex(__identifier)) {
10886
- this.hash = __identifier;
10887
- } else if (typeof __identifier === "bigint") {
10888
- this.hash = toHex(__identifier);
10889
- } else if (typeof __identifier === "number") {
10890
- this.number = __identifier;
10891
- } else if (typeof __identifier === "string" && validBlockTags.includes(__identifier)) {
10892
- this.tag = __identifier;
10893
- } else {
10894
- this.tag = "pending";
10895
- }
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}`
10851
+ );
10896
10852
  }
10897
- get queryIdentifier() {
10898
- if (this.number !== null) {
10899
- return `blockNumber=${this.number}`;
10900
- }
10901
- if (this.hash !== null) {
10902
- return `blockHash=${this.hash}`;
10903
- }
10904
- return `blockNumber=${this.tag}`;
10905
- }
10906
- get identifier() {
10907
- if (this.number !== null) {
10908
- return { block_number: this.number };
10909
- }
10910
- if (this.hash !== null) {
10911
- return { block_hash: this.hash };
10912
- }
10913
- return this.tag;
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}`);
10914
10863
  }
10915
- set identifier(_identifier) {
10916
- this.setIdentifier(_identifier);
10864
+ if (Array.isArray(element)) {
10865
+ throw Error(`Array inside array (nD) are not supported by cairo. Element: ${element} ${type}`);
10917
10866
  }
10918
- get sequencerIdentifier() {
10919
- return this.hash !== null ? { blockHash: this.hash } : { blockNumber: this.number ?? this.tag };
10867
+ if (isTypeUint256(type)) {
10868
+ const el_uint256 = uint256(element);
10869
+ return [felt(el_uint256.low), felt(el_uint256.high)];
10920
10870
  }
10921
- };
10922
-
10923
- // src/provider/rpc.ts
10924
- var defaultOptions = {
10925
- headers: { "Content-Type": "application/json" },
10926
- blockIdentifier: "latest",
10927
- retries: 200
10928
- };
10929
- var RpcProvider = class {
10930
- constructor(optionsOrProvider) {
10931
- this.responseParser = new RPCResponseParser();
10932
- const { nodeUrl, retries, headers, blockIdentifier } = optionsOrProvider;
10933
- this.nodeUrl = nodeUrl;
10934
- this.retries = retries || defaultOptions.retries;
10935
- this.headers = { ...defaultOptions.headers, ...headers };
10936
- this.blockIdentifier = blockIdentifier || defaultOptions.blockIdentifier;
10937
- this.getChainId();
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
+ }, []);
10938
10877
  }
10939
- fetch(method, params) {
10940
- return fetchPonyfill_default(this.nodeUrl, {
10941
- method: "POST",
10942
- body: stringify2({ method, jsonrpc: "2.0", params, id: 0 }),
10943
- headers: this.headers
10944
- });
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
+ }, []);
10945
10884
  }
10946
- errorHandler(error) {
10947
- if (error) {
10948
- const { code, message } = error;
10949
- throw new LibraryError(`${code}: ${message}`);
10950
- }
10885
+ if (typeof element === "object") {
10886
+ throw Error(`Parameter ${element} do not align with abi parameter ${type}`);
10951
10887
  }
10952
- async fetchEndpoint(method, params) {
10953
- var _a;
10954
- try {
10955
- const rawResult = await this.fetch(method, params);
10956
- const { error, result } = await rawResult.json();
10957
- this.errorHandler(error);
10958
- return result;
10959
- } catch (error) {
10960
- this.errorHandler((_a = error == null ? void 0 : error.response) == null ? void 0 : _a.data);
10961
- throw error;
10962
- }
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);
10963
10920
  }
10964
- async getChainId() {
10965
- this.chainId ?? (this.chainId = await this.fetchEndpoint("starknet_chainId"));
10966
- return this.chainId;
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
+ }, {});
10967
10930
  }
10968
- async getBlock(blockIdentifier = this.blockIdentifier) {
10969
- return this.getBlockWithTxHashes(blockIdentifier).then(
10970
- this.responseParser.parseGetBlockResponse
10971
- );
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
+ }, {});
10972
10939
  }
10973
- async getBlockHashAndNumber() {
10974
- return this.fetchEndpoint("starknet_blockHashAndNumber");
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);
10975
10982
  }
10976
- async getBlockWithTxHashes(blockIdentifier = this.blockIdentifier) {
10977
- const block_id = new Block(blockIdentifier).identifier;
10978
- return this.fetchEndpoint("starknet_getBlockWithTxHashes", { block_id });
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
+ );
10979
10998
  }
10980
- async getBlockWithTxs(blockIdentifier = this.blockIdentifier) {
10981
- const block_id = new Block(blockIdentifier).identifier;
10982
- return this.fetchEndpoint("starknet_getBlockWithTxs", { 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;
10983
11043
  }
10984
- async getClassHashAt(contractAddress, blockIdentifier = this.blockIdentifier) {
10985
- const block_id = new Block(blockIdentifier).identifier;
10986
- return this.fetchEndpoint("starknet_getClassHashAt", {
10987
- block_id,
10988
- contract_address: contractAddress
10989
- });
10990
- }
10991
- async getNonceForAddress(contractAddress, blockIdentifier = this.blockIdentifier) {
10992
- const block_id = new Block(blockIdentifier).identifier;
10993
- return this.fetchEndpoint("starknet_getNonce", {
10994
- contract_address: contractAddress,
10995
- block_id
10996
- });
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
+ );
10997
11096
  }
10998
- async getPendingTransactions() {
10999
- return this.fetchEndpoint("starknet_pendingTransactions");
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);
11000
11138
  }
11001
- async getProtocolVersion() {
11002
- throw new Error("Pathfinder does not implement this rpc 0.1.0 method");
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);
11003
11162
  }
11004
- async getStateUpdate(blockIdentifier = this.blockIdentifier) {
11005
- const block_id = new Block(blockIdentifier).identifier;
11006
- return this.fetchEndpoint("starknet_getStateUpdate", { block_id });
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
+ );
11007
11170
  }
11008
- async getStorageAt(contractAddress, key, blockIdentifier = this.blockIdentifier) {
11009
- const parsedKey = toHex(key);
11010
- const block_id = new Block(blockIdentifier).identifier;
11011
- return this.fetchEndpoint("starknet_getStorageAt", {
11012
- contract_address: contractAddress,
11013
- key: parsedKey,
11014
- block_id
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);
11195
+ }
11196
+ Object.defineProperty(callTreeArray, "__compiled__", {
11197
+ enumerable: false,
11198
+ writable: false,
11199
+ value: true
11015
11200
  });
11201
+ return callTreeArray;
11016
11202
  }
11017
- async getTransaction(txHash) {
11018
- return this.getTransactionByHash(txHash).then(this.responseParser.parseGetTransactionResponse);
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`];
11211
+ }
11212
+ return acc;
11213
+ }, {});
11214
+ return Object.keys(parsed).length === 1 && 0 in parsed ? parsed[0] : parsed;
11019
11215
  }
11020
- async getTransactionByHash(txHash) {
11021
- return this.fetchEndpoint("starknet_getTransactionByHash", { transaction_hash: txHash });
11216
+ format(method, response, format) {
11217
+ const parsed = this.parse(method, response);
11218
+ return formatter(parsed, format);
11022
11219
  }
11023
- async getTransactionByBlockIdAndIndex(blockIdentifier, index) {
11024
- const block_id = new Block(blockIdentifier).identifier;
11025
- return this.fetchEndpoint("starknet_getTransactionByBlockIdAndIndex", { block_id, index });
11220
+ static abiInputsLength(inputs) {
11221
+ return inputs.reduce((acc, input) => !isLen(input.name) ? acc + 1 : acc, 0);
11026
11222
  }
11027
- async getTransactionReceipt(txHash) {
11028
- return this.fetchEndpoint("starknet_getTransactionReceipt", { transaction_hash: txHash });
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
+ );
11029
11231
  }
11030
- async getClassByHash(classHash) {
11031
- return this.getClass(classHash);
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;
11032
11253
  }
11033
- async getClass(classHash, blockIdentifier = this.blockIdentifier) {
11034
- const block_id = new Block(blockIdentifier).identifier;
11035
- return this.fetchEndpoint("starknet_getClass", { class_hash: classHash, block_id });
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;
11275
+ }
11276
+ } else
11277
+ decoded += basicAlphabet[Number(code)];
11278
+ }
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;
11036
11286
  }
11037
- async getClassAt(contractAddress, blockIdentifier = this.blockIdentifier) {
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));
11299
+ }
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
+ }
11320
+ }
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");
11336
+ }
11337
+ }
11338
+
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
+ }
11380
+
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);
11391
+ }
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
+ }
11404
+ }
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}`;
11413
+ }
11414
+ get identifier() {
11415
+ if (this.number !== null) {
11416
+ return { block_number: this.number };
11417
+ }
11418
+ if (this.hash !== null) {
11419
+ return { block_hash: this.hash };
11420
+ }
11421
+ return this.tag;
11422
+ }
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
11452
+ });
11453
+ }
11454
+ errorHandler(error) {
11455
+ if (error) {
11456
+ const { code, message } = error;
11457
+ throw new LibraryError(`${code}: ${message}`);
11458
+ }
11459
+ }
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
+ }
11471
+ }
11472
+ async getChainId() {
11473
+ this.chainId ?? (this.chainId = await this.fetchEndpoint("starknet_chainId"));
11474
+ return this.chainId;
11475
+ }
11476
+ async getBlock(blockIdentifier = this.blockIdentifier) {
11477
+ return this.getBlockWithTxHashes(blockIdentifier).then(
11478
+ this.responseParser.parseGetBlockResponse
11479
+ );
11480
+ }
11481
+ async getBlockHashAndNumber() {
11482
+ return this.fetchEndpoint("starknet_blockHashAndNumber");
11483
+ }
11484
+ async getBlockWithTxHashes(blockIdentifier = this.blockIdentifier) {
11485
+ const block_id = new Block(blockIdentifier).identifier;
11486
+ return this.fetchEndpoint("starknet_getBlockWithTxHashes", { block_id });
11487
+ }
11488
+ async getBlockWithTxs(blockIdentifier = this.blockIdentifier) {
11489
+ const block_id = new Block(blockIdentifier).identifier;
11490
+ return this.fetchEndpoint("starknet_getBlockWithTxs", { block_id });
11491
+ }
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
+ });
11498
+ }
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
+ });
11505
+ }
11506
+ async getPendingTransactions() {
11507
+ return this.fetchEndpoint("starknet_pendingTransactions");
11508
+ }
11509
+ async getProtocolVersion() {
11510
+ throw new Error("Pathfinder does not implement this rpc 0.1.0 method");
11511
+ }
11512
+ async getStateUpdate(blockIdentifier = this.blockIdentifier) {
11513
+ const block_id = new Block(blockIdentifier).identifier;
11514
+ return this.fetchEndpoint("starknet_getStateUpdate", { block_id });
11515
+ }
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
+ });
11524
+ }
11525
+ async getTransaction(txHash) {
11526
+ return this.getTransactionByHash(txHash).then(this.responseParser.parseGetTransactionResponse);
11527
+ }
11528
+ async getTransactionByHash(txHash) {
11529
+ return this.fetchEndpoint("starknet_getTransactionByHash", { transaction_hash: txHash });
11530
+ }
11531
+ async getTransactionByBlockIdAndIndex(blockIdentifier, index) {
11532
+ const block_id = new Block(blockIdentifier).identifier;
11533
+ return this.fetchEndpoint("starknet_getTransactionByBlockIdAndIndex", { block_id, index });
11534
+ }
11535
+ async getTransactionReceipt(txHash) {
11536
+ return this.fetchEndpoint("starknet_getTransactionReceipt", { transaction_hash: txHash });
11537
+ }
11538
+ async getClassByHash(classHash) {
11539
+ return this.getClass(classHash);
11540
+ }
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 });
11544
+ }
11545
+ async getClassAt(contractAddress, blockIdentifier = this.blockIdentifier) {
11038
11546
  const block_id = new Block(blockIdentifier).identifier;
11039
11547
  return this.fetchEndpoint("starknet_getClassAt", {
11040
11548
  block_id,
@@ -11224,11 +11732,11 @@ var starknet = (() => {
11224
11732
  async getSimulateTransaction(_invocation, _invocationDetails, _blockIdentifier) {
11225
11733
  throw new Error("RPC does not implement simulateTransaction function");
11226
11734
  }
11227
- async getStarkName(address, StarknetIdContract) {
11228
- return getStarkName(this, address, StarknetIdContract);
11735
+ async getStarkName(address, StarknetIdContract2) {
11736
+ return getStarkName(this, address, StarknetIdContract2);
11229
11737
  }
11230
- async getAddressFromStarkName(name, StarknetIdContract) {
11231
- return getAddressFromStarkName(this, name, StarknetIdContract);
11738
+ async getAddressFromStarkName(name, StarknetIdContract2) {
11739
+ return getAddressFromStarkName(this, name, StarknetIdContract2);
11232
11740
  }
11233
11741
  };
11234
11742
 
@@ -11759,710 +12267,205 @@ var starknet = (() => {
11759
12267
  signature: bigNumberishArrayToDecimalStringArray(formatSignature(invocation.signature)),
11760
12268
  version: toHex(toBigInt((invocation == null ? void 0 : invocation.version) || 1)),
11761
12269
  nonce: toHex(toBigInt(invocation.nonce))
11762
- };
11763
- });
11764
- return this.fetchEndpoint("estimate_fee_bulk", { blockIdentifier }, params).then(
11765
- this.responseParser.parseFeeEstimateBulkResponse
11766
- );
11767
- }
11768
- async getCode(contractAddress, blockIdentifier = this.blockIdentifier) {
11769
- return this.fetchEndpoint("get_code", { contractAddress, blockIdentifier });
11770
- }
11771
- async waitForTransaction(txHash, options) {
11772
- const errorStates = ["REJECTED" /* REJECTED */, "NOT_RECEIVED" /* NOT_RECEIVED */];
11773
- let onchain = false;
11774
- let res;
11775
- const retryInterval = (options == null ? void 0 : options.retryInterval) ?? 8e3;
11776
- const successStates = (options == null ? void 0 : options.successStates) ?? [
11777
- "ACCEPTED_ON_L1" /* ACCEPTED_ON_L1 */,
11778
- "ACCEPTED_ON_L2" /* ACCEPTED_ON_L2 */,
11779
- "PENDING" /* PENDING */
11780
- ];
11781
- while (!onchain) {
11782
- await wait(retryInterval);
11783
- res = await this.getTransactionStatus(txHash);
11784
- if (successStates.includes(res.tx_status)) {
11785
- onchain = true;
11786
- } else if (errorStates.includes(res.tx_status)) {
11787
- const message = res.tx_failure_reason ? `${res.tx_status}: ${res.tx_failure_reason.code}
11788
- ${res.tx_failure_reason.error_message}` : res.tx_status;
11789
- const error = new Error(message);
11790
- error.response = res;
11791
- throw error;
11792
- }
11793
- }
11794
- const txReceipt = await this.getTransactionReceipt(txHash);
11795
- return txReceipt;
11796
- }
11797
- async getTransactionStatus(txHash) {
11798
- const txHashHex = toHex(txHash);
11799
- return this.fetchEndpoint("get_transaction_status", { transactionHash: txHashHex });
11800
- }
11801
- async getContractAddresses() {
11802
- return this.fetchEndpoint("get_contract_addresses");
11803
- }
11804
- async getTransactionTrace(txHash) {
11805
- const txHashHex = toHex(txHash);
11806
- return this.fetchEndpoint("get_transaction_trace", { transactionHash: txHashHex });
11807
- }
11808
- async estimateMessageFee({ from_address, to_address, entry_point_selector, payload }, blockIdentifier = this.blockIdentifier) {
11809
- const validCallL1Handler = {
11810
- from_address: getDecimalString(from_address),
11811
- to_address: getHexString(to_address),
11812
- entry_point_selector: getSelector(entry_point_selector),
11813
- payload: getHexStringArray(payload)
11814
- };
11815
- return this.fetchEndpoint("estimate_message_fee", { blockIdentifier }, validCallL1Handler);
11816
- }
11817
- async getSimulateTransaction(invocation, invocationDetails, blockIdentifier = this.blockIdentifier, skipValidate = false) {
11818
- return this.fetchEndpoint(
11819
- "simulate_transaction",
11820
- { blockIdentifier, skipValidate },
11821
- {
11822
- type: "INVOKE_FUNCTION",
11823
- sender_address: invocation.contractAddress,
11824
- calldata: invocation.calldata ?? [],
11825
- signature: signatureToDecimalArray(invocation.signature),
11826
- version: toHex((invocationDetails == null ? void 0 : invocationDetails.version) || 1),
11827
- nonce: toHex(invocationDetails.nonce),
11828
- max_fee: toHex((invocationDetails == null ? void 0 : invocationDetails.maxFee) || 0)
11829
- }
11830
- ).then(this.responseParser.parseFeeSimulateTransactionResponse);
11831
- }
11832
- async getStateUpdate(blockIdentifier = this.blockIdentifier) {
11833
- const args = new Block(blockIdentifier).sequencerIdentifier;
11834
- return this.fetchEndpoint("get_state_update", { ...args }).then(
11835
- this.responseParser.parseGetStateUpdateResponse
11836
- );
11837
- }
11838
- async getBlockTraces(blockIdentifier = this.blockIdentifier) {
11839
- const args = new Block(blockIdentifier).sequencerIdentifier;
11840
- return this.fetchEndpoint("get_block_traces", { ...args });
11841
- }
11842
- async getStarkName(address, StarknetIdContract) {
11843
- return getStarkName(this, address, StarknetIdContract);
11844
- }
11845
- async getAddressFromStarkName(name, StarknetIdContract) {
11846
- return getAddressFromStarkName(this, name, StarknetIdContract);
11847
- }
11848
- };
11849
-
11850
- // src/provider/default.ts
11851
- var Provider = class {
11852
- constructor(providerOrOptions) {
11853
- if (providerOrOptions instanceof Provider) {
11854
- this.provider = providerOrOptions.provider;
11855
- } else if (providerOrOptions instanceof RpcProvider || providerOrOptions instanceof SequencerProvider) {
11856
- this.provider = providerOrOptions;
11857
- } else if (providerOrOptions && "rpc" in providerOrOptions) {
11858
- this.provider = new RpcProvider(providerOrOptions.rpc);
11859
- } else if (providerOrOptions && "sequencer" in providerOrOptions) {
11860
- this.provider = new SequencerProvider(providerOrOptions.sequencer);
11861
- } else {
11862
- this.provider = new SequencerProvider();
11863
- }
11864
- }
11865
- async getChainId() {
11866
- return this.provider.getChainId();
11867
- }
11868
- async getBlock(blockIdentifier) {
11869
- return this.provider.getBlock(blockIdentifier);
11870
- }
11871
- async getClassAt(contractAddress, blockIdentifier) {
11872
- return this.provider.getClassAt(contractAddress, blockIdentifier);
11873
- }
11874
- async getClassHashAt(contractAddress, blockIdentifier) {
11875
- return this.provider.getClassHashAt(contractAddress, blockIdentifier);
11876
- }
11877
- getClassByHash(classHash) {
11878
- return this.provider.getClassByHash(classHash);
11879
- }
11880
- async getEstimateFee(invocationWithTxType, invocationDetails, blockIdentifier) {
11881
- return this.provider.getEstimateFee(invocationWithTxType, invocationDetails, blockIdentifier);
11882
- }
11883
- async getInvokeEstimateFee(invocationWithTxType, invocationDetails, blockIdentifier, skipValidate) {
11884
- return this.provider.getInvokeEstimateFee(
11885
- invocationWithTxType,
11886
- invocationDetails,
11887
- blockIdentifier,
11888
- skipValidate
11889
- );
11890
- }
11891
- async getEstimateFeeBulk(invocations, blockIdentifier) {
11892
- return this.provider.getEstimateFeeBulk(invocations, blockIdentifier);
11893
- }
11894
- async getNonceForAddress(contractAddress, blockIdentifier) {
11895
- return this.provider.getNonceForAddress(contractAddress, blockIdentifier);
11896
- }
11897
- async getStorageAt(contractAddress, key, blockIdentifier) {
11898
- return this.provider.getStorageAt(contractAddress, key, blockIdentifier);
11899
- }
11900
- async getTransaction(txHash) {
11901
- return this.provider.getTransaction(txHash);
11902
- }
11903
- async getTransactionReceipt(txHash) {
11904
- return this.provider.getTransactionReceipt(txHash);
11905
- }
11906
- async callContract(request, blockIdentifier) {
11907
- return this.provider.callContract(request, blockIdentifier);
11908
- }
11909
- async invokeFunction(functionInvocation, details) {
11910
- return this.provider.invokeFunction(functionInvocation, details);
11911
- }
11912
- async deployAccountContract(payload, details) {
11913
- return this.provider.deployAccountContract(payload, details);
11914
- }
11915
- async declareContract(transaction, details) {
11916
- return this.provider.declareContract(transaction, details);
11917
- }
11918
- async getDeclareEstimateFee(transaction, details, blockIdentifier, skipValidate) {
11919
- return this.provider.getDeclareEstimateFee(transaction, details, blockIdentifier, skipValidate);
11920
- }
11921
- getDeployAccountEstimateFee(transaction, details, blockIdentifier, skipValidate) {
11922
- return this.provider.getDeployAccountEstimateFee(
11923
- transaction,
11924
- details,
11925
- blockIdentifier,
11926
- skipValidate
11927
- );
11928
- }
11929
- async getCode(contractAddress, blockIdentifier) {
11930
- return this.provider.getCode(contractAddress, blockIdentifier);
11931
- }
11932
- async waitForTransaction(txHash, options) {
11933
- return this.provider.waitForTransaction(txHash, options);
11934
- }
11935
- async getSimulateTransaction(invocation, invocationDetails, blockIdentifier, skipValidate) {
11936
- return this.provider.getSimulateTransaction(
11937
- invocation,
11938
- invocationDetails,
11939
- blockIdentifier,
11940
- skipValidate
11941
- );
11942
- }
11943
- async getStateUpdate(blockIdentifier) {
11944
- return this.provider.getStateUpdate(blockIdentifier);
11945
- }
11946
- async getStarkName(address, StarknetIdContract) {
11947
- return getStarkName(this, address, StarknetIdContract);
11948
- }
11949
- async getAddressFromStarkName(name, StarknetIdContract) {
11950
- return getAddressFromStarkName(this, name, StarknetIdContract);
11951
- }
11952
- };
11953
-
11954
- // src/provider/interface.ts
11955
- var ProviderInterface = class {
11956
- };
11957
-
11958
- // src/provider/index.ts
11959
- var defaultProvider = new Provider();
11960
-
11961
- // src/utils/calldata/formatter.ts
11962
- var guard = {
11963
- isBN: (data, type, key) => {
11964
- if (!isBigInt(data[key]))
11965
- throw new Error(
11966
- `Data and formatter mismatch on ${key}:${type[key]}, expected response data ${key}:${data[key]} to be BN instead it is ${typeof data[key]}`
11967
- );
11968
- },
11969
- unknown: (data, type, key) => {
11970
- throw new Error(`Unhandled formatter type on ${key}:${type[key]} for data ${key}:${data[key]}`);
11971
- }
11972
- };
11973
- function formatter(data, type, sameType) {
11974
- return Object.entries(data).reduce((acc, [key, value]) => {
11975
- const elType = sameType ?? type[key];
11976
- if (!(key in type) && !sameType) {
11977
- acc[key] = value;
11978
- return acc;
11979
- }
11980
- if (elType === "string") {
11981
- if (Array.isArray(data[key])) {
11982
- const arrayStr = formatter(
11983
- data[key],
11984
- data[key].map((_) => elType)
11985
- );
11986
- acc[key] = Object.values(arrayStr).join("");
11987
- return acc;
11988
- }
11989
- guard.isBN(data, type, key);
11990
- acc[key] = decodeShortString(value);
11991
- return acc;
11992
- }
11993
- if (elType === "number") {
11994
- guard.isBN(data, type, key);
11995
- acc[key] = Number(value);
11996
- return acc;
11997
- }
11998
- if (typeof elType === "function") {
11999
- acc[key] = elType(value);
12000
- return acc;
12001
- }
12002
- if (Array.isArray(elType)) {
12003
- const arrayObj = formatter(data[key], elType, elType[0]);
12004
- acc[key] = Object.values(arrayObj);
12005
- return acc;
12006
- }
12007
- if (typeof elType === "object") {
12008
- acc[key] = formatter(data[key], elType);
12009
- return acc;
12010
- }
12011
- guard.unknown(data, type, key);
12012
- return acc;
12013
- }, {});
12014
- }
12015
-
12016
- // src/utils/calldata/tuple.ts
12017
- function parseNamedTuple(namedTuple) {
12018
- const name = namedTuple.substring(0, namedTuple.indexOf(":"));
12019
- const type = namedTuple.substring(name.length + ":".length);
12020
- return { name, type };
12021
- }
12022
- function parseSubTuple(s) {
12023
- if (!s.includes("("))
12024
- return { subTuple: [], result: s };
12025
- const subTuple = [];
12026
- let result = "";
12027
- let i = 0;
12028
- while (i < s.length) {
12029
- if (s[i] === "(") {
12030
- let counter = 1;
12031
- const lBracket = i;
12032
- i++;
12033
- while (counter) {
12034
- if (s[i] === ")")
12035
- counter--;
12036
- if (s[i] === "(")
12037
- counter++;
12038
- i++;
12039
- }
12040
- subTuple.push(s.substring(lBracket, i));
12041
- result += " ";
12042
- i--;
12043
- } else {
12044
- result += s[i];
12045
- }
12046
- i++;
12047
- }
12048
- return {
12049
- subTuple,
12050
- result
12051
- };
12052
- }
12053
- function extractCairo0Tuple(type) {
12054
- const cleanType = type.replace(/\s/g, "").slice(1, -1);
12055
- const { subTuple, result } = parseSubTuple(cleanType);
12056
- let recomposed = result.split(",").map((it) => {
12057
- return subTuple.length ? it.replace(" ", subTuple.shift()) : it;
12058
- });
12059
- if (isTypeNamedTuple(type)) {
12060
- recomposed = recomposed.reduce((acc, it) => {
12061
- return acc.concat(parseNamedTuple(it));
12062
- }, []);
12063
- }
12064
- return recomposed;
12065
- }
12066
- function extractCairo1Tuple(type) {
12067
- const cleanType = type.replace(/\s/g, "").slice(1, -1);
12068
- return cleanType.split(",");
12069
- }
12070
- function extractTupleMemberTypes(type) {
12071
- if (isCairo1Type(type)) {
12072
- return extractCairo1Tuple(type);
12073
- }
12074
- return extractCairo0Tuple(type);
12075
- }
12076
-
12077
- // src/utils/calldata/requestParser.ts
12078
- function parseTuple(element, typeStr) {
12079
- const memberTypes = extractTupleMemberTypes(typeStr);
12080
- const elements = Object.values(element);
12081
- if (elements.length !== memberTypes.length) {
12082
- throw Error(
12083
- `ParseTuple: provided and expected abi tuple size do not match.
12084
- provided: ${elements}
12085
- expected: ${memberTypes}`
12086
- );
12087
- }
12088
- return memberTypes.map((it, dx) => {
12089
- return {
12090
- element: elements[dx],
12091
- type: it.type ?? it
12092
- };
12093
- });
12094
- }
12095
- function parseCalldataValue(element, type, structs) {
12096
- if (element === void 0) {
12097
- throw Error(`Missing parameter for type ${type}`);
12098
- }
12099
- if (Array.isArray(element)) {
12100
- throw Error(`Array inside array (nD) are not supported by cairo. Element: ${element} ${type}`);
12101
- }
12102
- if (isTypeUint256(type)) {
12103
- const el_uint256 = uint256(element);
12104
- return [felt(el_uint256.low), felt(el_uint256.high)];
12105
- }
12106
- if (structs[type] && structs[type].members.length) {
12107
- const { members } = structs[type];
12108
- const subElement = element;
12109
- return members.reduce((acc, it) => {
12110
- return acc.concat(parseCalldataValue(subElement[it.name], it.type, structs));
12111
- }, []);
12112
- }
12113
- if (isTypeTuple(type)) {
12114
- const tupled = parseTuple(element, type);
12115
- return tupled.reduce((acc, it) => {
12116
- const parsedData = parseCalldataValue(it.element, it.type, structs);
12117
- return acc.concat(parsedData);
12118
- }, []);
12119
- }
12120
- if (typeof element === "object") {
12121
- throw Error(`Parameter ${element} do not align with abi parameter ${type}`);
12122
- }
12123
- return felt(element);
12124
- }
12125
- function parseCalldataField(argsIterator, input, structs) {
12126
- const { name, type } = input;
12127
- let { value } = argsIterator.next();
12128
- switch (true) {
12129
- case isTypeArray(type):
12130
- if (!Array.isArray(value) && !isText(value)) {
12131
- throw Error(`ABI expected parameter ${name} to be array or long string, got ${value}`);
12132
- }
12133
- if (typeof value === "string") {
12134
- value = splitLongString(value);
12135
- }
12136
- const result = [];
12137
- result.push(felt(value.length));
12138
- const arrayType = getArrayType(input.type);
12139
- return value.reduce((acc, el) => {
12140
- if (isTypeFelt(arrayType) || isTypeUint(arrayType) || isTypeContractAddress(arrayType)) {
12141
- acc.push(felt(el));
12142
- } else if (isTypeBool(arrayType) && typeof el === "boolean") {
12143
- acc.push(el.toString());
12144
- } else {
12145
- acc.push(...parseCalldataValue(el, arrayType, structs));
12146
- }
12147
- return acc;
12148
- }, result);
12149
- case (isTypeStruct(type, structs) || isTypeTuple(type) || isTypeUint256(type)):
12150
- return parseCalldataValue(value, type, structs);
12151
- case isTypeBool(type):
12152
- return `${+value}`;
12153
- default:
12154
- return felt(value);
12155
- }
12156
- }
12157
-
12158
- // src/utils/calldata/responseParser.ts
12159
- function parseResponseStruct(responseIterator, type, structs) {
12160
- if (type in structs && structs[type]) {
12161
- return structs[type].members.reduce((acc, el) => {
12162
- acc[el.name] = parseResponseStruct(responseIterator, el.type, structs);
12163
- return acc;
12164
- }, {});
12165
- }
12166
- if (isTypeTuple(type)) {
12167
- const memberTypes = extractTupleMemberTypes(type);
12168
- return memberTypes.reduce((acc, it, idx) => {
12169
- const tName = (it == null ? void 0 : it.name) ? it.name : idx;
12170
- const tType = (it == null ? void 0 : it.type) ? it.type : it;
12171
- acc[tName] = parseResponseStruct(responseIterator, tType, structs);
12172
- return acc;
12173
- }, {});
12174
- }
12175
- const temp = responseIterator.next().value;
12176
- return BigInt(temp);
12177
- }
12178
- function responseParser(responseIterator, output2, structs, parsedResult) {
12179
- const { name, type } = output2;
12180
- let temp;
12181
- switch (true) {
12182
- case isLen(name):
12183
- temp = responseIterator.next().value;
12184
- return BigInt(temp);
12185
- case isTypeBool(type):
12186
- temp = responseIterator.next().value;
12187
- return Boolean(BigInt(temp));
12188
- case isTypeUint256(type):
12189
- const low = responseIterator.next().value;
12190
- const high = responseIterator.next().value;
12191
- return uint256ToBN({ low, high });
12192
- case isTypeArray(type):
12193
- const parsedDataArr = [];
12194
- if (isCairo1Type(type)) {
12195
- responseIterator.next();
12196
- let it = responseIterator.next();
12197
- while (!it.done) {
12198
- parsedDataArr.push(BigInt(it.value));
12199
- it = responseIterator.next();
12200
- }
12201
- return parsedDataArr;
12202
- }
12203
- if (parsedResult && parsedResult[`${name}_len`]) {
12204
- const arrLen = parsedResult[`${name}_len`];
12205
- while (parsedDataArr.length < arrLen) {
12206
- parsedDataArr.push(
12207
- parseResponseStruct(responseIterator, output2.type.replace("*", ""), structs)
12208
- );
12209
- }
12210
- }
12211
- return parsedDataArr;
12212
- case (type in structs || isTypeTuple(type)):
12213
- return parseResponseStruct(responseIterator, type, structs);
12214
- default:
12215
- temp = responseIterator.next().value;
12216
- return BigInt(temp);
12217
- }
12218
- }
12219
-
12220
- // src/utils/calldata/validate.ts
12221
- var validateFelt = (parameter, input) => {
12222
- assert2(
12223
- typeof parameter === "string" || typeof parameter === "number" || typeof parameter === "bigint",
12224
- `Validate: arg ${input.name} should be a felt typed as (String, Number or BigInt)`
12225
- );
12226
- };
12227
- var validateUint = (parameter, input) => {
12228
- if (typeof parameter === "number") {
12229
- assert2(
12230
- parameter <= Number.MAX_SAFE_INTEGER,
12231
- `Validation: Parameter is to large to be typed as Number use (BigInt or String)`
12232
- );
12233
- }
12234
- assert2(
12235
- typeof parameter === "string" || typeof parameter === "number" || typeof parameter === "bigint",
12236
- `Validate: arg ${input.name} of cairo type ${input.type} should be type (String, Number or BigInt)`
12237
- );
12238
- const param = toBigInt(parameter);
12239
- switch (input.type) {
12240
- case "core::integer::u8" /* u8 */:
12241
- assert2(
12242
- param >= 0n && param <= 255n,
12243
- `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0 - 255]`
12244
- );
12245
- break;
12246
- case "core::integer::u16" /* u16 */:
12247
- assert2(
12248
- param >= 0n && param <= 65535n,
12249
- `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 65535]`
12250
- );
12251
- break;
12252
- case "core::integer::u32" /* u32 */:
12253
- assert2(
12254
- param >= 0n && param <= 4294967295n,
12255
- `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 4294967295]`
12256
- );
12257
- break;
12258
- case "core::integer::u64" /* u64 */:
12259
- assert2(
12260
- param >= 0n && param <= 2n ** 64n - 1n,
12261
- `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 2^64-1]`
12262
- );
12263
- break;
12264
- case "core::integer::u128" /* u128 */:
12265
- assert2(
12266
- param >= 0n && param <= 2n ** 128n - 1n,
12267
- `Validate: arg ${input.name} cairo typed ${input.type} should be in range [0, 2^128-1]`
12268
- );
12269
- break;
12270
- case "core::integer::u256" /* u256 */:
12271
- assert2(
12272
- param >= 0n && param <= 2n ** 256n - 1n,
12273
- `Validate: arg ${input.name} is ${input.type} 0 - 2^256-1`
12274
- );
12275
- break;
12276
- default:
12277
- break;
12278
- }
12279
- };
12280
- var validateBool = (parameter, input) => {
12281
- assert2(
12282
- typeof parameter === "boolean",
12283
- `Validate: arg ${input.name} of cairo type ${input.type} should be type (Boolean)`
12284
- );
12285
- };
12286
- var validateStruct = (parameter, input, structs) => {
12287
- assert2(
12288
- typeof parameter === "object" && !Array.isArray(parameter),
12289
- `Validate: arg ${input.name} is cairo type struct (${input.type}), and should be defined as js object (not array)`
12290
- );
12291
- structs[input.type].members.forEach(({ name }) => {
12292
- assert2(
12293
- Object.keys(parameter).includes(name),
12294
- `Validate: arg ${input.name} should have a property ${name}`
12295
- );
12296
- });
12297
- };
12298
- var validateTuple = (parameter, input) => {
12299
- assert2(
12300
- typeof parameter === "object" && !Array.isArray(parameter),
12301
- `Validate: arg ${input.name} should be a tuple (defined as object)`
12302
- );
12303
- };
12304
- var validateArray = (parameter, input, structs) => {
12305
- const baseType = getArrayType(input.type);
12306
- if (isTypeFelt(baseType) && isLongText(parameter))
12307
- return;
12308
- assert2(Array.isArray(parameter), `Validate: arg ${input.name} should be an Array`);
12309
- switch (true) {
12310
- case isTypeFelt(baseType):
12311
- parameter.forEach((param) => validateFelt(param, input));
12312
- break;
12313
- case isTypeTuple(baseType):
12314
- parameter.forEach((it) => validateTuple(it, { name: input.name, type: baseType }));
12315
- break;
12316
- case isTypeStruct(baseType, structs):
12317
- parameter.forEach(
12318
- (it) => validateStruct(it, { name: input.name, type: baseType }, structs)
12319
- );
12320
- break;
12321
- case isTypeUint(baseType):
12322
- parameter.forEach((param) => validateUint(param, input));
12323
- break;
12324
- case isTypeBool(baseType):
12325
- parameter.forEach((param) => validateBool(param, input));
12326
- break;
12327
- default:
12328
- throw new Error(
12329
- `Validate Unhandled: argument ${input.name}, type ${input.type}, value ${parameter}`
12330
- );
12331
- }
12332
- };
12333
- function validateFields(abiMethod, args, structs) {
12334
- abiMethod.inputs.reduce((acc, input) => {
12335
- const parameter = args[acc];
12336
- switch (true) {
12337
- case isLen(input.name):
12338
- return acc;
12339
- case isTypeFelt(input.type):
12340
- validateFelt(parameter, input);
12341
- break;
12342
- case isTypeUint(input.type):
12343
- validateUint(parameter, input);
12344
- break;
12345
- case isTypeBool(input.type):
12346
- validateBool(parameter, input);
12347
- break;
12348
- case isTypeContractAddress(input.type):
12349
- break;
12350
- case isTypeStruct(input.type, structs):
12351
- validateStruct(parameter, input, structs);
12352
- break;
12353
- case isTypeTuple(input.type):
12354
- validateTuple(parameter, input);
12355
- break;
12356
- case isTypeArray(input.type):
12357
- validateArray(parameter, input, structs);
12358
- break;
12359
- default:
12360
- throw new Error(
12361
- `Validate Unhandled: argument ${input.name}, type ${input.type}, value ${parameter}`
12362
- );
12363
- }
12364
- return acc + 1;
12365
- }, 0);
12366
- }
12367
-
12368
- // src/utils/calldata/index.ts
12369
- var CallData = class {
12370
- constructor(abi) {
12371
- this.abi = abi;
12372
- this.structs = CallData.getAbiStruct(abi);
12373
- }
12374
- validate(type, method, args = []) {
12375
- if (type !== "DEPLOY") {
12376
- const invocableFunctionNames = this.abi.filter((abi) => {
12377
- if (abi.type !== "function")
12378
- return false;
12379
- const isView = abi.stateMutability === "view" || abi.state_mutability === "view";
12380
- return type === "INVOKE" ? !isView : isView;
12381
- }).map((abi) => abi.name);
12382
- assert2(
12383
- invocableFunctionNames.includes(method),
12384
- `${type === "INVOKE" ? "invocable" : "viewable"} method not found in abi`
12385
- );
12386
- }
12387
- const abiMethod = this.abi.find(
12388
- (abi) => type === "DEPLOY" ? abi.name === method && abi.type === method : abi.name === method && abi.type === "function"
12270
+ };
12271
+ });
12272
+ return this.fetchEndpoint("estimate_fee_bulk", { blockIdentifier }, params).then(
12273
+ this.responseParser.parseFeeEstimateBulkResponse
12389
12274
  );
12390
- const inputsLength = CallData.abiInputsLength(abiMethod.inputs);
12391
- if (args.length !== inputsLength) {
12392
- throw Error(
12393
- `Invalid number of arguments, expected ${inputsLength} arguments, but got ${args.length}`
12394
- );
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
+ }
12395
12301
  }
12396
- validateFields(abiMethod, args, this.structs);
12302
+ const txReceipt = await this.getTransactionReceipt(txHash);
12303
+ return txReceipt;
12397
12304
  }
12398
- compile(args, inputs) {
12399
- const argsIterator = args[Symbol.iterator]();
12400
- return inputs.reduce(
12401
- (acc, input) => isLen(input.name) ? acc : acc.concat(parseCalldataField(argsIterator, input, this.structs)),
12402
- []
12403
- );
12305
+ async getTransactionStatus(txHash) {
12306
+ const txHashHex = toHex(txHash);
12307
+ return this.fetchEndpoint("get_transaction_status", { transactionHash: txHashHex });
12404
12308
  }
12405
- static compile(data) {
12406
- const createTree = (obj) => {
12407
- const getEntries = (o, prefix = "") => {
12408
- const oe = Array.isArray(o) ? [o.length.toString(), ...o] : o;
12409
- return Object.entries(oe).flatMap(([k, v]) => {
12410
- let value = v;
12411
- if (isLongText(value))
12412
- value = splitLongString(value);
12413
- const kk = Array.isArray(oe) && k === "0" ? "$$len" : k;
12414
- if (isBigInt(value))
12415
- return [[`${prefix}${kk}`, felt(value)]];
12416
- return Object(value) === value ? getEntries(value, `${prefix}${kk}.`) : [[`${prefix}${kk}`, felt(value)]];
12417
- });
12418
- };
12419
- return Object.fromEntries(getEntries(obj));
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)
12420
12322
  };
12421
- let callTreeArray;
12422
- if (!Array.isArray(data)) {
12423
- const callTree = createTree(data);
12424
- callTreeArray = Object.values(callTree);
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);
12355
+ }
12356
+ };
12357
+
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);
12425
12369
  } else {
12426
- callTreeArray = data;
12370
+ this.provider = new SequencerProvider();
12427
12371
  }
12428
- Object.defineProperty(callTreeArray, "compiled", {
12429
- enumerable: false,
12430
- writable: false,
12431
- value: true
12432
- });
12433
- return callTreeArray;
12434
12372
  }
12435
- parse(method, response) {
12436
- const { outputs } = this.abi.find((abi) => abi.name === method);
12437
- const responseIterator = response.flat()[Symbol.iterator]();
12438
- const parsed = outputs.flat().reduce((acc, output2, idx) => {
12439
- const propName = output2.name ?? idx;
12440
- acc[propName] = responseParser(responseIterator, output2, this.structs, acc);
12441
- if (acc[propName] && acc[`${propName}_len`]) {
12442
- delete acc[`${propName}_len`];
12443
- }
12444
- return acc;
12445
- }, {});
12446
- return Object.keys(parsed).length === 1 && 0 in parsed ? parsed[0] : parsed;
12373
+ async getChainId() {
12374
+ return this.provider.getChainId();
12447
12375
  }
12448
- format(method, response, format) {
12449
- const parsed = this.parse(method, response);
12450
- return formatter(parsed, format);
12376
+ async getBlock(blockIdentifier) {
12377
+ return this.provider.getBlock(blockIdentifier);
12451
12378
  }
12452
- static abiInputsLength(inputs) {
12453
- return inputs.reduce((acc, input) => !isLen(input.name) ? acc + 1 : acc, 0);
12379
+ async getClassAt(contractAddress, blockIdentifier) {
12380
+ return this.provider.getClassAt(contractAddress, blockIdentifier);
12454
12381
  }
12455
- static getAbiStruct(abi) {
12456
- return abi.filter((abiEntry) => abiEntry.type === "struct").reduce(
12457
- (acc, abiEntry) => ({
12458
- ...acc,
12459
- [abiEntry.name]: abiEntry
12460
- }),
12461
- {}
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
12397
+ );
12398
+ }
12399
+ async getEstimateFeeBulk(invocations, blockIdentifier) {
12400
+ return this.provider.getEstimateFeeBulk(invocations, blockIdentifier);
12401
+ }
12402
+ async getNonceForAddress(contractAddress, blockIdentifier) {
12403
+ return this.provider.getNonceForAddress(contractAddress, blockIdentifier);
12404
+ }
12405
+ async getStorageAt(contractAddress, key, blockIdentifier) {
12406
+ return this.provider.getStorageAt(contractAddress, key, blockIdentifier);
12407
+ }
12408
+ async getTransaction(txHash) {
12409
+ return this.provider.getTransaction(txHash);
12410
+ }
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
12462
12449
  );
12463
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 {
12464
12464
  };
12465
12465
 
12466
+ // src/provider/index.ts
12467
+ var defaultProvider = new Provider();
12468
+
12466
12469
  // src/contract/default.ts
12467
12470
  var splitArgsAndOptions = (args) => {
12468
12471
  const options = [
@@ -12472,13 +12475,14 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12472
12475
  "formatResponse",
12473
12476
  "maxFee",
12474
12477
  "nonce",
12475
- "signature"
12478
+ "signature",
12479
+ "addressSalt"
12476
12480
  ];
12477
12481
  const lastArg = args[args.length - 1];
12478
12482
  if (typeof lastArg === "object" && options.some((x) => x in lastArg)) {
12479
12483
  return { args, options: args.pop() };
12480
12484
  }
12481
- return { args, options: {} };
12485
+ return { args };
12482
12486
  };
12483
12487
  function buildCall(contract, functionAbi) {
12484
12488
  return async function(...args) {
@@ -12515,20 +12519,20 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12515
12519
  return contract.estimate(functionAbi.name, args);
12516
12520
  };
12517
12521
  }
12518
- var detectCairoVersion = (abi) => {
12519
- if (!abi)
12520
- return "0";
12521
- return abi.find((it) => "state_mutability" in it) ? "1" : "0";
12522
- };
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
+ }
12523
12529
  var Contract = class {
12524
- constructor(abi, address, providerOrAccount = defaultProvider, cairoVersion = detectCairoVersion(abi)) {
12525
- this.version = "0";
12530
+ constructor(abi, address, providerOrAccount = defaultProvider) {
12526
12531
  this.address = address && address.toLowerCase();
12527
12532
  this.providerOrAccount = providerOrAccount;
12528
12533
  this.callData = new CallData(abi);
12529
12534
  this.structs = CallData.getAbiStruct(abi);
12530
12535
  this.abi = abi;
12531
- this.version = cairoVersion;
12532
12536
  const options = { enumerable: true, value: {}, writable: false };
12533
12537
  Object.defineProperties(this, {
12534
12538
  functions: { enumerable: true, value: {}, writable: false },
@@ -12585,15 +12589,21 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12585
12589
  }
12586
12590
  return this;
12587
12591
  }
12588
- 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
+ } = {}) {
12589
12598
  assert2(this.address !== null, "contract is not connected to an address");
12590
- const blockIdentifier = (options == null ? void 0 : options.blockIdentifier) || void 0;
12591
- let calldata = "compiled" in args ? args : args[0];
12592
- if (options.parseRequest && !(calldata == null ? void 0 : calldata.compiled)) {
12593
- const { inputs } = this.abi.find((abi) => abi.name === method);
12594
- this.callData.validate("CALL", method, args);
12595
- calldata = this.callData.compile(args, inputs);
12596
- }
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
+ });
12597
12607
  return this.providerOrAccount.callContract(
12598
12608
  {
12599
12609
  contractAddress: this.address,
@@ -12602,25 +12612,25 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12602
12612
  },
12603
12613
  blockIdentifier
12604
12614
  ).then((x) => {
12605
- if (!options.parseResponse) {
12615
+ if (!parseResponse) {
12606
12616
  return x.result;
12607
12617
  }
12608
- if (options.formatResponse) {
12609
- return this.callData.format(method, x.result, options.formatResponse);
12618
+ if (formatResponse) {
12619
+ return this.callData.format(method, x.result, formatResponse);
12610
12620
  }
12611
12621
  return this.callData.parse(method, x.result);
12612
12622
  });
12613
12623
  }
12614
- invoke(method, args = [], options = {
12615
- parseRequest: true
12616
- }) {
12624
+ invoke(method, args = [], { parseRequest = true, maxFee, nonce, signature } = {}) {
12617
12625
  assert2(this.address !== null, "contract is not connected to an address");
12618
- let calldata = "compiled" in args ? args : args[0];
12619
- if (options.parseRequest && !(calldata == null ? void 0 : calldata.compiled)) {
12620
- const { inputs } = this.abi.find((abi) => abi.name === method);
12621
- this.callData.validate("INVOKE", method, args);
12622
- calldata = this.callData.compile(args, inputs);
12623
- }
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
+ });
12624
12634
  const invocation = {
12625
12635
  contractAddress: this.address,
12626
12636
  calldata,
@@ -12628,40 +12638,36 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12628
12638
  };
12629
12639
  if ("execute" in this.providerOrAccount) {
12630
12640
  return this.providerOrAccount.execute(invocation, void 0, {
12631
- maxFee: options.maxFee,
12632
- nonce: options.nonce
12641
+ maxFee,
12642
+ nonce
12633
12643
  });
12634
12644
  }
12635
- if (!options.nonce) {
12645
+ if (!nonce)
12636
12646
  throw new Error(`Nonce is required when invoking a function without an account`);
12637
- }
12638
12647
  console.warn(`Invoking ${method} without an account. This will not work on a public node.`);
12639
12648
  return this.providerOrAccount.invokeFunction(
12640
12649
  {
12641
12650
  ...invocation,
12642
- signature: options.signature
12651
+ signature
12643
12652
  },
12644
12653
  {
12645
- nonce: options.nonce
12654
+ nonce
12646
12655
  }
12647
12656
  );
12648
12657
  }
12649
12658
  async estimate(method, args = []) {
12650
- var _a;
12651
12659
  assert2(this.address !== null, "contract is not connected to an address");
12652
- if (!((_a = args[0]) == null ? void 0 : _a.compiled)) {
12660
+ if (!getCalldata(args, () => false)) {
12653
12661
  this.callData.validate("INVOKE", method, args);
12654
12662
  }
12655
- const invocation = this.populateTransaction[method](...args);
12663
+ const invocation = this.populate(method, args);
12656
12664
  if ("estimateInvokeFee" in this.providerOrAccount) {
12657
12665
  return this.providerOrAccount.estimateInvokeFee(invocation);
12658
12666
  }
12659
12667
  throw Error("Contract must be connected to the account contract to estimate");
12660
12668
  }
12661
12669
  populate(method, args = []) {
12662
- var _a;
12663
- const { inputs } = this.abi.find((abi) => abi.name === method);
12664
- 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));
12665
12671
  return {
12666
12672
  contractAddress: this.address,
12667
12673
  entrypoint: method,
@@ -12681,36 +12687,24 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
12681
12687
  this.compiledContract = compiledContract;
12682
12688
  this.account = account;
12683
12689
  this.classHash = classHash;
12684
- this.callData = new CallData(abi);
12690
+ this.CallData = new CallData(abi);
12685
12691
  }
12686
12692
  async deploy(...args) {
12687
- var _a;
12688
- let constructorCalldata;
12689
- let parseRequest = true;
12690
- let addressSalt;
12691
- args.forEach((arg) => {
12692
- if (typeof arg !== "object")
12693
- return;
12694
- if ("addressSalt" in arg) {
12695
- addressSalt = arg.addressSalt;
12696
- }
12697
- if ("parseRequest" in arg) {
12698
- parseRequest = arg.parseRequest;
12699
- }
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;
12700
12701
  });
12701
- if (!parseRequest || ((_a = args[0]) == null ? void 0 : _a.compiled)) {
12702
- constructorCalldata = args[0];
12703
- } else {
12704
- this.callData.validate("DEPLOY", "constructor", args);
12705
- const { inputs } = this.abi.find((abi) => abi.type === "constructor");
12706
- constructorCalldata = this.callData.compile(args, inputs);
12707
- }
12708
12702
  const {
12709
12703
  deploy: { contract_address, transaction_hash }
12710
12704
  } = await this.account.declareAndDeploy({
12711
12705
  contract: this.compiledContract,
12712
12706
  constructorCalldata,
12713
- salt: addressSalt
12707
+ salt: options.addressSalt
12714
12708
  });
12715
12709
  assert2(Boolean(contract_address), "Deployment of the contract failed");
12716
12710
  const contractInstance = new Contract(
@@ -13338,7 +13332,7 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
13338
13332
  unique = true,
13339
13333
  constructorCalldata = []
13340
13334
  } = it;
13341
- const compiledConstructorCallData = compileCalldata(constructorCalldata);
13335
+ const compiledConstructorCallData = CallData.compile(constructorCalldata);
13342
13336
  const deploySalt = salt ?? randomAddress();
13343
13337
  return {
13344
13338
  call: {
@@ -13362,7 +13356,10 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
13362
13356
  });
13363
13357
  const calls = params.map((it) => it.call);
13364
13358
  const addresses = params.map((it) => it.address);
13365
- const invokeResponse = await this.execute(calls, void 0, details);
13359
+ const invokeResponse = await this.execute(calls, void 0, {
13360
+ ...details,
13361
+ cairoVersion: "0"
13362
+ });
13366
13363
  return {
13367
13364
  ...invokeResponse,
13368
13365
  contract_address: addresses
@@ -13434,7 +13431,7 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
13434
13431
  await this.callContract({
13435
13432
  contractAddress: this.address,
13436
13433
  entrypoint: "isValidSignature",
13437
- calldata: compileCalldata({
13434
+ calldata: CallData.compile({
13438
13435
  hash: toBigInt(hash2).toString(),
13439
13436
  signature: formatSignature(signature)
13440
13437
  })
@@ -13520,7 +13517,7 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
13520
13517
  unique = true,
13521
13518
  constructorCalldata = []
13522
13519
  } = it;
13523
- const compiledConstructorCallData = compileCalldata(constructorCalldata);
13520
+ const compiledConstructorCallData = CallData.compile(constructorCalldata);
13524
13521
  return {
13525
13522
  contractAddress: UDC.ADDRESS,
13526
13523
  entrypoint: UDC.ENTRYPOINT,
@@ -13564,8 +13561,8 @@ ${res.tx_failure_reason.error_message}` : res.tx_status;
13564
13561
  }
13565
13562
  };
13566
13563
  }
13567
- async getStarkName(address = this.address, StarknetIdContract) {
13568
- return super.getStarkName(address, StarknetIdContract);
13564
+ async getStarkName(address = this.address, StarknetIdContract2) {
13565
+ return super.getStarkName(address, StarknetIdContract2);
13569
13566
  }
13570
13567
  };
13571
13568