@obelyzk/sdk 0.5.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -686,6 +686,124 @@ var DarkPoolClient = class {
686
686
  await this.obelysk.provider.waitForTransaction(result.transaction_hash);
687
687
  return { txHash: result.transaction_hash };
688
688
  }
689
+ /** Cancel an order before reveal. */
690
+ async cancelOrder(orderId) {
691
+ const account = this.obelysk.requireAccount();
692
+ const low = (orderId & (1n << 128n) - 1n).toString();
693
+ const high = (orderId >> 128n).toString();
694
+ const result = await account.execute([{
695
+ contractAddress: this.darkPoolAddress,
696
+ entrypoint: "cancel_order",
697
+ calldata: [low, high]
698
+ }]);
699
+ return result.transaction_hash;
700
+ }
701
+ /** Claim fills after epoch settlement. */
702
+ async claimFill(params) {
703
+ const account = this.obelysk.requireAccount();
704
+ const oLow = (params.orderId & (1n << 128n) - 1n).toString();
705
+ const oHigh = (params.orderId >> 128n).toString();
706
+ const result = await account.execute([{
707
+ contractAddress: this.darkPoolAddress,
708
+ entrypoint: "claim_fill",
709
+ calldata: [
710
+ oLow,
711
+ oHigh,
712
+ params.receiveCipher.c1.x.toString(),
713
+ params.receiveCipher.c1.y.toString(),
714
+ params.receiveCipher.c2.x.toString(),
715
+ params.receiveCipher.c2.y.toString(),
716
+ params.receiveHint.toString(),
717
+ params.receiveProof.commitment.toString(),
718
+ params.receiveProof.challenge.toString(),
719
+ params.receiveProof.response.toString(),
720
+ params.spendCipher.c1.x.toString(),
721
+ params.spendCipher.c1.y.toString(),
722
+ params.spendCipher.c2.x.toString(),
723
+ params.spendCipher.c2.y.toString(),
724
+ params.spendHint.toString(),
725
+ params.spendProof.commitment.toString(),
726
+ params.spendProof.challenge.toString(),
727
+ params.spendProof.response.toString()
728
+ ]
729
+ }]);
730
+ return result.transaction_hash;
731
+ }
732
+ /** Register your ElGamal public key with the DarkPool. */
733
+ async registerPubkey(pubkey) {
734
+ const account = this.obelysk.requireAccount();
735
+ const result = await account.execute([{
736
+ contractAddress: this.darkPoolAddress,
737
+ entrypoint: "register_pubkey",
738
+ calldata: [pubkey.x.toString(), pubkey.y.toString()]
739
+ }]);
740
+ return result.transaction_hash;
741
+ }
742
+ /** Get the result of a settled epoch. */
743
+ async getEpochResult(epochId) {
744
+ try {
745
+ const result = await this.obelysk.provider.callContract({
746
+ contractAddress: this.darkPoolAddress,
747
+ entrypoint: "get_epoch_result",
748
+ calldata: [epochId.toString()]
749
+ });
750
+ if (result.length < 2) return null;
751
+ const settled = BigInt(result[0]) !== 0n;
752
+ const priceCount = Number(BigInt(result[1]));
753
+ const clearingPrices = result.slice(2, 2 + priceCount);
754
+ return { settled, clearingPrices };
755
+ } catch {
756
+ return null;
757
+ }
758
+ }
759
+ /** Check if an order has been claimed. */
760
+ async isOrderClaimed(orderId) {
761
+ try {
762
+ const low = (orderId & (1n << 128n) - 1n).toString();
763
+ const high = (orderId >> 128n).toString();
764
+ const result = await this.obelysk.provider.callContract({
765
+ contractAddress: this.darkPoolAddress,
766
+ entrypoint: "is_order_claimed",
767
+ calldata: [low, high]
768
+ });
769
+ return BigInt(result[0]) !== 0n;
770
+ } catch {
771
+ return false;
772
+ }
773
+ }
774
+ /** Get a trader's registered public key. */
775
+ async getTraderPubkey(address) {
776
+ try {
777
+ const result = await this.obelysk.provider.callContract({
778
+ contractAddress: this.darkPoolAddress,
779
+ entrypoint: "get_trader_pubkey",
780
+ calldata: [address]
781
+ });
782
+ const x = BigInt(result[0]);
783
+ const y = BigInt(result[1]);
784
+ if (x === 0n && y === 0n) return null;
785
+ return { x, y };
786
+ } catch {
787
+ return null;
788
+ }
789
+ }
790
+ /** Get encrypted balance for a trader and asset. */
791
+ async getEncryptedBalance(address, assetId) {
792
+ try {
793
+ const result = await this.obelysk.provider.callContract({
794
+ contractAddress: this.darkPoolAddress,
795
+ entrypoint: "get_encrypted_balance",
796
+ calldata: [address, assetId]
797
+ });
798
+ if (result.length < 4) return null;
799
+ return {
800
+ c1: { x: BigInt(result[0]), y: BigInt(result[1]) },
801
+ c2: { x: BigInt(result[2]), y: BigInt(result[3]) }
802
+ };
803
+ } catch {
804
+ return null;
805
+ }
806
+ }
689
807
  };
690
808
 
691
809
  // src/obelysk/stealth.ts
@@ -845,6 +963,102 @@ var StealthClient = class {
845
963
  await this.obelysk.provider.waitForTransaction(result.transaction_hash);
846
964
  return { txHash: result.transaction_hash };
847
965
  }
966
+ /** Claim a stealth payment. */
967
+ async claim(params) {
968
+ const account = this.obelysk.requireAccount();
969
+ const p = params.spendingProof;
970
+ const result = await account.execute([{
971
+ contractAddress: this.registryAddress,
972
+ entrypoint: "claim_stealth_payment",
973
+ calldata: [
974
+ params.announcementIndex.toString(),
975
+ p.commitment.toString(),
976
+ p.challenge.toString(),
977
+ p.response.toString(),
978
+ p.stealthPubkey.x.toString(),
979
+ p.stealthPubkey.y.toString(),
980
+ params.recipient
981
+ ]
982
+ }]);
983
+ return result.transaction_hash;
984
+ }
985
+ /** Batch claim multiple stealth payments. */
986
+ async batchClaim(params) {
987
+ const account = this.obelysk.requireAccount();
988
+ const calldata = [
989
+ params.announcementIndices.length.toString(),
990
+ ...params.announcementIndices.map((i) => i.toString()),
991
+ params.spendingProofs.length.toString(),
992
+ ...params.spendingProofs.flatMap((p) => [
993
+ p.commitment.toString(),
994
+ p.challenge.toString(),
995
+ p.response.toString(),
996
+ p.stealthPubkey.x.toString(),
997
+ p.stealthPubkey.y.toString()
998
+ ]),
999
+ params.recipient
1000
+ ];
1001
+ const result = await account.execute([{
1002
+ contractAddress: this.registryAddress,
1003
+ entrypoint: "batch_claim_stealth_payments",
1004
+ calldata
1005
+ }]);
1006
+ return result.transaction_hash;
1007
+ }
1008
+ /** Update your stealth meta-address. */
1009
+ async updateMetaAddress(spendPubKey, viewPubKey) {
1010
+ const account = this.obelysk.requireAccount();
1011
+ const result = await account.execute([{
1012
+ contractAddress: this.registryAddress,
1013
+ entrypoint: "update_meta_address",
1014
+ calldata: [spendPubKey.x.toString(), spendPubKey.y.toString(), viewPubKey.x.toString(), viewPubKey.y.toString()]
1015
+ }]);
1016
+ return result.transaction_hash;
1017
+ }
1018
+ /** Get a specific announcement by index. */
1019
+ async getAnnouncement(index) {
1020
+ try {
1021
+ const result = await this.obelysk.provider.callContract({
1022
+ contractAddress: this.registryAddress,
1023
+ entrypoint: "get_announcement",
1024
+ calldata: [index.toString()]
1025
+ });
1026
+ return {
1027
+ ephemeralPubkey: { x: BigInt(result[0]), y: BigInt(result[1]) },
1028
+ stealthAddress: result[2],
1029
+ viewTag: result[3],
1030
+ token: result[4],
1031
+ amount: BigInt(result[5])
1032
+ };
1033
+ } catch {
1034
+ return null;
1035
+ }
1036
+ }
1037
+ /** Get announcements in a range. */
1038
+ async getAnnouncementsRange(start, end) {
1039
+ try {
1040
+ const result = await this.obelysk.provider.callContract({
1041
+ contractAddress: this.registryAddress,
1042
+ entrypoint: "get_announcements_range",
1043
+ calldata: [start.toString(), end.toString()]
1044
+ });
1045
+ const count = Number(BigInt(result[0]));
1046
+ const items = [];
1047
+ for (let i = 0; i < count; i++) {
1048
+ const base = 1 + i * 6;
1049
+ items.push({
1050
+ ephemeralPubkey: { x: BigInt(result[base]), y: BigInt(result[base + 1]) },
1051
+ stealthAddress: result[base + 2],
1052
+ viewTag: result[base + 3],
1053
+ token: result[base + 4],
1054
+ amount: BigInt(result[base + 5])
1055
+ });
1056
+ }
1057
+ return items;
1058
+ } catch {
1059
+ return [];
1060
+ }
1061
+ }
848
1062
  };
