@theliem/xmarket-sdk 3.4.2 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -2,7 +2,7 @@ import * as anchor5 from '@coral-xyz/anchor';
2
2
  import { PublicKey, SYSVAR_INSTRUCTIONS_PUBKEY, SystemProgram, SYSVAR_RENT_PUBKEY, ComputeBudgetProgram, Transaction, TransactionInstruction, Ed25519Program, AddressLookupTableProgram, TransactionMessage, VersionedTransaction, Connection } from '@solana/web3.js';
3
3
  import { createHash } from 'crypto';
4
4
  import { TOKEN_2022_PROGRAM_ID, getAssociatedTokenAddressSync, ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID, createAssociatedTokenAccountIdempotentInstruction, createApproveInstruction } from '@solana/spl-token';
5
- import BN5 from 'bn.js';
5
+ import BN4 from 'bn.js';
6
6
  import * as nacl from 'tweetnacl';
7
7
 
8
8
  // src/sdk.ts
@@ -1312,6 +1312,108 @@ function buildBatchedEd25519Instruction(orders) {
1312
1312
  });
1313
1313
  }
1314
1314
  var IX_SYSVAR = SYSVAR_INSTRUCTIONS_PUBKEY;
1315
+ function buildOrder(params) {
1316
+ return {
1317
+ maker: params.maker,
1318
+ condition: params.condition,
1319
+ tokenId: params.tokenId,
1320
+ side: params.side,
1321
+ makerAmount: params.makerAmount,
1322
+ takerAmount: params.takerAmount,
1323
+ nonce: params.nonce ?? new BN4(Date.now()),
1324
+ expiry: params.expiry ?? new BN4(0),
1325
+ createdAt: params.createdAt ?? new BN4(Math.floor(Date.now() / 1e3)),
1326
+ fee: params.fee ?? new BN4(0),
1327
+ taker: params.taker ?? new PublicKey(new Uint8Array(32)),
1328
+ signer: params.maker
1329
+ };
1330
+ }
1331
+ function orderAmountsFromPrice(side, price, quantity, decimals = 9) {
1332
+ const PRICE_PRECISION = new BN4(1e6);
1333
+ const DENOM = new BN4(100).mul(PRICE_PRECISION);
1334
+ const base = new BN4(10).pow(new BN4(decimals));
1335
+ const priceScaled = new BN4(Math.round(price * 1e6));
1336
+ const quantityBase = new BN4(quantity).mul(base);
1337
+ const collateral = quantityBase.mul(priceScaled).div(DENOM);
1338
+ return side === 0 ? { makerAmount: collateral, takerAmount: quantityBase } : { makerAmount: quantityBase, takerAmount: collateral };
1339
+ }
1340
+ function buildOrderFromPrice(params) {
1341
+ const { makerAmount, takerAmount } = orderAmountsFromPrice(
1342
+ params.side,
1343
+ params.price,
1344
+ params.quantity,
1345
+ params.decimals ?? 9
1346
+ );
1347
+ return buildOrder({ ...params, makerAmount, takerAmount });
1348
+ }
1349
+ function signOrderWithKeypair(order, keypair) {
1350
+ const message = serializeOrderToBytes(order);
1351
+ const signature = nacl.sign.detached(message, keypair.secretKey);
1352
+ return { order, signature };
1353
+ }
1354
+ function getOrderSignBytes(order) {
1355
+ return serializeOrderToBytes(order);
1356
+ }
1357
+ function serializeSignedOrder(signed) {
1358
+ const orderBytes = serializeOrderToBytes(signed.order);
1359
+ const buf = new Uint8Array(242);
1360
+ buf.set(orderBytes, 0);
1361
+ buf.set(signed.signature, 178);
1362
+ return buf;
1363
+ }
1364
+ function deserializeSignedOrder(bytes) {
1365
+ if (bytes.length !== 242) throw new InvalidParamError("SignedOrder must be 242 bytes");
1366
+ const readPubkey = (offset) => new PublicKey(bytes.slice(offset, offset + 32));
1367
+ const readU64 = (offset) => new BN4(bytes.slice(offset, offset + 8), "le");
1368
+ const readI64 = (offset) => new BN4(bytes.slice(offset, offset + 8), "le");
1369
+ const order = {
1370
+ maker: readPubkey(0),
1371
+ condition: readPubkey(32),
1372
+ tokenId: bytes[64],
1373
+ side: bytes[65],
1374
+ makerAmount: readU64(66),
1375
+ takerAmount: readU64(74),
1376
+ nonce: readU64(82),
1377
+ expiry: readI64(90),
1378
+ createdAt: readI64(98),
1379
+ fee: readU64(106),
1380
+ taker: readPubkey(114),
1381
+ signer: readPubkey(146)
1382
+ };
1383
+ const signature = bytes.slice(178, 242);
1384
+ return { order, signature };
1385
+ }
1386
+ function verifySignedOrder(signed) {
1387
+ const message = serializeOrderToBytes(signed.order);
1388
+ return nacl.sign.detached.verify(
1389
+ message,
1390
+ signed.signature,
1391
+ signed.order.signer.toBytes()
1392
+ );
1393
+ }
1394
+ function detectMatchType(a, b) {
1395
+ const _a = "order" in a ? a.order : a;
1396
+ const _b = "order" in b ? b.order : b;
1397
+ return _detectMatchType(_a, _b);
1398
+ }
1399
+ function _detectMatchType(a, b) {
1400
+ const SIDE_BUY = 0;
1401
+ if (a.tokenId === b.tokenId) {
1402
+ const aBuy2 = a.side === SIDE_BUY;
1403
+ const bBuy2 = b.side === SIDE_BUY;
1404
+ if (aBuy2 !== bBuy2) return "COMPLEMENTARY";
1405
+ throw new InvalidParamError(
1406
+ "Orders with same tokenId must be one BUY and one SELL (COMPLEMENTARY)"
1407
+ );
1408
+ }
1409
+ const aBuy = a.side === SIDE_BUY;
1410
+ const bBuy = b.side === SIDE_BUY;
1411
+ if (aBuy && bBuy) return "MINT";
1412
+ if (!aBuy && !bBuy) return "MERGE";
1413
+ throw new InvalidParamError(
1414
+ "Orders with different tokenIds must both be BUY (MINT) or both SELL (MERGE)"
1415
+ );
1416
+ }
1315
1417
 