849
1063
 
850
1064
  // src/obelysk/confidentialTransfer.ts
@@ -937,6 +1151,78 @@ var ConfidentialTransferClient = class {
937
1151
  return null;
938
1152
  }
939
1153
  }
1154
+ /** Register an ElGamal public key for confidential transfers. */
1155
+ async register(publicKey) {
1156
+ const account = this.obelysk.requireAccount();
1157
+ const result = await account.execute([{
1158
+ contractAddress: this.contractAddress,
1159
+ entrypoint: "register",
1160
+ calldata: [publicKey.x.toString(), publicKey.y.toString()]
1161
+ }]);
1162
+ return result.transaction_hash;
1163
+ }
1164
+ /** Fund: deposit public tokens into encrypted balance. */
1165
+ async fund(params) {
1166
+ const account = this.obelysk.requireAccount();
1167
+ const low = (params.amount & (1n << 128n) - 1n).toString();
1168
+ const high = (params.amount >> 128n).toString();
1169
+ const result = await account.execute([{
1170
+ contractAddress: this.contractAddress,
1171
+ entrypoint: "fund",
1172
+ calldata: [params.assetId.toString(), low, high, params.encryptionRandomness.toString(), params.aeHint.toString()]
1173
+ }]);
1174
+ return result.transaction_hash;
1175
+ }
1176
+ /** Fund another account's encrypted balance. */
1177
+ async fundFor(params) {
1178
+ const signer = this.obelysk.requireAccount();
1179
+ const low = (params.amount & (1n << 128n) - 1n).toString();
1180
+ const high = (params.amount >> 128n).toString();
1181
+ const result = await signer.execute([{
1182
+ contractAddress: this.contractAddress,
1183
+ entrypoint: "fund_for",
1184
+ calldata: [params.account, params.assetId.toString(), low, high, params.encryptionRandomness.toString(), params.aeHint.toString()]
1185
+ }]);
1186
+ return result.transaction_hash;
1187
+ }
1188
+ /** Rollover: claim pending incoming transfers into your balance. */
1189
+ async rollover(assetId) {
1190
+ const account = this.obelysk.requireAccount();
1191
+ const result = await account.execute([{
1192
+ contractAddress: this.contractAddress,
1193
+ entrypoint: "rollover",
1194
+ calldata: [assetId.toString()]
1195
+ }]);
1196
+ return result.transaction_hash;
1197
+ }
1198
+ /** Withdraw: convert encrypted balance back to public tokens. */
1199
+ async withdraw(params) {
1200
+ const account = this.obelysk.requireAccount();
1201
+ const low = (params.amount & (1n << 128n) - 1n).toString();
1202
+ const high = (params.amount >> 128n).toString();
1203
+ const result = await account.execute([{
1204
+ contractAddress: this.contractAddress,
1205
+ entrypoint: "withdraw",
1206
+ calldata: [params.to, params.assetId.toString(), low, high, params.proof.commitment.toString(), params.proof.challenge.toString(), params.proof.response.toString()]
1207
+ }]);
1208
+ return result.transaction_hash;
1209
+ }
1210
+ /** Get a registered public key. */
1211
+ async getPublicKey(address) {
1212
+ try {
1213
+ const result = await this.obelysk.provider.callContract({
1214
+ contractAddress: this.contractAddress,
1215
+ entrypoint: "get_public_key",
1216
+ calldata: [address]
1217
+ });
1218
+ const x = BigInt(result[0]);
1219
+ const y = BigInt(result[1]);
1220
+ if (x === 0n && y === 0n) return null;
1221
+ return { x, y };
1222
+ } catch {
1223
+ return null;
1224
+ }
1225
+ }
940
1226
  };
941
1227
 
942
1228
  // src/obelysk/proverStaking.ts
@@ -1281,6 +1567,133 @@ var PrivacyRouterClient = class {
1281
1567
  });
1282
1568
  return Number(BigInt(result[0]));
1283
1569
  }
1570
+ /** Register an account with the privacy router. */
1571
+ async registerAccount(publicKey) {
1572
+ const account = this.obelysk.requireAccount();
1573
+ const result = await account.execute([{
1574
+ contractAddress: this.contractAddress,
1575
+ entrypoint: "register_account",
1576
+ calldata: [publicKey.x.toString(), publicKey.y.toString()]
1577
+ }]);
1578
+ return result.transaction_hash;
1579
+ }
1580
+ /** Deposit tokens into encrypted balance. */
1581
+ async deposit(params) {
1582
+ const account = this.obelysk.requireAccount();
1583
+ const low = (params.amount & (1n << 128n) - 1n).toString();
1584
+ const high = (params.amount >> 128n).toString();
1585
+ const result = await account.execute([{
1586
+ contractAddress: this.contractAddress,
1587
+ entrypoint: "deposit",
1588
+ calldata: [
1589
+ low,
1590
+ high,
1591
+ params.encryptedAmount.c1.x.toString(),
1592
+ params.encryptedAmount.c1.y.toString(),
1593
+ params.encryptedAmount.c2.x.toString(),
1594
+ params.encryptedAmount.c2.y.toString(),
1595
+ params.proof.commitment.toString(),
1596
+ params.proof.challenge.toString(),
1597
+ params.proof.response.toString()
1598
+ ]
1599
+ }]);
1600
+ return result.transaction_hash;
1601
+ }
1602
+ /** Withdraw from encrypted balance to public. */
1603
+ async withdraw(params) {
1604
+ const account = this.obelysk.requireAccount();
1605
+ const low = (params.amount & (1n << 128n) - 1n).toString();
1606
+ const high = (params.amount >> 128n).toString();
1607
+ const calldata = [
1608
+ low,
1609
+ high,
1610
+ params.encryptedDelta.c1.x.toString(),
1611
+ params.encryptedDelta.c1.y.toString(),
1612
+ params.encryptedDelta.c2.x.toString(),
1613
+ params.encryptedDelta.c2.y.toString(),
1614
+ params.proof.commitment.toString(),
1615
+ params.proof.challenge.toString(),
1616
+ params.proof.response.toString()
1617
+ ];
1618
+ if (params.rangeProofData) calldata.push(...params.rangeProofData);
1619
+ const result = await account.execute([{
1620
+ contractAddress: this.contractAddress,
1621
+ entrypoint: "withdraw",
1622
+ calldata
1623
+ }]);
1624
+ return result.transaction_hash;
1625
+ }
1626
+ /** Private transfer between accounts. */
1627
+ async privateTransfer(params) {
1628
+ const account = this.obelysk.requireAccount();
1629
+ const result = await account.execute([{
1630
+ contractAddress: this.contractAddress,
1631
+ entrypoint: "private_transfer",
1632
+ calldata: [
1633
+ params.to,
1634
+ params.senderCipher.c1.x.toString(),
1635
+ params.senderCipher.c1.y.toString(),
1636
+ params.senderCipher.c2.x.toString(),
1637
+ params.senderCipher.c2.y.toString(),
1638
+ params.receiverCipher.c1.x.toString(),
1639
+ params.receiverCipher.c1.y.toString(),
1640
+ params.receiverCipher.c2.x.toString(),
1641
+ params.receiverCipher.c2.y.toString(),
1642
+ params.proof.commitment.toString(),
1643
+ params.proof.challenge.toString(),
1644
+ params.proof.response.toString(),
1645
+ params.senderAeHint.toString(),
1646
+ params.receiverAeHint.toString()
1647
+ ]
1648
+ }]);
1649
+ return result.transaction_hash;
1650
+ }
1651
+ /** Request disclosure of a nullifier (audit). */
1652
+ async requestDisclosure(nullifier, reason) {
1653
+ const account = this.obelysk.requireAccount();
1654
+ const result = await account.execute([{
1655
+ contractAddress: this.contractAddress,
1656
+ entrypoint: "request_disclosure",
1657
+ calldata: [nullifier, reason]
1658
+ }]);
1659
+ return result.transaction_hash;
1660
+ }
1661
+ /** Ragequit: emergency withdrawal with proof. */
1662
+ async ragequit(proof) {
1663
+ const account = this.obelysk.requireAccount();
1664
+ const result = await account.execute([{
1665
+ contractAddress: this.contractAddress,
1666
+ entrypoint: "ragequit",
1667
+ calldata: proof
1668
+ }]);
1669
+ return result.transaction_hash;
1670
+ }
1671
+ /** Get the nullifier tree state. */
1672
+ async getNullifierTreeState() {
1673
+ const result = await this.obelysk.provider.callContract({
1674
+ contractAddress: this.contractAddress,
1675
+ entrypoint: "get_nullifier_tree_state",
1676
+ calldata: []
1677
+ });
1678
+ return { root: result[0], size: Number(BigInt(result[1])) };
1679
+ }
1680
+ /** Get account balance hints (for O(1) decryption). */
1681
+ async getAccountHints(address) {
1682
+ try {
1683
+ const result = await this.obelysk.provider.callContract({
1684
+ contractAddress: this.contractAddress,
1685
+ entrypoint: "get_account_hints",
1686
+ calldata: [address]
1687
+ });
1688
+ return {
1689
+ balanceHint: BigInt(result[0]),
1690
+ pendingInHint: BigInt(result[1]),
1691
+ pendingOutHint: BigInt(result[2])
1692
+ };
1693
+ } catch {
1694
+ return null;
1695
+ }
1696
+ }
1284
1697
  };
1285
1698
 
1286
1699
  // src/obelysk/shieldedSwap.ts
@@ -1349,6 +1762,911 @@ var ShieldedSwapClient = class {
1349
1762
  });
1350
1763
  return result[0];
1351
1764
  }