1316
1418
  // src/programs/clob.ts
1317
1419
  var ClobClient = class {
@@ -1381,15 +1483,39 @@ var ClobClient = class {
1381
1483
  takerOrderRecord
1382
1484
  ];
1383
1485
  if (feeRecipientAddr) addresses.push(feeRecipientAddr);
1486
+ const [collateralVault] = PDA.collateralVault(collateralMint, this.programIds);
1487
+ const [vaultToken] = PDA.vaultToken(collateralMint, this.programIds);
1488
+ const [mintAuth] = PDA.mintAuthority(condition, this.programIds);
1489
+ const [extraMetaNo] = PDA.extraAccountMetaList(noMint, this.programIds);
1490
+ const clobUsdcAta = getAssociatedTokenAddressSync(collateralMint, clobConfigPda, true);
1491
+ const clobYesAta = getAssociatedTokenAddressSync(yesMint, clobConfigPda, true, TOKEN_2022_PROGRAM_ID);
1492
+ const clobNoAta = getAssociatedTokenAddressSync(noMint, clobConfigPda, true, TOKEN_2022_PROGRAM_ID);
1493
+ const [clobYesPos] = PDA.position(condition, 1, clobConfigPda, this.programIds);
1494
+ const [clobNoPos] = PDA.position(condition, 0, clobConfigPda, this.programIds);
1495
+ addresses.push(
1496
+ collateralVault,
1497
+ vaultToken,
1498
+ mintAuth,
1499
+ extraMetaNo,
1500
+ clobUsdcAta,
1501
+ clobYesAta,
1502
+ clobNoAta,
1503
+ clobYesPos,
1504
+ clobNoPos,
1505
+ collateralMint,
1506
+ ASSOCIATED_TOKEN_PROGRAM_ID
1507
+ );
1384
1508
  for (const m of makers) {
1385
1509
  const seller = m.order.maker;
1386
- const [sellerPos] = PDA.position(condition, tokenId, seller, this.programIds);
1510
+ const makerTokenId = m.order.tokenId;
1511
+ const makerMint = makerTokenId === 1 ? yesMint : noMint;
1512
+ const [sellerPos] = PDA.position(condition, makerTokenId, seller, this.programIds);
1387
1513
  const [sellerStatus] = PDA.orderStatus(seller, m.order.nonce, this.programIds);
1388
1514
  const [sellerRecord] = PDA.orderRecord(seller, m.order.nonce, this.programIds);
1389
1515
  addresses.push(
1390
1516
  seller,
1391
1517
  sellerRecord,
1392
- getAssociatedTokenAddressSync(outcomeMint, seller, false, TOKEN_2022_PROGRAM_ID),
1518
+ getAssociatedTokenAddressSync(makerMint, seller, false, TOKEN_2022_PROGRAM_ID),
1393
1519
  getAssociatedTokenAddressSync(collateralMint, seller),
1394
1520
  sellerPos,
1395
1521
  sellerStatus
@@ -1461,6 +1587,36 @@ ${logs.join("\n")}`);
1461
1587
  async _sendLegacyTx(instructions) {
1462
1588
  await this._sendLegacyTxSig(instructions);
1463
1589
  }
1590
+ async _ensureClobOutcomeAtas(yesMint, noMint, clobConfig, clobYesAta, clobNoAta) {
1591
+ const { connection } = this.provider;
1592
+ const [yesInfo, noInfo] = await Promise.all([
1593
+ connection.getAccountInfo(clobYesAta),
1594
+ connection.getAccountInfo(clobNoAta)
1595
+ ]);
1596
+ const { createAssociatedTokenAccountIdempotentInstruction: createAssociatedTokenAccountIdempotentInstruction2 } = await import('@solana/spl-token');
1597
+ const ixs = [];
1598
+ if (!yesInfo) {
1599
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction2(
1600
+ this.walletPubkey,
1601
+ clobYesAta,
1602
+ clobConfig,
1603
+ yesMint,
1604
+ TOKEN_2022_PROGRAM_ID
1605
+ ));
1606
+ }
1607
+ if (!noInfo) {
1608
+ ixs.push(createAssociatedTokenAccountIdempotentInstruction2(
1609
+ this.walletPubkey,
1610
+ clobNoAta,
1611
+ clobConfig,
1612
+ noMint,
1613
+ TOKEN_2022_PROGRAM_ID
1614
+ ));
1615
+ }
1616
+ if (ixs.length > 0) {
1617
+ await this._sendLegacyTx(ixs);
1618
+ }
1619
+ }
1464
1620
  /**
1465
1621
  * Send a match transaction as versioned (v0) with optional ALT.
1466
1622
  * Both operator wallet and payer (this.provider.wallet) sign.
@@ -1468,11 +1624,12 @@ ${logs.join("\n")}`);
1468
1624
  async sendMatchTx(instructions, lookupTable, whitelistedWallet) {
1469
1625
  const { connection } = this.provider;
1470
1626
  const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
1471
- const cuLimit = ComputeBudgetProgram.setComputeUnitLimit({ units: 8e5 });
1627
+ const cuLimit = ComputeBudgetProgram.setComputeUnitLimit({ units: 14e5 });
1628
+ const heapFrame = ComputeBudgetProgram.requestHeapFrame({ bytes: 262144 });
1472
1629
  const message = new TransactionMessage({
1473
1630
  payerKey: this.walletPubkey,
1474
1631
  recentBlockhash: blockhash,
1475
- instructions: [cuLimit, ...instructions]
1632
+ instructions: [cuLimit, heapFrame, ...instructions]
1476
1633
  }).compileToV0Message(lookupTable ? [lookupTable] : []);
1477
1634
  const vtx = new VersionedTransaction(message);
1478
1635
  const signers = [this.provider.wallet.payer];
@@ -1481,7 +1638,7 @@ ${logs.join("\n")}`);
1481
1638
  }
1482
1639
  vtx.sign(signers);
1483
1640
  const sig = await connection.sendRawTransaction(vtx.serialize(), {
1484
- skipPreflight: true
1641
+ skipPreflight: false
1485
1642
  });
1486
1643
  const result = await connection.confirmTransaction(
1487
1644
  { signature: sig, blockhash, lastValidBlockHeight },
@@ -1593,7 +1750,7 @@ ${logs.join("\n")}`);
1593
1750
  * [extraAccountMetaList, hookConfig, hookProgram]
1594
1751
  * [feeManagement, fee_config, mkt_override, company_ata, oracle_vault] (when fee > 0)
1595
1752
  */
1596
- async buildMatchComplementaryIxs(takerSigned, makersSigned, collateralMint, feeRecipient, operator, opts) {
1753
+ async buildMatchComplementaryIxs(takerSigned, makersSigned, collateralMint, feeRecipient, operator, opts, useTakerPrice = false) {
1597
1754
  const condition = takerSigned.order.condition;
1598
1755
  const tokenId = takerSigned.order.tokenId;
1599
1756
  const taker = takerSigned.order.maker;
@@ -1643,7 +1800,7 @@ ${logs.join("\n")}`);
1643
1800
  ];
1644
1801
  }
1645
1802
  }
1646
- const matchIx = await this.program.methods.matchComplementary(takerNonce, fillAmount).accounts({
1803
+ const matchIx = await this.program.methods.matchComplementary(takerNonce, fillAmount, useTakerPrice).accounts({
1647
1804
  operator,
1648
1805
  payer: this.walletPubkey,
1649
1806
  clobConfig: this.configPda(),
@@ -1684,6 +1841,49 @@ ${logs.join("\n")}`);
1684
1841
  const sig = await this.sendMatchTx(ixs, lookupTable, operatorWallet);
1685
1842
  return { signature: sig };
1686
1843
  }
1844
+ /**
1845
+ * 1 SELL taker vs N BUY makers.
1846
+ * Rust program only supports BUY-as-taker, so we decompose into N instructions
1847
+ * (BUY_i as taker, SELL as single maker) combined into one atomic transaction.
1848
+ * Engine must use limitPrice for BUY.makerAmount to pass per-pair crossing check.
1849
+ */
1850
+ async matchComplementarySellVsMultiBuy(sellTaker, buyMakers, collateralMint, feeRecipient, operatorWallet, lookupTable, opts) {
1851
+ await Promise.all([
1852
+ this.registerOrderIfNeeded(sellTaker),
1853
+ ...buyMakers.map((m) => this.registerOrderIfNeeded(m))
1854
+ ]);
1855
+ const sell = sellTaker.order;
1856
+ const crossingBuys = buyMakers.filter((b) => {
1857
+ const buy = b.order;
1858
+ const lhs = BigInt(buy.makerAmount.toString()) * BigInt(sell.makerAmount.toString());
1859
+ const rhs = BigInt(buy.takerAmount.toString()) * BigInt(sell.takerAmount.toString());
1860
+ return lhs >= rhs;
1861
+ });
1862
+ if (crossingBuys.length === 0) {
1863
+ throw new InvalidParamError("COMPLEMENTARY: no BUY maker orders cross with the SELL taker");
1864
+ }
1865
+ if (crossingBuys.length < buyMakers.length) {
1866
+ console.warn(`[matchOrders] SELL+BUY: filtered ${buyMakers.length - crossingBuys.length} non-crossing BUY(s)`);
1867
+ }
1868
+ const allIxs = [];
1869
+ for (const buyMaker of crossingBuys) {
1870
+ const ixs = await this.buildMatchComplementaryIxs(
1871
+ buyMaker,
1872
+ // BUY as taker
1873
+ [sellTaker],
1874
+ // SELL as maker
1875
+ collateralMint,
1876
+ feeRecipient,
1877
+ operatorWallet.publicKey,
1878
+ opts,
1879
+ true
1880
+ // useTakerPrice: SELL gets filled at BUY's price (maker's price per doc)
1881
+ );
1882
+ allIxs.push(...ixs);
1883
+ }
1884
+ const sig = await this.sendMatchTx(allIxs, lookupTable, operatorWallet);
1885
+ return { signature: sig };
1886
+ }
1687
1887
  /**
1688
1888
  * MINT: 1 YES buyer (taker) + N NO buyers (makers).
1689
1889
  * Phase 1: register taker + all NO makers in parallel.
@@ -1701,6 +1901,7 @@ ${logs.join("\n")}`);
1701
1901
  const taker = yesSigned.order.maker;
1702
1902
  const takerNonce = yesSigned.order.nonce;
1703
1903
  const fillAmount = new anchor5.BN("18446744073709551615");
1904
+ const clobConfig = this.configPda();
1704
1905
  const [yesMint] = PDA.yesMint(condition, this.programIds);
1705
1906
  const [noMint] = PDA.noMint(condition, this.programIds);
1706
1907
  const [mintAuthority] = PDA.mintAuthority(condition, this.programIds);
@@ -1711,6 +1912,15 @@ ${logs.join("\n")}`);
1711
1912
  const takerYesToken = getAssociatedTokenAddressSync(yesMint, taker, false, TOKEN_2022_PROGRAM_ID);
1712
1913
  const [takerYesPosition] = PDA.position(condition, 1, taker, this.programIds);
1713
1914
  const [takerOrderStatus] = PDA.orderStatus(taker, takerNonce, this.programIds);
1915
+ const clobUsdcAta = getAssociatedTokenAddressSync(collateralMint, clobConfig, true);
1916
+ const clobYesAta = getAssociatedTokenAddressSync(yesMint, clobConfig, true, TOKEN_2022_PROGRAM_ID);
1917
+ const clobNoAta = getAssociatedTokenAddressSync(noMint, clobConfig, true, TOKEN_2022_PROGRAM_ID);
1918
+ const [clobYesPos] = PDA.position(condition, 1, clobConfig, this.programIds);
1919
+ const [clobNoPos] = PDA.position(condition, 0, clobConfig, this.programIds);
1920
+ const [extraMetaYes] = PDA.extraAccountMetaList(yesMint, this.programIds);
1921
+ const [extraMetaNo] = PDA.extraAccountMetaList(noMint, this.programIds);
1922
+ const [hookConfig] = PDA.hookConfig(this.programIds);
1923
+ const hookProgram = this.programIds.hook;
1714
1924
  const remainingAccounts = [];
1715
1925
  for (const nm of noMakers) {
1716
1926
  const noMaker = nm.order.maker;
@@ -1720,6 +1930,7 @@ ${logs.join("\n")}`);
1720
1930
  const [noPosition] = PDA.position(condition, 0, noMaker, this.programIds);
1721
1931
  const [noStatus] = PDA.orderStatus(noMaker, nm.order.nonce, this.programIds);
1722
1932
  remainingAccounts.push(
1933
+ { pubkey: noMaker, isSigner: false, isWritable: false },
1723
1934
  { pubkey: noRecord, isSigner: false, isWritable: false },
1724
1935
  { pubkey: noToken, isSigner: false, isWritable: true },
1725
1936
  { pubkey: noCollateral, isSigner: false, isWritable: true },
@@ -1727,10 +1938,16 @@ ${logs.join("\n")}`);
1727
1938
  { pubkey: noStatus, isSigner: false, isWritable: true }
1728
1939
  );
1729
1940
  }
1941
+ remainingAccounts.push(
1942
+ { pubkey: extraMetaYes, isSigner: false, isWritable: false },
1943
+ { pubkey: extraMetaNo, isSigner: false, isWritable: false },
1944
+ { pubkey: hookConfig, isSigner: false, isWritable: false },
1945
+ { pubkey: hookProgram, isSigner: false, isWritable: false }
1946
+ );
1730
1947
  const matchIx = await this.program.methods.matchMintOrders(takerNonce, fillAmount).accounts({
1731
1948
  operator: operatorWallet.publicKey,
1732
1949
  payer: this.walletPubkey,
1733
- clobConfig: this.configPda(),
1950
+ clobConfig,
1734
1951
  condition,
1735
1952
  taker,
1736
1953
  takerOrderRecord,
@@ -1738,16 +1955,25 @@ ${logs.join("\n")}`);
1738
1955
  takerYesToken,
1739
1956
  takerYesPosition,
1740
1957
  takerOrderStatus,
1958
+ clobUsdcAta,
1959
+ clobYesAta,
1960
+ clobNoAta,
1961
+ clobYesPosition: clobYesPos,
1962
+ clobNoPosition: clobNoPos,
1741
1963
  collateralVault,
1742
1964
  vaultTokenAccount,
1965
+ collateralMint,
1743
1966
  yesMint,
1744
1967
  noMint,
1745
1968
  mintAuthority,
1746
- clobAuthority: this.configPda(),
1969
+ clobAuthority: clobConfig,
1747
1970
  conditionalTokensProgram: this.programIds.conditionalTokens,
1748
1971
  collateralTokenProgram: TOKEN_PROGRAM_ID,
1972
+ token2022Program: TOKEN_2022_PROGRAM_ID,
1973
+ associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
1749
1974
  systemProgram: SystemProgram.programId
1750
1975
  }).remainingAccounts(remainingAccounts).instruction();
1976
+ await this._ensureClobOutcomeAtas(yesMint, noMint, clobConfig, clobYesAta, clobNoAta);
1751
1977
  const sig = await this.sendMatchTx([matchIx], lookupTable, operatorWallet);
1752
1978
  return { signature: sig };
1753
1979
  }
@@ -1769,9 +1995,9 @@ ${logs.join("\n")}`);
1769
1995
  const sellerYes = yesSigned.order.maker;
1770
1996
  const takerNonce = yesSigned.order.nonce;
1771
1997
  const fillAmount = new anchor5.BN("18446744073709551615");
1998
+ const clobConfig = this.configPda();
1772
1999
  const [yesMint] = PDA.yesMint(condition, this.programIds);
1773
2000
  const [noMint] = PDA.noMint(condition, this.programIds);
1774
- const [mintAuthority] = PDA.mintAuthority(condition, this.programIds);
1775
2001
  const [collateralVault] = PDA.collateralVault(collateralMint, this.programIds);
1776
2002
  const [vaultTokenAccount] = PDA.vaultToken(collateralMint, this.programIds);
1777
2003
  const [takerOrderRecord] = PDA.orderRecord(sellerYes, takerNonce, this.programIds);
@@ -1779,6 +2005,15 @@ ${logs.join("\n")}`);
1779
2005
  const [takerYesPosition] = PDA.position(condition, 1, sellerYes, this.programIds);
1780
2006
  const takerCollateral = getAssociatedTokenAddressSync(collateralMint, sellerYes);
1781
2007
  const [takerOrderStatus] = PDA.orderStatus(sellerYes, takerNonce, this.programIds);
2008
+ const clobUsdcAta = getAssociatedTokenAddressSync(collateralMint, clobConfig, true);
2009
+ const clobYesAta = getAssociatedTokenAddressSync(yesMint, clobConfig, true, TOKEN_2022_PROGRAM_ID);
2010
+ const clobNoAta = getAssociatedTokenAddressSync(noMint, clobConfig, true, TOKEN_2022_PROGRAM_ID);
2011
+ const [clobYesPos] = PDA.position(condition, 1, clobConfig, this.programIds);
2012
+ const [clobNoPos] = PDA.position(condition, 0, clobConfig, this.programIds);
2013
+ const [extraMetaYes] = PDA.extraAccountMetaList(yesMint, this.programIds);
2014
+ const [extraMetaNo] = PDA.extraAccountMetaList(noMint, this.programIds);
2015
+ const [hookConfig] = PDA.hookConfig(this.programIds);
2016
+ const hookProgram = this.programIds.hook;
1782
2017
  const remainingAccounts = [];
1783
2018
  for (const nm of noMakers) {
1784
2019
  const noMaker = nm.order.maker;
@@ -1788,6 +2023,7 @@ ${logs.join("\n")}`);
1788
2023
  const [noPosition] = PDA.position(condition, 0, noMaker, this.programIds);
1789
2024
  const [noStatus] = PDA.orderStatus(noMaker, nm.order.nonce, this.programIds);
1790
2025
  remainingAccounts.push(
2026
+ { pubkey: noMaker, isSigner: false, isWritable: false },
1791
2027
  { pubkey: noRecord, isSigner: false, isWritable: false },
1792
2028
  { pubkey: noToken, isSigner: false, isWritable: true },
1793
2029
  { pubkey: noCollateral, isSigner: false, isWritable: true },
@@ -1795,6 +2031,12 @@ ${logs.join("\n")}`);
1795
2031
  { pubkey: noStatus, isSigner: false, isWritable: true }
1796
2032
  );
1797
2033
  }
2034
+ remainingAccounts.push(
2035
+ { pubkey: extraMetaYes, isSigner: false, isWritable: false },
2036
+ { pubkey: extraMetaNo, isSigner: false, isWritable: false },
2037
+ { pubkey: hookConfig, isSigner: false, isWritable: false },
2038
+ { pubkey: hookProgram, isSigner: false, isWritable: false }
2039
+ );
1798
2040
  if (yesSigned.order.fee.gtn(0) && this.programIds.feeManagement && this.feeConfigOwner) {
1799
2041
  const companyAddr = await this.companyAddress();
1800
2042
  if (companyAddr) {
@@ -1811,7 +2053,7 @@ ${logs.join("\n")}`);
1811
2053
  const matchIx = await this.program.methods.matchMergeOrders(takerNonce, fillAmount).accounts({
1812
2054
  operator: operatorWallet.publicKey,
1813
2055
  payer: this.walletPubkey,
1814
- clobConfig: this.configPda(),
2056
+ clobConfig,
1815
2057
  condition,
1816
2058
  taker: sellerYes,
1817
2059
  takerOrderRecord,
@@ -1819,17 +2061,24 @@ ${logs.join("\n")}`);
1819
2061
  takerYesPosition,
1820
2062
  takerCollateral,
1821
2063
  takerOrderStatus,
2064
+ clobUsdcAta,
2065
+ clobYesAta,
2066
+ clobNoAta,
2067
+ clobYesPosition: clobYesPos,
2068
+ clobNoPosition: clobNoPos,
1822
2069
  collateralVault,
1823
2070
  vaultTokenAccount,
2071
+ collateralMint,
1824
2072
  yesMint,
1825
2073
  noMint,
1826
- mintAuthority,
1827
- feeRecipient,
1828
- clobAuthority: this.configPda(),
2074
+ clobAuthority: clobConfig,
1829
2075
  conditionalTokensProgram: this.programIds.conditionalTokens,
1830
2076
  collateralTokenProgram: TOKEN_PROGRAM_ID,
2077
+ token2022Program: TOKEN_2022_PROGRAM_ID,
2078
+ associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
1831
2079
  systemProgram: SystemProgram.programId
1832
2080
  }).remainingAccounts(remainingAccounts).instruction();
2081
+ await this._ensureClobOutcomeAtas(yesMint, noMint, clobConfig, clobYesAta, clobNoAta);
1833
2082
  const sig = await this.sendMatchTx([matchIx], lookupTable, operatorWallet);
1834
2083
  return { signature: sig };
1835
2084
  }
@@ -1870,38 +2119,22 @@ ${logs.join("\n")}`);
1870
2119
  buySignedOrder = taker;
1871
2120
  sellCandidates = makers;
1872
2121
  } else if (t.side === SIDE_SELL && makers.every((m) => m.order.side === SIDE_BUY)) {
1873
- buySignedOrder = makers[0];
1874
- sellCandidates = [taker, ...makers.slice(1)];
2122
+ return this.matchComplementarySellVsMultiBuy(taker, makers, collateralMint, feeRecipient, operatorWallet, alt, opts);
1875
2123
  } else {
1876
2124
  throw new InvalidParamError("COMPLEMENTARY requires one BUY and one or more SELLs on same tokenId");
1877
2125
  }
1878
- const budget = BigInt(buySignedOrder.order.makerAmount.toString());
1879
- const totalAsk = sellCandidates.reduce(
1880
- (s, m) => s + BigInt(m.order.takerAmount.toString()),
1881
- BigInt(0)
1882
- );
1883
- let finalSells;
1884
- if (budget >= totalAsk) {
1885
- finalSells = sellCandidates;
1886
- } else {
1887
- const sorted = [...sellCandidates].sort((a, b) => {
1888
- const pa = BigInt(a.order.takerAmount.toString()) * BigInt(b.order.makerAmount.toString());
1889
- const pb = BigInt(b.order.takerAmount.toString()) * BigInt(a.order.makerAmount.toString());
1890
- return pa < pb ? -1 : pa > pb ? 1 : 0;
1891
- });
1892
- finalSells = [];
1893
- let remaining = budget;
1894
- for (const s of sorted) {
1895
- const cost = BigInt(s.order.takerAmount.toString());
1896
- if (remaining >= cost) {
1897
- finalSells.push(s);
1898
- remaining -= cost;
1899
- }
1900
- }
1901
- if (finalSells.length === 0) {
1902
- throw new InvalidParamError("COMPLEMENTARY: taker budget insufficient for any maker");
1903
- }
1904
- console.warn(`[matchOrders] budget ${budget} < totalAsk ${totalAsk}: matched ${finalSells.length}/${sellCandidates.length} makers`);
2126
+ const buy = buySignedOrder.order;
2127
+ const finalSells = sellCandidates.filter((s) => {
2128
+ const sell = s.order;
2129
+ const lhs = BigInt(buy.makerAmount.toString()) * BigInt(sell.makerAmount.toString());
2130
+ const rhs = BigInt(buy.takerAmount.toString()) * BigInt(sell.takerAmount.toString());
2131
+ return lhs >= rhs;
2132
+ });
2133
+ if (finalSells.length === 0) {
2134
+ throw new InvalidParamError("COMPLEMENTARY: no maker orders cross with the buy order");
2135
+ }
2136
+ if (finalSells.length < sellCandidates.length) {
2137
+ console.warn(`[matchOrders] filtered ${sellCandidates.length - finalSells.length} non-crossing maker(s)`);
1905
2138
  }
1906
2139
  return this.matchComplementary(buySignedOrder, finalSells, collateralMint, feeRecipient, operatorWallet, alt, opts);
1907
2140
  }
@@ -1913,6 +2146,53 @@ ${logs.join("\n")}`);
1913
2146
  if (allBuy) return this.matchMintOrders(taker, makers, collateralMint, feeRecipient, operatorWallet, alt);
1914
2147
  return this.matchMergeOrders(taker, makers, collateralMint, feeRecipient, operatorWallet, alt, opts);
1915
2148
  }
2149
+ /**
2150
+ * High-level match: caller passes price + quantity + keypair — SDK builds,
2151
+ * signs, and submits in one call. No manual amount calculation needed.
2152
+ *
2153
+ * Amounts are computed from each order's own limit `price` (percentage, e.g. 51 for 51%).
2154
+ * NEVER pass averageMatchedPrice — that is an engine output, not an order input.
2155
+ *
2156
+ * @param taker { keypair, condition, tokenId, side, price, quantity, nonce?, expiry? }
2157
+ * @param makers Array of same shape
2158
+ * @param decimals Collateral decimals (default 9 for USDS)
2159
+ */
2160
+ async matchOrdersFromPrice(taker, makers, decimals = 9, opts) {
2161
+ const nacl2 = await import('tweetnacl');
2162
+ const buildSigned = (p) => {
2163
+ const order = buildOrderFromPrice({
2164
+ maker: p.keypair.publicKey,
2165
+ condition: p.condition,
2166
+ tokenId: p.tokenId,
2167
+ side: p.side,
2168
+ price: p.price,
2169
+ quantity: p.quantity,
2170
+ decimals,
2171
+ nonce: p.nonce,
2172
+ expiry: p.expiry,
2173
+ fee: p.fee,
2174
+ taker: p.taker
2175
+ });
2176
+ const msg = serializeOrderToBytes(order);
2177
+ const sig = nacl2.default.sign.detached(msg, p.keypair.secretKey);
2178
+ return { order, signature: sig };
2179
+ };
2180
+ const takerSigned = buildSigned(taker);
2181
+ const sortedMakers = [...makers].sort((a, b) => {
2182
+ const sameToken = a.tokenId === taker.tokenId && b.tokenId === taker.tokenId;
2183
+ const isDirectBuy = taker.side === 0 && sameToken;
2184
+ const isDirectSell = taker.side === 1 && sameToken;
2185
+ const isMint = taker.side === 0 && taker.tokenId === 1;
2186
+ const isMerge = taker.side === 1 && taker.tokenId === 1;
2187
+ if (isDirectBuy) return a.price - b.price;
2188
+ if (isDirectSell) return b.price - a.price;
2189
+ if (isMint) return b.price - a.price;
2190
+ if (isMerge) return a.price - b.price;
2191
+ return 0;
2192
+ });
2193
+ const makersSigned = sortedMakers.map(buildSigned);
2194
+ return this.matchOrders(takerSigned, makersSigned, opts);
2195
+ }
1916
2196
  // ─── Queries ─────────────────────────────────────────────────────────────────
1917
2197
  async fetchConfig() {
1918
2198
  try {
@@ -8552,6 +8832,10 @@ var clob_exchange_default = {
8552
8832
  {
8553
8833
  name: "fill_amount",
8554
8834
  type: "u64"
8835
+ },
8836
+ {
8837
+ name: "use_taker_price",
8838
+ type: "bool"
8555
8839
  }
8556
8840
  ]
8557
8841
  },
@@ -8604,7 +8888,8 @@ var clob_exchange_default = {
8604
8888
  }
8605
8889
  },
8606
8890
  {
8607
- name: "condition"
8891
+ name: "condition",
8892
+ writable: true
8608
8893
  },
8609
8894
  {
8610
8895
  name: "taker"
@@ -8680,27 +8965,98 @@ var clob_exchange_default = {
8680
8965
  }
8681
8966
  },
8682
8967
  {
8683
- name: "collateral_vault",
8968
+ name: "clob_usdc_ata",
8969
+ docs: [
8970
+ "USDC ATA owned by clob_config \u2014 receives USDC from vault after merge"
8971
+ ],
8972
+ writable: true,
8973
+ pda: {
8974
+ seeds: [
8975
+ {
8976
+ kind: "account",
8977
+ path: "clob_config"
8978
+ },
8979
+ {
8980
+ kind: "account",
8981
+ path: "collateral_token_program"
8982
+ },
8983
+ {
8984
+ kind: "account",
8985
+ path: "collateral_mint"
8986
+ }
8987
+ ],
8988
+ program: {
8989
+ kind: "const",
8990
+ value: [
8991
+ 140,
8992
+ 151,
8993
+ 37,
8994
+ 143,
8995
+ 78,
8996
+ 36,
8997
+ 137,
8998
+ 241,
8999
+ 187,
9000
+ 61,
9001
+ 16,
9002
+ 41,
9003
+ 20,
9004
+ 142,
9005
+ 13,
9006
+ 131,
9007
+ 11,
9008
+ 90,
9009
+ 19,
9010
+ 153,
9011
+ 218,
9012
+ 255,
9013
+ 16,
9014
+ 132,
9015
+ 4,
9016
+ 142,
9017
+ 123,
9018
+ 216,
9019
+ 219,
9020
+ 233,
9021
+ 248,
9022
+ 89
9023
+ ]
9024
+ }
9025
+ }
9026
+ },
9027
+ {
9028
+ name: "clob_yes_ata",
8684
9029
  writable: true
8685
9030
  },
8686
9031
  {
8687
- name: "vault_token_account",
9032
+ name: "clob_no_ata",
8688
9033
  writable: true
8689
9034
  },
8690
9035
  {
8691
- name: "yes_mint",
9036
+ name: "clob_yes_position",
8692
9037
  writable: true
8693
9038
  },
8694
9039
  {
8695
- name: "no_mint",
9040
+ name: "clob_no_position",
8696
9041
  writable: true
8697
9042
  },
8698
9043
  {
8699
- name: "mint_authority",
9044
+ name: "collateral_vault",
8700
9045
  writable: true
8701
9046
  },
8702
9047
  {
8703
- name: "fee_recipient",
9048
+ name: "vault_token_account",
9049
+ writable: true
9050
+ },
9051
+ {
9052
+ name: "collateral_mint"
9053
+ },
9054
+ {
9055
+ name: "yes_mint",
9056
+ writable: true
9057
+ },
9058
+ {
9059
+ name: "no_mint",
8704
9060
  writable: true
8705
9061
  },
8706
9062
  {
@@ -8734,6 +9090,14 @@ var clob_exchange_default = {
8734
9090
  name: "collateral_token_program",
8735
9091
  address: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
8736
9092
  },
9093
+ {
9094
+ name: "token_2022_program",
9095
+ address: "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"
9096
+ },
9097
+ {
9098
+ name: "associated_token_program",
9099
+ address: "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
9100
+ },
8737
9101
  {
8738
9102
  name: "system_program",
8739
9103
  address: "11111111111111111111111111111111"
@@ -8799,7 +9163,8 @@ var clob_exchange_default = {
8799
9163
  }
8800
9164
  },
8801
9165
  {
8802
- name: "condition"
9166
+ name: "condition",
9167
+ writable: true
8803
9168
  },
8804
9169
  {
8805
9170
  name: "taker"
@@ -8874,6 +9239,94 @@ var clob_exchange_default = {
8874
9239
  ]
8875
9240
  }
8876
9241
  },
9242
+ {
9243
+ name: "clob_usdc_ata",
9244
+ docs: [
9245
+ "USDC ATA owned by clob_config \u2014 receives combined USDC, then split_position pulls from here"
9246
+ ],
9247
+ writable: true,
9248
+ pda: {
9249
+ seeds: [
9250
+ {
9251
+ kind: "account",
9252
+ path: "clob_config"
9253
+ },
9254
+ {
9255
+ kind: "account",
9256
+ path: "collateral_token_program"
9257
+ },
9258
+ {
9259
+ kind: "account",
9260
+ path: "collateral_mint"
9261
+ }
9262
+ ],
9263
+ program: {
9264
+ kind: "const",
9265
+ value: [
9266
+ 140,
9267
+ 151,
9268
+ 37,
9269
+ 143,
9270
+ 78,
9271
+ 36,
9272
+ 137,
9273
+ 241,
9274
+ 187,
9275
+ 61,
9276
+ 16,
9277
+ 41,
9278
+ 20,
9279
+ 142,
9280
+ 13,
9281
+ 131,
9282
+ 11,
9283
+ 90,
9284
+ 19,
9285
+ 153,
9286
+ 218,
9287
+ 255,
9288
+ 16,
9289
+ 132,
9290
+ 4,
9291
+ 142,
9292
+ 123,
9293
+ 216,
9294
+ 219,
9295
+ 233,
9296
+ 248,
9297
+ 89
9298
+ ]
9299
+ }
9300
+ }
9301
+ },
9302
+ {
9303
+ name: "clob_yes_ata",
9304
+ docs: [
9305
+ "YES Token-2022 ATA owned by clob_config \u2014 receives YES from split, then transferred to taker"
9306
+ ],
9307
+ writable: true
9308
+ },
9309
+ {
9310
+ name: "clob_no_ata",
9311
+ docs: [
9312
+ "NO Token-2022 ATA owned by clob_config \u2014 receives NO from split, then transferred to makers"
9313
+ ],
9314
+ writable: true
9315
+ },
9316
+ {
9317
+ name: "clob_yes_position",
9318
+ docs: [
9319
+ "YES Position PDA for clob_config (set by CTF split_position init_if_needed)"
9320
+ ],
9321
+ writable: true
9322
+ },
9323
+ {
9324
+ name: "clob_no_position",
9325
+ docs: [
9326
+ "NO Position PDA for clob_config (set by CTF split_position init_if_needed)"
9327
+ ],
9328
+ writable: true
9329
+ },
8877
9330
  {
8878
9331
  name: "collateral_vault",
8879
9332
  writable: true
@@ -8882,6 +9335,9 @@ var clob_exchange_default = {
8882
9335
  name: "vault_token_account",
8883
9336
  writable: true
8884
9337
  },
9338
+ {
9339
+ name: "collateral_mint"
9340
+ },
8885
9341
  {
8886
9342
  name: "yes_mint",
8887
9343
  writable: true
@@ -8925,6 +9381,14 @@ var clob_exchange_default = {
8925
9381
  name: "collateral_token_program",
8926
9382
  address: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
8927
9383
  },
9384
+ {
9385
+ name: "token_2022_program",
9386
+ address: "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"
9387
+ },
9388
+ {
9389
+ name: "associated_token_program",
9390
+ address: "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
9391
+ },
8928
9392
  {
8929
9393
  name: "system_program",
8930
9394
  address: "11111111111111111111111111111111"
@@ -14515,91 +14979,7 @@ var XMarketSDK = class {
14515
14979
  return this._admin;
14516
14980
  }
14517
14981
  };
14518
- function buildOrder(params) {
14519
- return {
14520
- maker: params.maker,
14521
- condition: params.condition,
14522
- tokenId: params.tokenId,
14523
- side: params.side,
14524
- makerAmount: params.makerAmount,
14525
- takerAmount: params.takerAmount,
14526
- nonce: params.nonce ?? new BN5(Date.now()),
14527
- expiry: params.expiry ?? new BN5(0),
14528
- createdAt: params.createdAt ?? new BN5(Math.floor(Date.now() / 1e3)),
14529
- fee: params.fee ?? new BN5(0),
14530
- taker: params.taker ?? new PublicKey(new Uint8Array(32)),
14531
- signer: params.maker
14532
- };
14533
- }
14534
- function signOrderWithKeypair(order, keypair) {
14535
- const message = serializeOrderToBytes(order);
14536
- const signature = nacl.sign.detached(message, keypair.secretKey);
14537
- return { order, signature };
14538
- }
14539
- function getOrderSignBytes(order) {
14540
- return serializeOrderToBytes(order);
14541
- }
14542
- function serializeSignedOrder(signed) {
14543
- const orderBytes = serializeOrderToBytes(signed.order);
14544
- const buf = new Uint8Array(242);
14545
- buf.set(orderBytes, 0);
14546
- buf.set(signed.signature, 178);
14547
- return buf;
14548
- }
14549
- function deserializeSignedOrder(bytes) {
14550
- if (bytes.length !== 242) throw new InvalidParamError("SignedOrder must be 242 bytes");
14551
- const readPubkey = (offset) => new PublicKey(bytes.slice(offset, offset + 32));
14552
- const readU64 = (offset) => new BN5(bytes.slice(offset, offset + 8), "le");
14553
- const readI64 = (offset) => new BN5(bytes.slice(offset, offset + 8), "le");
14554
- const order = {
14555
- maker: readPubkey(0),
14556
- condition: readPubkey(32),
14557
- tokenId: bytes[64],
14558
- side: bytes[65],
14559
- makerAmount: readU64(66),
14560
- takerAmount: readU64(74),
14561
- nonce: readU64(82),
14562
- expiry: readI64(90),
14563
- createdAt: readI64(98),
14564
- fee: readU64(106),
14565
- taker: readPubkey(114),
14566
- signer: readPubkey(146)
14567
- };
14568
- const signature = bytes.slice(178, 242);
14569
- return { order, signature };
14570
- }
14571
- function verifySignedOrder(signed) {
14572
- const message = serializeOrderToBytes(signed.order);
14573
- return nacl.sign.detached.verify(
14574
- message,
14575
- signed.signature,
14576
- signed.order.signer.toBytes()
14577
- );
14578
- }
14579
- function detectMatchType(a, b) {
14580
- const _a = "order" in a ? a.order : a;
14581
- const _b = "order" in b ? b.order : b;
14582
- return _detectMatchType(_a, _b);
14583
- }
14584
- function _detectMatchType(a, b) {
14585
- const SIDE_BUY = 0;
14586
- if (a.tokenId === b.tokenId) {
14587
- const aBuy2 = a.side === SIDE_BUY;
14588
- const bBuy2 = b.side === SIDE_BUY;
14589
- if (aBuy2 !== bBuy2) return "COMPLEMENTARY";
14590
- throw new InvalidParamError(
14591
- "Orders with same tokenId must be one BUY and one SELL (COMPLEMENTARY)"
14592
- );
14593
- }
14594
- const aBuy = a.side === SIDE_BUY;
14595
- const bBuy = b.side === SIDE_BUY;
14596
- if (aBuy && bBuy) return "MINT";
14597
- if (!aBuy && !bBuy) return "MERGE";
14598
- throw new InvalidParamError(
14599
- "Orders with different tokenIds must both be BUY (MINT) or both SELL (MERGE)"
14600
- );
14601
- }
14602
- var MAX_APPROVE_AMOUNT = new BN5("18446744073709551615");
14982
+ var MAX_APPROVE_AMOUNT = new BN4("18446744073709551615");
14603
14983
  function buildApproveCollateralTx(collateralMint, signer, payer, delegate, amount = MAX_APPROVE_AMOUNT) {
14604
14984
  const ownerAta = getAssociatedTokenAddressSync(collateralMint, signer, false, TOKEN_PROGRAM_ID);
14605
14985
  const approveIx = createApproveInstruction(
@@ -14643,6 +15023,6 @@ function buildApproveAllOutcomeTokensTx(condition, signer, payer, delegate, prog
14643
15023
  return tx;
14644
15024
  }
14645
15025
 
14646
- export { AccountNotFoundError, AdminClient, ClobClient, CtfClient, FEE_DENOMINATOR, FeeManagementClient, HookClient, IX_SYSVAR, InvalidParamError, MAX_APPROVE_AMOUNT, MarketClient, MarketOracleClient, OracleClient, PDA, PresaleClient, QuestionStatus, SEEDS, UnauthorizedError, XMarketError, XMarketSDK, buildApproveAllOutcomeTokensTx, buildApproveCollateralTx, buildBatchedEd25519Instruction, buildOrder, deserializeSignedOrder, detectMatchType, generateContentHash, generateQuestionId, getOrderSignBytes, serializeOrderToBytes, serializeSignedOrder, signOrder, signOrderWithKeypair, verifySignedOrder };
15026
+ export { AccountNotFoundError, AdminClient, ClobClient, CtfClient, FEE_DENOMINATOR, FeeManagementClient, HookClient, IX_SYSVAR, InvalidParamError, MAX_APPROVE_AMOUNT, MarketClient, MarketOracleClient, OracleClient, PDA, PresaleClient, QuestionStatus, SEEDS, UnauthorizedError, XMarketError, XMarketSDK, buildApproveAllOutcomeTokensTx, buildApproveCollateralTx, buildBatchedEd25519Instruction, buildOrder, buildOrderFromPrice, deserializeSignedOrder, detectMatchType, generateContentHash, generateQuestionId, getOrderSignBytes, orderAmountsFromPrice, serializeOrderToBytes, serializeSignedOrder, signOrder, signOrderWithKeypair, verifySignedOrder };
14647
15027
  //# sourceMappingURL=index.mjs.map
14648
15028
  //# sourceMappingURL=index.mjs.map