1765
+ /**
1766
+ * Execute a shielded swap (privacy pool -> AMM -> re-deposit).
1767
+ * This is the full privacy-preserving swap flow.
1768
+ */
1769
+ async shieldedSwap(params) {
1770
+ const account = this.obelysk.requireAccount();
1771
+ const result = await account.execute([{
1772
+ contractAddress: this.contractAddress,
1773
+ entrypoint: "shielded_swap",
1774
+ calldata: [
1775
+ params.tokenIn,
1776
+ params.tokenOut,
1777
+ params.amountIn.toString(),
1778
+ params.minAmountOut.toString(),
1779
+ params.nullifier,
1780
+ params.merkleRoot,
1781
+ ...params.merkleProof,
1782
+ params.newCommitment,
1783
+ params.encryptedAmount.toString(),
1784
+ params.proof
1785
+ ]
1786
+ }]);
1787
+ return result.transaction_hash;
1788
+ }
1789
+ };
1790
+
1791
+ // src/obelysk/vm31Vault.ts
1792
+ var VM31VaultClient = class {
1793
+ constructor(obelysk) {
1794
+ this.obelysk = obelysk;
1795
+ }
1796
+ get contractAddress() {
1797
+ return this.obelysk.contracts.vm31_pool;
1798
+ }
1799
+ get relayerUrl() {
1800
+ return this.obelysk.relayerUrl ?? "https://relay.bitsage.network:3080";
1801
+ }
1802
+ get relayerApiKey() {
1803
+ return this.obelysk.relayerApiKey;
1804
+ }
1805
+ async relayerFetch(path, init) {
1806
+ const url = `${this.relayerUrl}${path}`;
1807
+ const headers = { "Content-Type": "application/json" };
1808
+ if (this.relayerApiKey) headers["x-api-key"] = this.relayerApiKey;
1809
+ const res = await fetch(url, { ...init, headers: { ...headers, ...init?.headers } });
1810
+ if (!res.ok) {
1811
+ const body = await res.text().catch(() => "");
1812
+ throw new Error(`VM31 relayer ${res.status}: ${body}`);
1813
+ }
1814
+ return res.json();
1815
+ }
1816
+ // --------------------------------------------------------------------------
1817
+ // On-chain reads (callContract to vm31_pool)
1818
+ // --------------------------------------------------------------------------
1819
+ /** Get the current Merkle root of the VM31 commitment tree */
1820
+ async getMerkleRoot() {
1821
+ const result = await this.obelysk.provider.callContract({
1822
+ contractAddress: this.contractAddress,
1823
+ entrypoint: "get_merkle_root",
1824
+ calldata: []
1825
+ });
1826
+ return { lo: result[0], hi: result[1] };
1827
+ }
1828
+ /** Get the number of leaves in the commitment tree */
1829
+ async getTreeSize() {
1830
+ const result = await this.obelysk.provider.callContract({
1831
+ contractAddress: this.contractAddress,
1832
+ entrypoint: "get_tree_size",
1833
+ calldata: []
1834
+ });
1835
+ return Number(BigInt(result[0]));
1836
+ }
1837
+ /** Check if a nullifier has been spent */
1838
+ async isNullifierSpent(nullifier) {
1839
+ const result = await this.obelysk.provider.callContract({
1840
+ contractAddress: this.contractAddress,
1841
+ entrypoint: "is_nullifier_spent",
1842
+ calldata: [nullifier.lo, nullifier.hi]
1843
+ });
1844
+ return BigInt(result[0]) !== 0n;
1845
+ }
1846
+ /** Check if a Merkle root is known (valid historical root) */
1847
+ async isKnownRoot(root) {
1848
+ const result = await this.obelysk.provider.callContract({
1849
+ contractAddress: this.contractAddress,
1850
+ entrypoint: "is_known_root",
1851
+ calldata: [root.lo, root.hi]
1852
+ });
1853
+ return BigInt(result[0]) !== 0n;
1854
+ }
1855
+ /** Get the total balance of an asset held in the pool */
1856
+ async getAssetBalance(assetId) {
1857
+ const result = await this.obelysk.provider.callContract({
1858
+ contractAddress: this.contractAddress,
1859
+ entrypoint: "get_asset_balance",
1860
+ calldata: [assetId.toString()]
1861
+ });
1862
+ return BigInt(result[0]);
1863
+ }
1864
+ /** Get on-chain batch status (0=NONE, 1=SUBMITTED, 2=FINALIZED, 3=CANCELLED) */
1865
+ async getBatchStatus(batchId) {
1866
+ const result = await this.obelysk.provider.callContract({
1867
+ contractAddress: this.contractAddress,
1868
+ entrypoint: "get_batch_status",
1869
+ calldata: [batchId]
1870
+ });
1871
+ return Number(BigInt(result[0]));
1872
+ }
1873
+ /** Get the currently active batch ID */
1874
+ async getActiveBatchId() {
1875
+ const result = await this.obelysk.provider.callContract({
1876
+ contractAddress: this.contractAddress,
1877
+ entrypoint: "get_active_batch_id",
1878
+ calldata: []
1879
+ });
1880
+ return result[0];
1881
+ }
1882
+ /** Get total transaction count in a batch */
1883
+ async getBatchTotalTxs(batchId) {
1884
+ const result = await this.obelysk.provider.callContract({
1885
+ contractAddress: this.contractAddress,
1886
+ entrypoint: "get_batch_total_txs",
1887
+ calldata: [batchId]
1888
+ });
1889
+ return Number(BigInt(result[0]));
1890
+ }
1891
+ /** Get number of processed transactions in a batch */
1892
+ async getBatchProcessedCount(batchId) {
1893
+ const result = await this.obelysk.provider.callContract({
1894
+ contractAddress: this.contractAddress,
1895
+ entrypoint: "get_batch_processed_count",
1896
+ calldata: [batchId]
1897
+ });
1898
+ return Number(BigInt(result[0]));
1899
+ }
1900
+ /** Get the ERC-20 token address for a VM31 asset ID */
1901
+ async getAssetToken(assetId) {
1902
+ const result = await this.obelysk.provider.callContract({
1903
+ contractAddress: this.contractAddress,
1904
+ entrypoint: "get_asset_token",
1905
+ calldata: [assetId.toString()]
1906
+ });
1907
+ return result[0];
1908
+ }
1909
+ /** Get the VM31 asset ID for a given ERC-20 token address */
1910
+ async getTokenAsset(tokenAddress) {
1911
+ const result = await this.obelysk.provider.callContract({
1912
+ contractAddress: this.contractAddress,
1913
+ entrypoint: "get_token_asset",
1914
+ calldata: [tokenAddress]
1915
+ });
1916
+ return Number(BigInt(result[0]));
1917
+ }
1918
+ /** Check if the VM31Pool contract is paused */
1919
+ async isPaused() {
1920
+ const result = await this.obelysk.provider.callContract({
1921
+ contractAddress: this.contractAddress,
1922
+ entrypoint: "is_paused",
1923
+ calldata: []
1924
+ });
1925
+ return BigInt(result[0]) !== 0n;
1926
+ }
1927
+ /** Get the contract owner address */
1928
+ async getOwner() {
1929
+ const result = await this.obelysk.provider.callContract({
1930
+ contractAddress: this.contractAddress,
1931
+ entrypoint: "get_owner",
1932
+ calldata: []
1933
+ });
1934
+ return result[0];
1935
+ }
1936
+ /** Get the authorized relayer address */
1937
+ async getRelayer() {
1938
+ const result = await this.obelysk.provider.callContract({
1939
+ contractAddress: this.contractAddress,
1940
+ entrypoint: "get_relayer",
1941
+ calldata: []
1942
+ });
1943
+ return result[0];
1944
+ }
1945
+ /** Get batch timeout in blocks */
1946
+ async getBatchTimeoutBlocks() {
1947
+ const result = await this.obelysk.provider.callContract({
1948
+ contractAddress: this.contractAddress,
1949
+ entrypoint: "get_batch_timeout_blocks",
1950
+ calldata: []
1951
+ });
1952
+ return Number(BigInt(result[0]));
1953
+ }
1954
+ // --------------------------------------------------------------------------
1955
+ // Relayer HTTP calls
1956
+ // --------------------------------------------------------------------------
1957
+ /** Check relayer health (no auth required) */
1958
+ async getRelayerHealth() {
1959
+ return this.relayerFetch("/health");
1960
+ }
1961
+ /** Get relayer queue status */
1962
+ async getRelayerStatus() {
1963
+ const data = await this.relayerFetch("/status");
1964
+ return {
1965
+ pendingTransactions: data.pending_transactions,
1966
+ batchMaxSize: data.batch_max_size,
1967
+ batchTimeoutSecs: data.batch_timeout_secs
1968
+ };
1969
+ }
1970
+ /** Get the relayer's public encryption key */
1971
+ async getRelayerPublicKey() {
1972
+ const data = await this.relayerFetch("/public-key");
1973
+ return {
1974
+ publicKey: data.public_key,
1975
+ version: data.version,
1976
+ algorithm: data.algorithm
1977
+ };
1978
+ }
1979
+ /** Submit a deposit transaction to the relayer */
1980
+ async submitDeposit(params) {
1981
+ return this.relayerFetch("/submit", {
1982
+ method: "POST",
1983
+ body: JSON.stringify({
1984
+ type: "deposit",
1985
+ amount: Number(params.amount),
1986
+ asset_id: params.assetId,
1987
+ recipient_pubkey: params.recipientPubkey,
1988
+ recipient_viewing_key: params.recipientViewingKey
1989
+ })
1990
+ });
1991
+ }
1992
+ /** Submit a withdrawal transaction to the relayer */
1993
+ async submitWithdraw(params) {
1994
+ return this.relayerFetch("/submit", {
1995
+ method: "POST",
1996
+ body: JSON.stringify({
1997
+ type: "withdraw",
1998
+ amount: Number(params.amount),
1999
+ asset_id: params.assetId,
2000
+ note: {
2001
+ owner_pubkey: params.note.owner_pubkey,
2002
+ asset_id: params.note.asset_id,
2003
+ amount_lo: params.note.amount_lo,
2004
+ amount_hi: params.note.amount_hi,
2005
+ blinding: params.note.blinding
2006
+ },
2007
+ spending_key: params.spendingKey,
2008
+ merkle_path: params.merklePath,
2009
+ merkle_root: params.merkleRoot,
2010
+ withdrawal_binding: params.withdrawalBinding,
2011
+ binding_salt: params.bindingSalt
2012
+ })
2013
+ });
2014
+ }
2015
+ /** Submit a private transfer transaction to the relayer */
2016
+ async submitTransfer(params) {
2017
+ return this.relayerFetch("/submit", {
2018
+ method: "POST",
2019
+ body: JSON.stringify({
2020
+ type: "transfer",
2021
+ amount: Number(params.amount),
2022
+ asset_id: params.assetId,
2023
+ recipient_pubkey: params.recipientPubkey,
2024
+ recipient_viewing_key: params.recipientViewingKey,
2025
+ sender_viewing_key: params.senderViewingKey,
2026
+ input_notes: params.inputNotes.map((n) => ({
2027
+ note: n.note,
2028
+ spending_key: n.spendingKey,
2029
+ merkle_path: n.merklePath
2030
+ })),
2031
+ merkle_root: params.merkleRoot
2032
+ })
2033
+ });
2034
+ }
2035
+ /** Query batch info from the relayer */
2036
+ async queryBatch(batchId) {
2037
+ const data = await this.relayerFetch(`/batch/${batchId}`);
2038
+ return {
2039
+ id: data.id,
2040
+ status: data.status,
2041
+ txCount: data.tx_count,
2042
+ proofHash: data.proof_hash,
2043
+ batchIdOnchain: data.batch_id_onchain,
2044
+ txHash: data.tx_hash,
2045
+ createdAt: data.created_at,
2046
+ error: data.error
2047
+ };
2048
+ }
2049
+ /** Fetch Merkle path for a commitment from the relayer */
2050
+ async fetchMerklePath(commitment) {
2051
+ const data = await this.relayerFetch(`/merkle-path/${commitment}`);
2052
+ return {
2053
+ commitment: data.commitment,
2054
+ merklePath: data.merkle_path ?? null,
2055
+ merkleRoot: data.merkle_root ?? null,
2056
+ batchId: data.batch_id ?? null,
2057
+ createdAt: data.created_at,
2058
+ status: data.status
2059
+ };
2060
+ }
2061
+ /** Force the relayer to prove the current batch immediately */
2062
+ async forceProve() {
2063
+ const data = await this.relayerFetch("/prove", { method: "POST" });
2064
+ return {
2065
+ status: data.status,
2066
+ batchId: data.batch_id
2067
+ };
2068
+ }
2069
+ // --------------------------------------------------------------------------
2070
+ // Helpers
2071
+ // --------------------------------------------------------------------------
2072
+ /** Encode a bigint amount into M31 lo/hi pair (31-bit limbs) */
2073
+ static encodeAmountM31(amount) {
2074
+ const lo = Number(amount & 0x7FFFFFFFn);
2075
+ const hi = Number(amount >> 31n);
2076
+ return { lo, hi };
2077
+ }
2078
+ /** Decode an M31 lo/hi pair back into a bigint amount */
2079
+ static decodeAmountM31(lo, hi) {
2080
+ return BigInt(lo) + BigInt(hi) * (1n << 31n);
2081
+ }
2082
+ };
2083
+
2084
+ // src/obelysk/vm31Bridge.ts
2085
+ var VM31BridgeClient = class {
2086
+ constructor(obelysk) {
2087
+ this.obelysk = obelysk;
2088
+ }
2089
+ get contractAddress() {
2090
+ return this.obelysk.contracts.vm31_bridge;
2091
+ }
2092
+ /** Get the authorized relayer address */
2093
+ async getRelayer() {
2094
+ const result = await this.obelysk.provider.callContract({
2095
+ contractAddress: this.contractAddress,
2096
+ entrypoint: "get_relayer",
2097
+ calldata: []
2098
+ });
2099
+ return result[0];
2100
+ }
2101
+ /** Get the VM31Pool contract address */
2102
+ async getVM31Pool() {
2103
+ const result = await this.obelysk.provider.callContract({
2104
+ contractAddress: this.contractAddress,
2105
+ entrypoint: "get_vm31_pool",
2106
+ calldata: []
2107
+ });
2108
+ return result[0];
2109
+ }
2110
+ /** Get the ConfidentialTransfer contract address */
2111
+ async getConfidentialTransfer() {
2112
+ const result = await this.obelysk.provider.callContract({
2113
+ contractAddress: this.contractAddress,
2114
+ entrypoint: "get_confidential_transfer",
2115
+ calldata: []
2116
+ });
2117
+ return result[0];
2118
+ }
2119
+ /** Get the asset pair mapping for a given token address */
2120
+ async getAssetPair(tokenAddress) {
2121
+ try {
2122
+ const result = await this.obelysk.provider.callContract({
2123
+ contractAddress: this.contractAddress,
2124
+ entrypoint: "get_asset_pair",
2125
+ calldata: [tokenAddress]
2126
+ });
2127
+ return {
2128
+ vm31AssetId: result[0],
2129
+ confidentialAssetId: result[1]
2130
+ };
2131
+ } catch {
2132
+ return null;
2133
+ }
2134
+ }
2135
+ /** Check if a bridge key has already been processed */
2136
+ async isBridgeKeyProcessed(bridgeKey) {
2137
+ const result = await this.obelysk.provider.callContract({
2138
+ contractAddress: this.contractAddress,
2139
+ entrypoint: "is_bridge_key_processed",
2140
+ calldata: [bridgeKey]
2141
+ });
2142
+ return BigInt(result[0]) !== 0n;
2143
+ }
2144
+ /** Compute a bridge key from withdrawal parameters */
2145
+ async computeBridgeKey(params) {
2146
+ const low = params.amount & (1n << 128n) - 1n;
2147
+ const high = params.amount >> 128n;
2148
+ const result = await this.obelysk.provider.callContract({
2149
+ contractAddress: this.contractAddress,
2150
+ entrypoint: "compute_bridge_key",
2151
+ calldata: [
2152
+ params.batchId,
2153
+ params.withdrawalIdx.toString(),
2154
+ params.payoutRecipient,
2155
+ params.creditRecipient,
2156
+ params.token,
2157
+ low.toString(),
2158
+ high.toString()
2159
+ ]
2160
+ });
2161
+ return result[0];
2162
+ }
2163
+ /** Get full bridge configuration (relayer, vm31Pool, confidentialTransfer) */
2164
+ async getConfig() {
2165
+ const [relayer, vm31Pool, confidentialTransfer] = await Promise.all([
2166
+ this.getRelayer(),
2167
+ this.getVM31Pool(),
2168
+ this.getConfidentialTransfer()
2169
+ ]);
2170
+ return { relayer, vm31Pool, confidentialTransfer };
2171
+ }
2172
+ /** Get pending upgrade info, if any */
2173
+ async getPendingUpgrade() {
2174
+ const result = await this.obelysk.provider.callContract({
2175
+ contractAddress: this.contractAddress,
2176
+ entrypoint: "get_pending_upgrade",
2177
+ calldata: []
2178
+ });
2179
+ const classHash = result[0];
2180
+ if (classHash === "0x0") return null;
2181
+ return {
2182
+ classHash,
2183
+ scheduledAt: Number(BigInt(result[1]))
2184
+ };
2185
+ }
2186
+ /** Check if the bridge contract is paused */
2187
+ async isPaused() {
2188
+ try {
2189
+ const result = await this.obelysk.provider.callContract({
2190
+ contractAddress: this.contractAddress,
2191
+ entrypoint: "is_paused",
2192
+ calldata: []
2193
+ });
2194
+ return BigInt(result[0]) !== 0n;
2195
+ } catch {
2196
+ return false;
2197
+ }
2198
+ }
2199
+ };
2200
+
2201
+ // src/obelysk/otcOrderbook.ts
2202
+ var OrderSide = /* @__PURE__ */ ((OrderSide2) => {
2203
+ OrderSide2[OrderSide2["Buy"] = 0] = "Buy";
2204
+ OrderSide2[OrderSide2["Sell"] = 1] = "Sell";
2205
+ return OrderSide2;
2206
+ })(OrderSide || {});
2207
+ var OrderType = /* @__PURE__ */ ((OrderType2) => {
2208
+ OrderType2[OrderType2["Limit"] = 0] = "Limit";
2209
+ OrderType2[OrderType2["Market"] = 1] = "Market";
2210
+ return OrderType2;
2211
+ })(OrderType || {});
2212
+ var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
2213
+ OrderStatus2[OrderStatus2["Open"] = 0] = "Open";
2214
+ OrderStatus2[OrderStatus2["PartialFill"] = 1] = "PartialFill";
2215
+ OrderStatus2[OrderStatus2["Filled"] = 2] = "Filled";
2216
+ OrderStatus2[OrderStatus2["Cancelled"] = 3] = "Cancelled";
2217
+ OrderStatus2[OrderStatus2["Expired"] = 4] = "Expired";
2218
+ return OrderStatus2;
2219
+ })(OrderStatus || {});
2220
+ var U128_MASK = (1n << 128n) - 1n;
2221
+ function splitU256(value) {
2222
+ return {
2223
+ low: (value & U128_MASK).toString(),
2224
+ high: (value >> 128n).toString()
2225
+ };
2226
+ }
2227
+ function parseU256(result, offset) {
2228
+ return BigInt(result[offset]) + (BigInt(result[offset + 1]) << 128n);
2229
+ }
2230
+ var ORDER_SIDE_VALUES = [0 /* Buy */, 1 /* Sell */];
2231
+ var ORDER_TYPE_VALUES = [0 /* Limit */, 1 /* Market */];
2232
+ var ORDER_STATUS_VALUES = [
2233
+ 0 /* Open */,
2234
+ 1 /* PartialFill */,
2235
+ 2 /* Filled */,
2236
+ 3 /* Cancelled */,
2237
+ 4 /* Expired */
2238
+ ];
2239
+ var ORDER_FELT_COUNT = 15;
2240
+ function parseOrder(result, offset) {
2241
+ return {
2242
+ orderId: parseU256(result, offset),
2243
+ maker: result[offset + 2],
2244
+ pairId: Number(BigInt(result[offset + 3])),
2245
+ side: ORDER_SIDE_VALUES[Number(BigInt(result[offset + 4]))] ?? 0 /* Buy */,
2246
+ orderType: ORDER_TYPE_VALUES[Number(BigInt(result[offset + 5]))] ?? 0 /* Limit */,
2247
+ price: parseU256(result, offset + 6),
2248
+ amount: parseU256(result, offset + 8),
2249
+ remaining: parseU256(result, offset + 10),
2250
+ status: ORDER_STATUS_VALUES[Number(BigInt(result[offset + 12]))] ?? 0 /* Open */,
2251
+ createdAt: Number(BigInt(result[offset + 13])),
2252
+ expiresAt: Number(BigInt(result[offset + 14]))
2253
+ };
2254
+ }
2255
+ var TRADE_FELT_COUNT = 15;
2256
+ function parseTrade(result, offset) {
2257
+ return {
2258
+ tradeId: parseU256(result, offset),
2259
+ makerOrderId: parseU256(result, offset + 2),
2260
+ takerOrderId: parseU256(result, offset + 4),
2261
+ maker: result[offset + 6],
2262
+ taker: result[offset + 7],
2263
+ price: parseU256(result, offset + 8),
2264
+ amount: parseU256(result, offset + 10),
2265
+ quoteAmount: parseU256(result, offset + 12),
2266
+ executedAt: Number(BigInt(result[offset + 14]))
2267
+ };
2268
+ }
2269
+ var OTCOrderbookClient = class {
2270
+ constructor(obelysk) {
2271
+ this.obelysk = obelysk;
2272
+ }
2273
+ get contractAddress() {
2274
+ const addr = this.obelysk.contracts.otc_orderbook;
2275
+ if (!addr) throw new Error("OTC Orderbook contract not configured for this network");
2276
+ return addr;
2277
+ }
2278
+ // --------------------------------------------------------------------------
2279
+ // Write operations
2280
+ // --------------------------------------------------------------------------
2281
+ /**
2282
+ * Place a limit order on the orderbook.
2283
+ *
2284
+ * The contract handles internal matching against resting orders.
2285
+ * Returns the transaction hash.
2286
+ */
2287
+ async placeLimitOrder(params) {
2288
+ const account = this.obelysk.requireAccount();
2289
+ const { low: pLow, high: pHigh } = splitU256(params.price);
2290
+ const { low: aLow, high: aHigh } = splitU256(params.amount);
2291
+ const result = await account.execute([
2292
+ {
2293
+ contractAddress: this.contractAddress,
2294
+ entrypoint: "place_limit_order",
2295
+ calldata: [
2296
+ params.pairId.toString(),
2297
+ params.side.toString(),
2298
+ pLow,
2299
+ pHigh,
2300
+ aLow,
2301
+ aHigh,
2302
+ (params.expiresIn ?? 0).toString()
2303
+ ]
2304
+ }
2305
+ ]);
2306
+ return result.transaction_hash;
2307
+ }
2308
+ /**
2309
+ * Place a market order that fills immediately against resting liquidity.
2310
+ * Returns the transaction hash.
2311
+ */
2312
+ async placeMarketOrder(params) {
2313
+ const account = this.obelysk.requireAccount();
2314
+ const { low: aLow, high: aHigh } = splitU256(params.amount);
2315
+ const result = await account.execute([
2316
+ {
2317
+ contractAddress: this.contractAddress,
2318
+ entrypoint: "place_market_order",
2319
+ calldata: [
2320
+ params.pairId.toString(),
2321
+ params.side.toString(),
2322
+ aLow,
2323
+ aHigh
2324
+ ]
2325
+ }
2326
+ ]);
2327
+ return result.transaction_hash;
2328
+ }
2329
+ /**
2330
+ * Cancel a single order by ID.
2331
+ * Only the maker can cancel their own order.
2332
+ */
2333
+ async cancelOrder(orderId) {
2334
+ const account = this.obelysk.requireAccount();
2335
+ const { low, high } = splitU256(orderId);
2336
+ const result = await account.execute([
2337
+ {
2338
+ contractAddress: this.contractAddress,
2339
+ entrypoint: "cancel_order",
2340
+ calldata: [low, high]
2341
+ }
2342
+ ]);
2343
+ return result.transaction_hash;
2344
+ }
2345
+ /**
2346
+ * Cancel all open orders for the caller.
2347
+ */
2348
+ async cancelAllOrders() {
2349
+ const account = this.obelysk.requireAccount();
2350
+ const result = await account.execute([
2351
+ {
2352
+ contractAddress: this.contractAddress,
2353
+ entrypoint: "cancel_all_orders",
2354
+ calldata: []
2355
+ }
2356
+ ]);
2357
+ return result.transaction_hash;
2358
+ }
2359
+ /**
2360
+ * Place multiple limit orders in a single transaction.
2361
+ *
2362
+ * Cairo expects an array of (u8, OrderSide, u256, u256, u64) tuples.
2363
+ * Calldata: [length, ...flattened orders].
2364
+ */
2365
+ async batchPlaceOrders(orders) {
2366
+ const account = this.obelysk.requireAccount();
2367
+ const calldata = [orders.length.toString()];
2368
+ for (const order of orders) {
2369
+ const { low: pLow, high: pHigh } = splitU256(order.price);
2370
+ const { low: aLow, high: aHigh } = splitU256(order.amount);
2371
+ calldata.push(
2372
+ order.pairId.toString(),
2373
+ order.side.toString(),
2374
+ pLow,
2375
+ pHigh,
2376
+ aLow,
2377
+ aHigh,
2378
+ (order.expiresIn ?? 0).toString()
2379
+ );
2380
+ }
2381
+ const result = await account.execute([
2382
+ {
2383
+ contractAddress: this.contractAddress,
2384
+ entrypoint: "batch_place_orders",
2385
+ calldata
2386
+ }
2387
+ ]);
2388
+ return result.transaction_hash;
2389
+ }
2390
+ /**
2391
+ * Cancel multiple orders in a single transaction.
2392
+ *
2393
+ * Calldata: [length, ...flattened u256 order IDs].
2394
+ */
2395
+ async batchCancelOrders(orderIds) {
2396
+ const account = this.obelysk.requireAccount();
2397
+ const calldata = [orderIds.length.toString()];
2398
+ for (const id of orderIds) {
2399
+ const { low, high } = splitU256(id);
2400
+ calldata.push(low, high);
2401
+ }
2402
+ const result = await account.execute([
2403
+ {
2404
+ contractAddress: this.contractAddress,
2405
+ entrypoint: "batch_cancel_orders",
2406
+ calldata
2407
+ }
2408
+ ]);
2409
+ return result.transaction_hash;
2410
+ }
2411
+ // --------------------------------------------------------------------------
2412
+ // Read operations
2413
+ // --------------------------------------------------------------------------
2414
+ /**
2415
+ * Get a single order by ID.
2416
+ */
2417
+ async getOrder(orderId) {
2418
+ const { low, high } = splitU256(orderId);
2419
+ const result = await this.obelysk.provider.callContract({
2420
+ contractAddress: this.contractAddress,
2421
+ entrypoint: "get_order",
2422
+ calldata: [low, high]
2423
+ });
2424
+ return parseOrder(result, 0);
2425
+ }
2426
+ /**
2427
+ * Get all order IDs belonging to a user.
2428
+ */
2429
+ async getUserOrders(user) {
2430
+ const result = await this.obelysk.provider.callContract({
2431
+ contractAddress: this.contractAddress,
2432
+ entrypoint: "get_user_orders",
2433
+ calldata: [user]
2434
+ });
2435
+ const len = Number(BigInt(result[0]));
2436
+ const ids = [];
2437
+ for (let i = 0; i < len; i++) {
2438
+ ids.push(parseU256(result, 1 + i * 2));
2439
+ }
2440
+ return ids;
2441
+ }
2442
+ /**
2443
+ * Get the best (highest) bid price for a trading pair.
2444
+ */
2445
+ async getBestBid(pairId) {
2446
+ const result = await this.obelysk.provider.callContract({
2447
+ contractAddress: this.contractAddress,
2448
+ entrypoint: "get_best_bid",
2449
+ calldata: [pairId.toString()]
2450
+ });
2451
+ return parseU256(result, 0);
2452
+ }
2453
+ /**
2454
+ * Get the best (lowest) ask price for a trading pair.
2455
+ */
2456
+ async getBestAsk(pairId) {
2457
+ const result = await this.obelysk.provider.callContract({
2458
+ contractAddress: this.contractAddress,
2459
+ entrypoint: "get_best_ask",
2460
+ calldata: [pairId.toString()]
2461
+ });
2462
+ return parseU256(result, 0);
2463
+ }
2464
+ /**
2465
+ * Get the bid-ask spread for a trading pair.
2466
+ */
2467
+ async getSpread(pairId) {
2468
+ const result = await this.obelysk.provider.callContract({
2469
+ contractAddress: this.contractAddress,
2470
+ entrypoint: "get_spread",
2471
+ calldata: [pairId.toString()]
2472
+ });
2473
+ return parseU256(result, 0);
2474
+ }
2475
+ /**
2476
+ * Get trading pair configuration.
2477
+ */
2478
+ async getPair(pairId) {
2479
+ const result = await this.obelysk.provider.callContract({
2480
+ contractAddress: this.contractAddress,
2481
+ entrypoint: "get_pair",
2482
+ calldata: [pairId.toString()]
2483
+ });
2484
+ return {
2485
+ baseToken: result[0],
2486
+ quoteToken: result[1],
2487
+ minOrderSize: parseU256(result, 2),
2488
+ tickSize: parseU256(result, 4),
2489
+ isActive: BigInt(result[6]) !== 0n
2490
+ };
2491
+ }
2492
+ /**
2493
+ * Get the orderbook configuration (fees, limits, pause state).
2494
+ */
2495
+ async getConfig() {
2496
+ const result = await this.obelysk.provider.callContract({
2497
+ contractAddress: this.contractAddress,
2498
+ entrypoint: "get_config",
2499
+ calldata: []
2500
+ });
2501
+ return {
2502
+ makerFeeBps: Number(BigInt(result[0])),
2503
+ takerFeeBps: Number(BigInt(result[1])),
2504
+ defaultExpirySecs: Number(BigInt(result[2])),
2505
+ maxOrdersPerUser: Number(BigInt(result[3])),
2506
+ paused: BigInt(result[4]) !== 0n
2507
+ };
2508
+ }
2509
+ /**
2510
+ * Get aggregate orderbook statistics.
2511
+ */
2512
+ async getStats() {
2513
+ const result = await this.obelysk.provider.callContract({
2514
+ contractAddress: this.contractAddress,
2515
+ entrypoint: "get_stats",
2516
+ calldata: []
2517
+ });
2518
+ return {
2519
+ orderCount: parseU256(result, 0),
2520
+ tradeCount: parseU256(result, 2),
2521
+ totalVolume: parseU256(result, 4),
2522
+ totalFees: parseU256(result, 6)
2523
+ };
2524
+ }
2525
+ /**
2526
+ * Get total number of orders ever placed.
2527
+ */
2528
+ async getOrderCount() {
2529
+ const result = await this.obelysk.provider.callContract({
2530
+ contractAddress: this.contractAddress,
2531
+ entrypoint: "get_order_count",
2532
+ calldata: []
2533
+ });
2534
+ return parseU256(result, 0);
2535
+ }
2536
+ /**
2537
+ * Get total number of trades executed.
2538
+ */
2539
+ async getTradeCount() {
2540
+ const result = await this.obelysk.provider.callContract({
2541
+ contractAddress: this.contractAddress,
2542
+ entrypoint: "get_trade_count",
2543
+ calldata: []
2544
+ });
2545
+ return parseU256(result, 0);
2546
+ }
2547
+ /**
2548
+ * Get the time-weighted average price for a trading pair.
2549
+ */
2550
+ async getTwap(pairId) {
2551
+ const result = await this.obelysk.provider.callContract({
2552
+ contractAddress: this.contractAddress,
2553
+ entrypoint: "get_twap",
2554
+ calldata: [pairId.toString()]
2555
+ });
2556
+ return parseU256(result, 0);
2557
+ }
2558
+ /**
2559
+ * Get 24-hour rolling statistics for a trading pair.
2560
+ */
2561
+ async get24hStats(pairId) {
2562
+ const result = await this.obelysk.provider.callContract({
2563
+ contractAddress: this.contractAddress,
2564
+ entrypoint: "get_24h_stats",
2565
+ calldata: [pairId.toString()]
2566
+ });
2567
+ return {
2568
+ volume: parseU256(result, 0),
2569
+ high: parseU256(result, 2),
2570
+ low: parseU256(result, 4),
2571
+ tradeCount: parseU256(result, 6)
2572
+ };
2573
+ }
2574
+ /**
2575
+ * Get the most recent trade for a trading pair.
2576
+ */
2577
+ async getLastTrade(pairId) {
2578
+ const result = await this.obelysk.provider.callContract({
2579
+ contractAddress: this.contractAddress,
2580
+ entrypoint: "get_last_trade",
2581
+ calldata: [pairId.toString()]
2582
+ });
2583
+ return {
2584
+ price: parseU256(result, 0),
2585
+ amount: parseU256(result, 2),
2586
+ timestamp: Number(BigInt(result[4]))
2587
+ };
2588
+ }
2589
+ /**
2590
+ * Get the orderbook depth (price levels) for a trading pair.
2591
+ *
2592
+ * Returns up to `maxLevels` aggregated price levels for both
2593
+ * bids and asks. Each level contains price, total amount, and
2594
+ * number of orders at that price.
2595
+ */
2596
+ async getOrderbookDepth(pairId, maxLevels) {
2597
+ const result = await this.obelysk.provider.callContract({
2598
+ contractAddress: this.contractAddress,
2599
+ entrypoint: "get_orderbook_depth",
2600
+ calldata: [pairId.toString(), maxLevels.toString()]
2601
+ });
2602
+ let offset = 0;
2603
+ const bidCount = Number(BigInt(result[offset]));
2604
+ offset += 1;
2605
+ const bids = [];
2606
+ for (let i = 0; i < bidCount; i++) {
2607
+ bids.push({
2608
+ price: parseU256(result, offset),
2609
+ totalAmount: parseU256(result, offset + 2),
2610
+ orderCount: Number(BigInt(result[offset + 4]))
2611
+ });
2612
+ offset += 5;
2613
+ }
2614
+ const askCount = Number(BigInt(result[offset]));
2615
+ offset += 1;
2616
+ const asks = [];
2617
+ for (let i = 0; i < askCount; i++) {
2618
+ asks.push({
2619
+ price: parseU256(result, offset),
2620
+ totalAmount: parseU256(result, offset + 2),
2621
+ orderCount: Number(BigInt(result[offset + 4]))
2622
+ });
2623
+ offset += 5;
2624
+ }
2625
+ return { bids, asks };
2626
+ }
2627
+ /**
2628
+ * Get active orders for a trading pair with pagination.
2629
+ */
2630
+ async getActiveOrders(pairId, offset, limit) {
2631
+ const result = await this.obelysk.provider.callContract({
2632
+ contractAddress: this.contractAddress,
2633
+ entrypoint: "get_active_orders",
2634
+ calldata: [pairId.toString(), offset.toString(), limit.toString()]
2635
+ });
2636
+ const len = Number(BigInt(result[0]));
2637
+ const orders = [];
2638
+ for (let i = 0; i < len; i++) {
2639
+ orders.push(parseOrder(result, 1 + i * ORDER_FELT_COUNT));
2640
+ }
2641
+ return orders;
2642
+ }
2643
+ /**
2644
+ * Get trade history for a trading pair with pagination.
2645
+ */
2646
+ async getTradeHistory(pairId, offset, limit) {
2647
+ const result = await this.obelysk.provider.callContract({
2648
+ contractAddress: this.contractAddress,
2649
+ entrypoint: "get_trade_history",
2650
+ calldata: [pairId.toString(), offset.toString(), limit.toString()]
2651
+ });
2652
+ const len = Number(BigInt(result[0]));
2653
+ const trades = [];
2654
+ for (let i = 0; i < len; i++) {
2655
+ trades.push(parseTrade(result, 1 + i * TRADE_FELT_COUNT));
2656
+ }
2657
+ return trades;
2658
+ }
2659
+ /**
2660
+ * Get the contract owner address.
2661
+ */
2662
+ async getOwner() {
2663
+ const result = await this.obelysk.provider.callContract({
2664
+ contractAddress: this.contractAddress,
2665
+ entrypoint: "owner",
2666
+ calldata: []
2667
+ });
2668
+ return result[0];
2669
+ }
1352
2670
  };
1353
2671
 
1354
2672
  // src/obelysk/client.ts
@@ -1360,6 +2678,8 @@ var ObelyskClient = class {
1360
2678
  contracts;
1361
2679
  tokens;
1362
2680
  privacyPools;
2681
+ relayerUrl;
2682
+ relayerApiKey;
1363
2683
  /** Privacy Pool operations (deposit/withdraw shielded tokens) */
1364
2684
  privacyPool;
1365
2685
  /** DarkPool batch auction trading */
@@ -1374,6 +2694,12 @@ var ObelyskClient = class {
1374
2694
  router;
1375
2695
  /** Shielded swap router (privacy-preserving AMM swaps) */
1376
2696
  swap;
2697
+ /** VM31 UTXO privacy vault (deposits/withdrawals/transfers via relayer) */
2698
+ vm31;
2699
+ /** VM31 confidential bridge (bridge VM31 withdrawals to encrypted balances) */
2700
+ bridge;
2701
+ /** OTC orderbook (limit/market orders, trade history) */
2702
+ otc;
1377
2703
  constructor(config) {
1378
2704
  this.network = config.network;
1379
2705
  this.provider = new RpcProvider({ nodeUrl: config.rpcUrl ?? getRpcUrl(config.network) });
@@ -1381,6 +2707,8 @@ var ObelyskClient = class {
1381
2707
  this.contracts = getContracts(config.network);
1382
2708
  this.tokens = this.contracts.tokens ?? MAINNET_TOKENS;
1383
2709
  this.privacyPools = config.network === "mainnet" ? MAINNET_PRIVACY_POOLS : {};
2710
+ this.relayerUrl = config.relayerUrl;
2711
+ this.relayerApiKey = config.relayerApiKey;
1384
2712
  this.privacy = new ObelyskPrivacy();
1385
2713
  if (config.privacyPrivateKey) {
1386
2714
  const pk = BigInt(config.privacyPrivateKey);
@@ -1393,6 +2721,9 @@ var ObelyskClient = class {
1393
2721
  this.staking = new ProverStakingClient(this);
1394
2722
  this.router = new PrivacyRouterClient(this);
1395
2723
  this.swap = new ShieldedSwapClient(this);
2724
+ this.vm31 = new VM31VaultClient(this);
2725
+ this.bridge = new VM31BridgeClient(this);
2726
+ this.otc = new OTCOrderbookClient(this);
1396
2727
  }
1397
2728
  /** Get token address by symbol */
1398
2729
  getTokenAddress(symbol) {
@@ -1422,14 +2753,20 @@ export {
1422
2753
  GENERATOR_H,
1423
2754
  MAINNET_PRIVACY_POOLS,
1424
2755
  MAINNET_TOKENS,
2756
+ OTCOrderbookClient,
1425
2757
  ObelyskClient,
1426
2758
  ObelyskPrivacy,
2759
+ OrderSide,
2760
+ OrderStatus,
2761
+ OrderType,
1427
2762
  PrivacyPoolClient,
1428
2763
  PrivacyRouterClient,
1429
2764
  ProverStakingClient,
1430
2765
  ShieldedSwapClient,
1431
2766
  StealthClient,
1432
2767
  TOKEN_DECIMALS,
2768
+ VM31BridgeClient,
2769
+ VM31VaultClient,
1433
2770
  VM31_ASSET_IDS,
1434
2771
  commitmentToHash,
1435
2772
  createAEHint,