@medialane/sdk 0.62.0 → 0.64.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.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { keccak_256 } from '@noble/hashes/sha3.js';
3
3
  import { base58, base32 } from '@scure/base';
4
- import { hash, num, cairo, Contract, uint256, RpcProvider, CairoOption, CairoOptionVariant, ec, encode, TypedDataRevision, shortString, constants } from 'starknet';
4
+ import { hash, Contract, cairo, uint256, RpcProvider, CairoOption, CairoOptionVariant, num, ec, encode, TypedDataRevision, constants, shortString } from 'starknet';
5
5
 
6
6
  // src/config.ts
7
7
 
@@ -35,9 +35,9 @@ var COORDINATES = {
35
35
  creatorCoinFactoryClassHash: "0x51765926b1344c9a20b8cd4b5abe7b7d47375ae97cf6804db3ea5d4b05a9b55",
36
36
  creatorCoinStartBlock: 10474544,
37
37
  ekuboCore: "0x00000005dd3d2f4429af886cd1a3b08289dbcea99a294197e9eb43b0e0325b4b",
38
- ipTicketsFactory: "0x0664c2d6a4da9ee3ff053ceeba7579c01f2fedfd9d2b57b4c07af3734bd4acab",
39
- ipTicketCollectionClassHash: "0x086f59c416e365e2bee4ceff9f1dcb96198f2342d50ba4621f60b831863adb6",
40
- ipTicketsStartBlock: 11404656,
38
+ ipTicketsFactory: "0x03ffef4162fe2c44e17d6be2aad3553cab0ac2274cd0b1bb3fafb12fd66695c1",
39
+ ipTicketCollectionClassHash: "0x036393fb4241ed55bd12d8b328ed877d08100fadf9150a650e2b84cbab95e1d4",
40
+ ipTicketsStartBlock: 11689800,
41
41
  ipClubRegistry: "0x00e189c619b6bb07d78973a149641c59c37eb0716f8584d7520bce12d303eede",
42
42
  ipClubNftClassHash: "0x02bc9b20cca21b04245e9215bf7121f4d7295b195890e449b472b573017fb889",
43
43
  ipClubStartBlock: 11404776,
@@ -1294,124 +1294,6 @@ function createFailoverFetch(urls, options = {}) {
1294
1294
  };
1295
1295
  return failover;
1296
1296
  }
1297
- var STARKNET_DOMAIN = [
1298
- { name: "name", type: "shortstring" },
1299
- { name: "version", type: "shortstring" },
1300
- { name: "chainId", type: "shortstring" },
1301
- { name: "revision", type: "shortstring" }
1302
- ];
1303
- var OFFER_ITEM = [
1304
- { name: "item_type", type: "shortstring" },
1305
- { name: "token", type: "ContractAddress" },
1306
- { name: "identifier_or_criteria", type: "felt" },
1307
- { name: "amount", type: "felt" }
1308
- ];
1309
- var CONSIDERATION_ITEM = [
1310
- { name: "item_type", type: "shortstring" },
1311
- { name: "token", type: "ContractAddress" },
1312
- { name: "identifier_or_criteria", type: "felt" },
1313
- { name: "amount", type: "felt" },
1314
- { name: "recipient", type: "ContractAddress" }
1315
- ];
1316
- var ORDER_PARAMETERS = [
1317
- { name: "offerer", type: "ContractAddress" },
1318
- { name: "marketplace", type: "ContractAddress" },
1319
- { name: "offer", type: "OfferItem" },
1320
- { name: "consideration", type: "ConsiderationItem" },
1321
- { name: "royalty_max_bps", type: "felt" },
1322
- { name: "start_time", type: "felt" },
1323
- { name: "end_time", type: "felt" },
1324
- { name: "salt", type: "felt" },
1325
- { name: "counter", type: "felt" }
1326
- ];
1327
- var ORDER_CANCELLATION = [
1328
- { name: "order_hash", type: "felt" },
1329
- { name: "offerer", type: "ContractAddress" }
1330
- ];
1331
- var DOMAIN_VERSION = {
1332
- erc721: "5",
1333
- erc1155: "4"
1334
- };
1335
- function buildDomain(standard, chainId) {
1336
- return {
1337
- name: "Medialane",
1338
- version: DOMAIN_VERSION[standard],
1339
- chainId,
1340
- revision: TypedDataRevision.ACTIVE
1341
- };
1342
- }
1343
- function buildOrderTypedData(message, chainId) {
1344
- return {
1345
- domain: buildDomain("erc721", chainId),
1346
- primaryType: "OrderParameters",
1347
- types: {
1348
- StarknetDomain: STARKNET_DOMAIN,
1349
- OrderParameters: ORDER_PARAMETERS,
1350
- OfferItem: OFFER_ITEM,
1351
- ConsiderationItem: CONSIDERATION_ITEM
1352
- },
1353
- message
1354
- };
1355
- }
1356
- function build1155OrderTypedData(message, chainId) {
1357
- return {
1358
- domain: buildDomain("erc1155", chainId),
1359
- primaryType: "OrderParameters",
1360
- types: {
1361
- StarknetDomain: STARKNET_DOMAIN,
1362
- OrderParameters: ORDER_PARAMETERS,
1363
- OfferItem: OFFER_ITEM,
1364
- ConsiderationItem: CONSIDERATION_ITEM
1365
- },
1366
- message
1367
- };
1368
- }
1369
- function buildCancellationTypedData(message, chainId) {
1370
- return {
1371
- domain: buildDomain("erc721", chainId),
1372
- primaryType: "OrderCancellation",
1373
- types: {
1374
- StarknetDomain: STARKNET_DOMAIN,
1375
- OrderCancellation: ORDER_CANCELLATION
1376
- },
1377
- message
1378
- };
1379
- }
1380
- function build1155CancellationTypedData(message, chainId) {
1381
- return {
1382
- domain: buildDomain("erc1155", chainId),
1383
- primaryType: "OrderCancellation",
1384
- types: {
1385
- StarknetDomain: STARKNET_DOMAIN,
1386
- OrderCancellation: ORDER_CANCELLATION
1387
- },
1388
- message
1389
- };
1390
- }
1391
- function encodeByteArray(str) {
1392
- const bytes = new TextEncoder().encode(str);
1393
- const fullChunks = [];
1394
- let i = 0;
1395
- while (i + 31 <= bytes.length) {
1396
- let val = 0n;
1397
- for (const b of bytes.slice(i, i + 31)) {
1398
- val = val << 8n | BigInt(b);
1399
- }
1400
- fullChunks.push(num.toHex(val));
1401
- i += 31;
1402
- }
1403
- const remaining = bytes.slice(i);
1404
- let pendingVal = 0n;
1405
- for (const b of remaining) {
1406
- pendingVal = pendingVal << 8n | BigInt(b);
1407
- }
1408
- return [
1409
- fullChunks.length.toString(),
1410
- ...fullChunks,
1411
- num.toHex(pendingVal),
1412
- remaining.length.toString()
1413
- ];
1414
- }
1415
1297
 
1416
1298
  // src/starknet/abis/ipMarketplace.ts
1417
1299
  var IPMarketplaceABI = [
@@ -11442,13 +11324,71 @@ var IPGenesisABI = [
11442
11324
  }
11443
11325
  ];
11444
11326
 
11445
- // src/starknet/marketplace/errors.ts
11446
- var MedialaneError = class extends Error {
11447
- constructor(message, code = "UNKNOWN", cause) {
11448
- super(message);
11449
- this.code = code;
11450
- this.cause = cause;
11451
- this.name = "MedialaneError";
11327
+ // src/starknet/services/pop.ts
11328
+ var PopService = class {
11329
+ constructor(config) {
11330
+ this.factoryAddress = getStarknetCoordinates(config.chain).popFactory;
11331
+ }
11332
+ _collection(address, account) {
11333
+ return new Contract(POPCollectionABI, normalizeAddress("STARKNET", address), account);
11334
+ }
11335
+ async claim(account, collectionAddress) {
11336
+ const call = this._collection(collectionAddress, account).populate("claim", []);
11337
+ const res = await account.execute([call]);
11338
+ return { txHash: res.transaction_hash };
11339
+ }
11340
+ async adminMint(account, params) {
11341
+ const call = this._collection(params.collection, account).populate("admin_mint", [
11342
+ params.recipient,
11343
+ params.customUri ?? ""
11344
+ ]);
11345
+ const res = await account.execute([call]);
11346
+ return { txHash: res.transaction_hash };
11347
+ }
11348
+ async addToAllowlist(account, params) {
11349
+ const call = this._collection(params.collection, account).populate("add_to_allowlist", [params.address]);
11350
+ const res = await account.execute([call]);
11351
+ return { txHash: res.transaction_hash };
11352
+ }
11353
+ async batchAddToAllowlist(account, params) {
11354
+ const collection = this._collection(params.collection, account);
11355
+ const CHUNK = 200;
11356
+ const calls = [];
11357
+ for (let i = 0; i < params.addresses.length; i += CHUNK) {
11358
+ calls.push(collection.populate("batch_add_to_allowlist", [params.addresses.slice(i, i + CHUNK)]));
11359
+ }
11360
+ const res = await account.execute(calls);
11361
+ return { txHash: res.transaction_hash };
11362
+ }
11363
+ async removeFromAllowlist(account, params) {
11364
+ const call = this._collection(params.collection, account).populate("remove_from_allowlist", [params.address]);
11365
+ const res = await account.execute([call]);
11366
+ return { txHash: res.transaction_hash };
11367
+ }
11368
+ async setTokenUri(account, params) {
11369
+ const call = this._collection(params.collection, account).populate("set_token_uri", [
11370
+ BigInt(params.tokenId),
11371
+ params.uri
11372
+ ]);
11373
+ const res = await account.execute([call]);
11374
+ return { txHash: res.transaction_hash };
11375
+ }
11376
+ async setPaused(account, params) {
11377
+ const call = this._collection(params.collection, account).populate("set_paused", [params.paused]);
11378
+ const res = await account.execute([call]);
11379
+ return { txHash: res.transaction_hash };
11380
+ }
11381
+ async createCollection(account, params) {
11382
+ const factory = new Contract(POPFactoryABI, this.factoryAddress, account);
11383
+ const call = factory.populate("create_collection", [
11384
+ params.name,
11385
+ params.symbol,
11386
+ params.baseUri,
11387
+ params.claimEndTime,
11388
+ { [params.eventType]: {} }
11389
+ ]);
11390
+ const res = await account.execute([call]);
11391
+ return { txHash: res.transaction_hash };
11452
11392
  }
11453
11393
  };
11454
11394
  function buildFeeCall(p, cfg) {
@@ -11464,856 +11404,39 @@ function buildFeeCall(p, cfg) {
11464
11404
  calldata: [cfg.fundAddress, u.low.toString(), u.high.toString()]
11465
11405
  };
11466
11406
  }
11467
- var START_TIME_BUFFER_SECS = 30;
11468
- function generateSalt() {
11469
- const bytes = new Uint8Array(31);
11470
- crypto.getRandomValues(bytes);
11471
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
11472
- return num.toHex(BigInt("0x" + hex));
11407
+
11408
+ // src/starknet/services/drop.ts
11409
+ function toContractConditions(c) {
11410
+ return {
11411
+ start_time: c.startTime,
11412
+ end_time: c.endTime,
11413
+ price: BigInt(c.price),
11414
+ payment_token: c.paymentToken,
11415
+ max_quantity_per_wallet: BigInt(c.maxQuantityPerWallet)
11416
+ };
11473
11417
  }
11474
- async function resolveRoyaltyMaxBps(provider, nft, tokenId, override) {
11475
- if (override !== void 0) return override;
11476
- try {
11477
- const id = cairo.uint256(tokenId);
11478
- const res = await provider.callContract({
11479
- contractAddress: nft,
11480
- entrypoint: "royalty_info",
11481
- calldata: [id.low.toString(), id.high.toString(), "10000", "0"]
11482
- });
11483
- return BigInt(res[1] ?? "0").toString();
11484
- } catch {
11485
- return "0";
11418
+ var DropService = class {
11419
+ constructor(config) {
11420
+ this.factoryAddress = getStarknetCoordinates(config.chain).dropFactory;
11421
+ this.config = config;
11486
11422
  }
11487
- }
11488
- function toSignatureArray(sig) {
11489
- if (Array.isArray(sig)) return sig;
11490
- const s = sig;
11491
- return [s.r.toString(), s.s.toString()];
11492
- }
11493
- function getChainId(config) {
11494
- if (config.chain !== "STARKNET") {
11495
- throw new Error(`SNIP-12 signing is Starknet-only; got chain "${config.chain}"`);
11423
+ _collection(address, account) {
11424
+ return new Contract(DropCollectionABI, normalizeAddress("STARKNET", address), account);
11496
11425
  }
11497
- return constants.StarknetChainId.SN_MAIN;
11498
- }
11499
- function resolveToken(currency) {
11500
- const token = SUPPORTED_TOKENS.find(
11501
- (t) => t.symbol === currency.toUpperCase() || t.address.toLowerCase() === currency.toLowerCase()
11502
- );
11503
- if (!token) throw new MedialaneError(`Unsupported currency: ${currency}`, "INVALID_PARAMS");
11504
- return token;
11505
- }
11506
- var _providerCache = /* @__PURE__ */ new WeakMap();
11507
- function getProvider(config) {
11508
- let p = _providerCache.get(config);
11509
- if (!p) {
11510
- const urls = Array.from(/* @__PURE__ */ new Set([config.rpcUrl, ...PUBLIC_RPC_FALLBACKS]));
11511
- p = new RpcProvider({ nodeUrl: urls[0], baseFetch: createFailoverFetch(urls) });
11512
- _providerCache.set(config, p);
11513
- }
11514
- return p;
11515
- }
11516
-
11517
- // src/starknet/marketplace/orders.ts
11518
- var _contractCache = /* @__PURE__ */ new WeakMap();
11519
- function makeContract(config) {
11520
- const cached = _contractCache.get(config);
11521
- const provider = getProvider(config);
11522
- if (cached) return { ...cached, provider };
11523
- const contract = new Contract(
11524
- IPMarketplaceABI,
11525
- config.marketplaceContract,
11526
- provider
11527
- );
11528
- _contractCache.set(config, { contract });
11529
- return { contract, provider };
11530
- }
11531
- async function createListing(account, params, config) {
11532
- const { nftContract, tokenId, price, currency = DEFAULT_CURRENCY, durationSeconds } = params;
11533
- const { contract, provider } = makeContract(config);
11534
- const token = resolveToken(currency);
11535
- const priceWei = parseAmount(price, token.decimals);
11536
- const now = Math.floor(Date.now() / 1e3);
11537
- const startTime = now + START_TIME_BUFFER_SECS;
11538
- const endTime = now + durationSeconds;
11539
- const counter = (await contract.get_counter(account.address)).toString();
11540
- const royaltyMaxBps = await resolveRoyaltyMaxBps(provider, nftContract, tokenId, params.royaltyMaxBps);
11541
- const orderParams = {
11542
- offerer: account.address,
11543
- marketplace: config.marketplaceContract,
11544
- offer: {
11545
- item_type: "ERC721",
11546
- token: nftContract,
11547
- identifier_or_criteria: tokenId,
11548
- amount: "1"
11549
- },
11550
- consideration: {
11551
- item_type: "ERC20",
11552
- token: token.address,
11553
- identifier_or_criteria: "0",
11554
- amount: priceWei,
11555
- recipient: account.address
11556
- },
11557
- royalty_max_bps: royaltyMaxBps,
11558
- start_time: startTime.toString(),
11559
- end_time: endTime.toString(),
11560
- salt: generateSalt(),
11561
- counter
11562
- };
11563
- const chainId = getChainId(config);
11564
- const typedData = stringifyBigInts(buildOrderTypedData(orderParams, chainId));
11565
- const signature = await account.signMessage(typedData);
11566
- const signatureArray = toSignatureArray(signature);
11567
- const registerPayload = stringifyBigInts({
11568
- parameters: {
11569
- ...orderParams,
11570
- offer: {
11571
- ...orderParams.offer,
11572
- item_type: shortString.encodeShortString(orderParams.offer.item_type)
11573
- },
11574
- consideration: {
11575
- ...orderParams.consideration,
11576
- item_type: shortString.encodeShortString(orderParams.consideration.item_type)
11577
- }
11578
- },
11579
- signature: signatureArray
11580
- });
11581
- const tokenIdUint256 = cairo.uint256(tokenId);
11582
- let isAlreadyApproved = false;
11583
- try {
11584
- const result = await provider.callContract({
11585
- contractAddress: nftContract,
11586
- entrypoint: "get_approved",
11587
- calldata: [tokenIdUint256.low.toString(), tokenIdUint256.high.toString()]
11588
- });
11589
- isAlreadyApproved = BigInt(result[0]).toString() === BigInt(config.marketplaceContract).toString();
11590
- } catch {
11591
- }
11592
- const registerCall = contract.populate("register_order", [registerPayload]);
11593
- const calls = isAlreadyApproved ? [registerCall] : [
11594
- {
11595
- contractAddress: nftContract,
11596
- entrypoint: "approve",
11597
- calldata: [
11598
- config.marketplaceContract,
11599
- tokenIdUint256.low.toString(),
11600
- tokenIdUint256.high.toString()
11601
- ]
11602
- },
11603
- registerCall
11604
- ];
11605
- try {
11606
- const tx = await account.execute(calls);
11607
- await provider.waitForTransaction(tx.transaction_hash);
11608
- return { txHash: tx.transaction_hash };
11609
- } catch (err) {
11610
- throw new MedialaneError("Failed to create listing", "TRANSACTION_FAILED", err);
11611
- }
11612
- }
11613
- async function makeOffer(account, params, config) {
11614
- const { nftContract, tokenId, price, currency = DEFAULT_CURRENCY, durationSeconds } = params;
11615
- const { contract, provider } = makeContract(config);
11616
- const token = resolveToken(currency);
11617
- const priceWei = parseAmount(price, token.decimals);
11618
- const now = Math.floor(Date.now() / 1e3);
11619
- const startTime = now + START_TIME_BUFFER_SECS;
11620
- const endTime = now + durationSeconds;
11621
- const counter = (await contract.get_counter(account.address)).toString();
11622
- const royaltyMaxBps = await resolveRoyaltyMaxBps(provider, nftContract, tokenId, params.royaltyMaxBps);
11623
- const orderParams = {
11624
- offerer: account.address,
11625
- marketplace: config.marketplaceContract,
11626
- offer: {
11627
- item_type: "ERC20",
11628
- token: token.address,
11629
- identifier_or_criteria: "0",
11630
- amount: priceWei
11631
- },
11632
- consideration: {
11633
- item_type: "ERC721",
11634
- token: nftContract,
11635
- identifier_or_criteria: tokenId,
11636
- amount: "1",
11637
- recipient: account.address
11638
- },
11639
- royalty_max_bps: royaltyMaxBps,
11640
- start_time: startTime.toString(),
11641
- end_time: endTime.toString(),
11642
- salt: generateSalt(),
11643
- counter
11644
- };
11645
- const chainId = getChainId(config);
11646
- const typedData = stringifyBigInts(buildOrderTypedData(orderParams, chainId));
11647
- const signature = await account.signMessage(typedData);
11648
- const signatureArray = toSignatureArray(signature);
11649
- const registerPayload = stringifyBigInts({
11650
- parameters: {
11651
- ...orderParams,
11652
- offer: {
11653
- ...orderParams.offer,
11654
- item_type: shortString.encodeShortString(orderParams.offer.item_type)
11655
- },
11656
- consideration: {
11657
- ...orderParams.consideration,
11658
- item_type: shortString.encodeShortString(orderParams.consideration.item_type)
11659
- }
11660
- },
11661
- signature: signatureArray
11662
- });
11663
- const amountUint256 = cairo.uint256(priceWei);
11664
- const approveCall = {
11665
- contractAddress: token.address,
11666
- entrypoint: "approve",
11667
- calldata: [
11668
- config.marketplaceContract,
11669
- amountUint256.low.toString(),
11670
- amountUint256.high.toString()
11671
- ]
11672
- };
11673
- const registerCall = contract.populate("register_order", [registerPayload]);
11674
- try {
11675
- const tx = await account.execute([approveCall, registerCall]);
11676
- await provider.waitForTransaction(tx.transaction_hash);
11677
- return { txHash: tx.transaction_hash };
11678
- } catch (err) {
11679
- throw new MedialaneError("Failed to make offer", "TRANSACTION_FAILED", err);
11680
- }
11681
- }
11682
- async function fulfillOrder(account, params, config) {
11683
- const { orderHash, paymentToken, totalPrice } = params;
11684
- const { contract, provider } = makeContract(config);
11685
- const totalPriceU256 = cairo.uint256(totalPrice);
11686
- const approveCall = {
11687
- contractAddress: paymentToken,
11688
- entrypoint: "approve",
11689
- calldata: [
11690
- config.marketplaceContract,
11691
- totalPriceU256.low.toString(),
11692
- totalPriceU256.high.toString()
11693
- ]
11694
- };
11695
- const fulfillCall = contract.populate("fulfill_order", [orderHash]);
11696
- const feeCall = buildFeeCall(
11697
- { surface: "marketplace", token: paymentToken, grossAmount: BigInt(totalPrice) },
11698
- config.feeConfig
11699
- );
11700
- const calls = feeCall ? [approveCall, fulfillCall, feeCall] : [approveCall, fulfillCall];
11701
- try {
11702
- const tx = await account.execute(calls);
11703
- await provider.waitForTransaction(tx.transaction_hash);
11704
- return { txHash: tx.transaction_hash };
11705
- } catch (err) {
11706
- throw new MedialaneError("Failed to fulfill order", "TRANSACTION_FAILED", err);
11707
- }
11708
- }
11709
- async function cancelOrder(account, params, config) {
11710
- const { orderHash } = params;
11711
- const { contract, provider } = makeContract(config);
11712
- const chainId = getChainId(config);
11713
- const cancelParams = {
11714
- order_hash: orderHash,
11715
- offerer: account.address
11716
- };
11717
- const typedData = stringifyBigInts(
11718
- buildCancellationTypedData(cancelParams, chainId)
11719
- );
11720
- const signature = await account.signMessage(typedData);
11721
- const signatureArray = toSignatureArray(signature);
11722
- const cancelRequest = stringifyBigInts({
11723
- cancelation: cancelParams,
11724
- signature: signatureArray
11725
- });
11726
- const call = contract.populate("cancel_order", [cancelRequest]);
11727
- try {
11728
- const tx = await account.execute(call);
11729
- await provider.waitForTransaction(tx.transaction_hash);
11730
- return { txHash: tx.transaction_hash };
11731
- } catch (err) {
11732
- throw new MedialaneError("Failed to cancel order", "TRANSACTION_FAILED", err);
11733
- }
11734
- }
11735
- async function mint(account, params, config) {
11736
- const { collectionId, recipient, tokenUri, royaltyBps, collectionContract } = params;
11737
- const provider = getProvider(config);
11738
- const contractAddress = collectionContract ?? config.collectionContract;
11739
- const id = cairo.uint256(collectionId);
11740
- const calldata = [
11741
- id.low.toString(),
11742
- id.high.toString(),
11743
- recipient,
11744
- ...encodeByteArray(tokenUri),
11745
- royaltyBps.toString()
11746
- ];
11747
- try {
11748
- const tx = await account.execute([{ contractAddress, entrypoint: "mint", calldata }]);
11749
- await provider.waitForTransaction(tx.transaction_hash);
11750
- return { txHash: tx.transaction_hash };
11751
- } catch (err) {
11752
- throw new MedialaneError("Failed to mint NFT", "TRANSACTION_FAILED", err);
11753
- }
11754
- }
11755
- async function createCollection(account, params, config) {
11756
- const { name, symbol, baseUri, collectionContract } = params;
11757
- const provider = getProvider(config);
11758
- const contractAddress = collectionContract ?? config.collectionContract;
11759
- const calldata = [
11760
- ...encodeByteArray(name),
11761
- ...encodeByteArray(symbol),
11762
- ...encodeByteArray(baseUri)
11763
- ];
11764
- try {
11765
- const tx = await account.execute([{ contractAddress, entrypoint: "create_collection", calldata }]);
11766
- await provider.waitForTransaction(tx.transaction_hash);
11767
- return { txHash: tx.transaction_hash };
11768
- } catch (err) {
11769
- throw new MedialaneError("Failed to create collection", "TRANSACTION_FAILED", err);
11770
- }
11771
- }
11772
- async function checkoutCart(account, items, config) {
11773
- if (items.length === 0) throw new MedialaneError("Cart is empty", "INVALID_PARAMS");
11774
- const { contract, provider } = makeContract(config);
11775
- const tokenTotals = /* @__PURE__ */ new Map();
11776
- for (const item of items) {
11777
- const prev = tokenTotals.get(item.considerationToken) ?? 0n;
11778
- tokenTotals.set(item.considerationToken, prev + BigInt(item.considerationAmount));
11779
- }
11780
- const approveCalls = Array.from(tokenTotals.entries()).map(([tokenAddr, totalWei]) => {
11781
- const amount = cairo.uint256(totalWei.toString());
11782
- return {
11783
- contractAddress: tokenAddr,
11784
- entrypoint: "approve",
11785
- calldata: [
11786
- config.marketplaceContract,
11787
- amount.low.toString(),
11788
- amount.high.toString()
11789
- ]
11790
- };
11791
- });
11792
- const fulfillCalls = items.map(
11793
- (item) => contract.populate("fulfill_order", [item.orderHash])
11794
- );
11795
- const feeCalls = Array.from(tokenTotals.entries()).map(
11796
- ([tokenAddr, totalWei]) => buildFeeCall(
11797
- { surface: "marketplace", token: tokenAddr, grossAmount: totalWei },
11798
- config.feeConfig
11799
- )
11800
- ).filter((c) => c !== null);
11801
- try {
11802
- const tx = await account.execute([...approveCalls, ...fulfillCalls, ...feeCalls]);
11803
- await provider.waitForTransaction(tx.transaction_hash);
11804
- return { txHash: tx.transaction_hash };
11805
- } catch (err) {
11806
- throw new MedialaneError("Cart checkout failed", "TRANSACTION_FAILED", err);
11807
- }
11808
- }
11809
- async function getOrderDetails(orderHash, config) {
11810
- const { contract } = makeContract(config);
11811
- return contract.get_order_details(orderHash);
11812
- }
11813
- async function getCounter(address, config) {
11814
- const { contract } = makeContract(config);
11815
- return BigInt((await contract.get_counter(address)).toString());
11816
- }
11817
- async function incrementCounter(account, config) {
11818
- const { contract, provider } = makeContract(config);
11819
- const call = contract.populate("increment_counter", []);
11820
- try {
11821
- const tx = await account.execute(call);
11822
- await provider.waitForTransaction(tx.transaction_hash);
11823
- return { txHash: tx.transaction_hash };
11824
- } catch (err) {
11825
- throw new MedialaneError("Failed to increment counter", "TRANSACTION_FAILED", err);
11826
- }
11827
- }
11828
-
11829
- // src/starknet/marketplace/index.ts
11830
- var MarketplaceModule = class {
11831
- constructor(config) {
11832
- this.config = config;
11833
- }
11834
- // ─── Writes ───────────────────────────────────────────────────────────────
11835
- createListing(account, params) {
11836
- return createListing(account, params, this.config);
11837
- }
11838
- makeOffer(account, params) {
11839
- return makeOffer(account, params, this.config);
11840
- }
11841
- fulfillOrder(account, params) {
11842
- return fulfillOrder(account, params, this.config);
11843
- }
11844
- cancelOrder(account, params) {
11845
- return cancelOrder(account, params, this.config);
11846
- }
11847
- checkoutCart(account, items) {
11848
- return checkoutCart(account, items, this.config);
11849
- }
11850
- mint(account, params) {
11851
- return mint(account, params, this.config);
11852
- }
11853
- createCollection(account, params) {
11854
- return createCollection(account, params, this.config);
11855
- }
11856
- /** Bulk-cancel: bump the caller's counter, invalidating all their open orders. */
11857
- incrementCounter(account) {
11858
- return incrementCounter(account, this.config);
11859
- }
11860
- // ─── View calls ───────────────────────────────────────────────────────────
11861
- getOrderDetails(orderHash) {
11862
- return getOrderDetails(orderHash, this.config);
11863
- }
11864
- getCounter(address) {
11865
- return getCounter(address, this.config);
11866
- }
11867
- // ─── Typed data builders (for ChipiPay / custom signing flows) ───────────
11868
- buildListingTypedData(params, chainId) {
11869
- return buildOrderTypedData(params, chainId);
11870
- }
11871
- buildCancellationTypedData(params, chainId) {
11872
- return buildCancellationTypedData(params, chainId);
11873
- }
11874
- };
11875
- var _contractCache2 = /* @__PURE__ */ new WeakMap();
11876
- function getContract(config) {
11877
- let c = _contractCache2.get(config);
11878
- if (!c) {
11879
- const provider = getProvider(config);
11880
- c = new Contract(
11881
- Medialane1155ABI,
11882
- config.marketplace1155Contract,
11883
- provider
11884
- );
11885
- _contractCache2.set(config, c);
11886
- }
11887
- return c;
11888
- }
11889
- async function createListing1155(account, params, config) {
11890
- const {
11891
- nftContract,
11892
- tokenId,
11893
- amount,
11894
- pricePerUnit,
11895
- currency = DEFAULT_CURRENCY,
11896
- durationSeconds
11897
- } = params;
11898
- const contract = getContract(config);
11899
- const provider = getProvider(config);
11900
- const token = resolveToken(currency);
11901
- const priceWei = parseAmount(pricePerUnit, token.decimals);
11902
- const now = Math.floor(Date.now() / 1e3);
11903
- const endTime = now + durationSeconds;
11904
- const chainId = getChainId(config);
11905
- const counter = (await contract.get_counter(account.address)).toString();
11906
- const royaltyMaxBps = await resolveRoyaltyMaxBps(provider, nftContract, tokenId, params.royaltyMaxBps);
11907
- const orderParams = {
11908
- offerer: account.address,
11909
- marketplace: config.marketplace1155Contract,
11910
- offer: {
11911
- item_type: "ERC1155",
11912
- token: nftContract,
11913
- identifier_or_criteria: tokenId,
11914
- amount
11915
- // ERC-1155 leg amount = unit quantity
11916
- },
11917
- consideration: {
11918
- item_type: "ERC20",
11919
- token: token.address,
11920
- identifier_or_criteria: "0",
11921
- amount: priceWei,
11922
- // payment leg amount = price PER UNIT
11923
- recipient: account.address
11924
- },
11925
- royalty_max_bps: royaltyMaxBps,
11926
- start_time: (now + START_TIME_BUFFER_SECS).toString(),
11927
- end_time: endTime.toString(),
11928
- salt: generateSalt(),
11929
- counter
11930
- };
11931
- const typedData = stringifyBigInts(
11932
- build1155OrderTypedData(orderParams, chainId)
11933
- );
11934
- const signature = await account.signMessage(typedData);
11935
- const signatureArray = toSignatureArray(signature);
11936
- const orderPayload = stringifyBigInts({
11937
- parameters: {
11938
- ...orderParams,
11939
- offer: {
11940
- ...orderParams.offer,
11941
- item_type: shortString.encodeShortString(orderParams.offer.item_type)
11942
- },
11943
- consideration: {
11944
- ...orderParams.consideration,
11945
- item_type: shortString.encodeShortString(orderParams.consideration.item_type)
11946
- }
11947
- },
11948
- signature: signatureArray
11949
- });
11950
- let isApproved = false;
11951
- try {
11952
- const result = await provider.callContract({
11953
- contractAddress: nftContract,
11954
- entrypoint: "is_approved_for_all",
11955
- calldata: [account.address, config.marketplace1155Contract]
11956
- });
11957
- isApproved = BigInt(result[0]) === 1n;
11958
- } catch {
11959
- }
11960
- const registerCall = contract.populate("register_order", [orderPayload]);
11961
- const calls = isApproved ? [registerCall] : [
11962
- {
11963
- contractAddress: nftContract,
11964
- entrypoint: "set_approval_for_all",
11965
- calldata: [config.marketplace1155Contract, "1"]
11966
- },
11967
- registerCall
11968
- ];
11969
- try {
11970
- const tx = await account.execute(calls);
11971
- await provider.waitForTransaction(tx.transaction_hash);
11972
- return { txHash: tx.transaction_hash };
11973
- } catch (err) {
11974
- throw new MedialaneError("Failed to create ERC-1155 listing", "TRANSACTION_FAILED", err);
11975
- }
11976
- }
11977
- async function fulfillOrder1155(account, params, config) {
11978
- const { orderHash, paymentToken, totalPrice, quantity = "1" } = params;
11979
- const contract = getContract(config);
11980
- const provider = getProvider(config);
11981
- const totalPriceU256 = cairo.uint256(totalPrice);
11982
- const approveCall = {
11983
- contractAddress: paymentToken,
11984
- entrypoint: "approve",
11985
- calldata: [
11986
- config.marketplace1155Contract,
11987
- totalPriceU256.low.toString(),
11988
- totalPriceU256.high.toString()
11989
- ]
11990
- };
11991
- const fulfillCall = contract.populate("fulfill_order", [orderHash, quantity]);
11992
- try {
11993
- const tx = await account.execute([approveCall, fulfillCall]);
11994
- await provider.waitForTransaction(tx.transaction_hash);
11995
- return { txHash: tx.transaction_hash };
11996
- } catch (err) {
11997
- throw new MedialaneError("Failed to fulfill ERC-1155 order", "TRANSACTION_FAILED", err);
11998
- }
11999
- }
12000
- async function cancelOrder1155(account, params, config) {
12001
- const { orderHash } = params;
12002
- const contract = getContract(config);
12003
- const provider = getProvider(config);
12004
- const chainId = getChainId(config);
12005
- const cancelParams = {
12006
- order_hash: orderHash,
12007
- offerer: account.address
12008
- };
12009
- const typedData = stringifyBigInts(
12010
- build1155CancellationTypedData(cancelParams, chainId)
12011
- );
12012
- const signature = await account.signMessage(typedData);
12013
- const signatureArray = toSignatureArray(signature);
12014
- const cancelPayload = stringifyBigInts({
12015
- cancelation: cancelParams,
12016
- signature: signatureArray
12017
- });
12018
- const cancelCall = contract.populate("cancel_order", [cancelPayload]);
12019
- try {
12020
- const tx = await account.execute(cancelCall);
12021
- await provider.waitForTransaction(tx.transaction_hash);
12022
- return { txHash: tx.transaction_hash };
12023
- } catch (err) {
12024
- throw new MedialaneError("Failed to cancel ERC-1155 order", "TRANSACTION_FAILED", err);
12025
- }
12026
- }
12027
- async function makeOffer1155(account, params, config) {
12028
- const {
12029
- nftContract,
12030
- tokenId,
12031
- amount,
12032
- price,
12033
- currency = DEFAULT_CURRENCY,
12034
- durationSeconds
12035
- } = params;
12036
- const contract = getContract(config);
12037
- const provider = getProvider(config);
12038
- const chainId = getChainId(config);
12039
- const token = resolveToken(currency);
12040
- const priceWei = parseAmount(price, token.decimals);
12041
- const now = Math.floor(Date.now() / 1e3);
12042
- const endTime = now + durationSeconds;
12043
- const counter = (await contract.get_counter(account.address)).toString();
12044
- const royaltyMaxBps = await resolveRoyaltyMaxBps(provider, nftContract, tokenId, params.royaltyMaxBps);
12045
- const orderParams = {
12046
- offerer: account.address,
12047
- marketplace: config.marketplace1155Contract,
12048
- offer: {
12049
- item_type: "ERC20",
12050
- token: token.address,
12051
- identifier_or_criteria: "0",
12052
- amount: priceWei
12053
- // price PER UNIT
12054
- },
12055
- consideration: {
12056
- item_type: "ERC1155",
12057
- token: nftContract,
12058
- identifier_or_criteria: tokenId,
12059
- amount,
12060
- // unit quantity
12061
- recipient: account.address
12062
- },
12063
- royalty_max_bps: royaltyMaxBps,
12064
- start_time: (now + START_TIME_BUFFER_SECS).toString(),
12065
- end_time: endTime.toString(),
12066
- salt: generateSalt(),
12067
- counter
12068
- };
12069
- const typedData = stringifyBigInts(
12070
- build1155OrderTypedData(orderParams, chainId)
12071
- );
12072
- const signature = await account.signMessage(typedData);
12073
- const signatureArray = toSignatureArray(signature);
12074
- const registerPayload = stringifyBigInts({
12075
- parameters: {
12076
- ...orderParams,
12077
- offer: {
12078
- ...orderParams.offer,
12079
- item_type: shortString.encodeShortString(orderParams.offer.item_type)
12080
- },
12081
- consideration: {
12082
- ...orderParams.consideration,
12083
- item_type: shortString.encodeShortString(orderParams.consideration.item_type)
12084
- }
12085
- },
12086
- signature: signatureArray
12087
- });
12088
- const totalWei = BigInt(priceWei) * BigInt(amount);
12089
- const amountU256 = cairo.uint256(totalWei.toString());
12090
- const approveCall = {
12091
- contractAddress: token.address,
12092
- entrypoint: "approve",
12093
- calldata: [
12094
- config.marketplace1155Contract,
12095
- amountU256.low.toString(),
12096
- amountU256.high.toString()
12097
- ]
12098
- };
12099
- const registerCall = contract.populate("register_order", [registerPayload]);
12100
- try {
12101
- const tx = await account.execute([approveCall, registerCall]);
12102
- await provider.waitForTransaction(tx.transaction_hash);
12103
- return { txHash: tx.transaction_hash };
12104
- } catch (err) {
12105
- throw new MedialaneError("Failed to make ERC-1155 offer", "TRANSACTION_FAILED", err);
12106
- }
12107
- }
12108
- async function checkoutCart1155(account, items, config) {
12109
- if (items.length === 0) throw new MedialaneError("Cart is empty", "INVALID_PARAMS");
12110
- const contract = getContract(config);
12111
- const provider = getProvider(config);
12112
- const tokenTotals = /* @__PURE__ */ new Map();
12113
- for (const item of items) {
12114
- const prev = tokenTotals.get(item.considerationToken) ?? 0n;
12115
- tokenTotals.set(item.considerationToken, prev + BigInt(item.considerationAmount));
12116
- }
12117
- const approveCalls = Array.from(tokenTotals.entries()).map(([tokenAddr, totalWei]) => {
12118
- const amount = cairo.uint256(totalWei.toString());
12119
- return {
12120
- contractAddress: tokenAddr,
12121
- entrypoint: "approve",
12122
- calldata: [
12123
- config.marketplace1155Contract,
12124
- amount.low.toString(),
12125
- amount.high.toString()
12126
- ]
12127
- };
12128
- });
12129
- const fulfillCalls = items.map(
12130
- (item) => contract.populate("fulfill_order", [item.orderHash, item.quantity ?? "1"])
12131
- );
12132
- try {
12133
- const tx = await account.execute([...approveCalls, ...fulfillCalls]);
12134
- await provider.waitForTransaction(tx.transaction_hash);
12135
- return { txHash: tx.transaction_hash };
12136
- } catch (err) {
12137
- throw new MedialaneError("ERC-1155 cart checkout failed", "TRANSACTION_FAILED", err);
12138
- }
12139
- }
12140
- async function getOrderDetails1155(orderHash, config) {
12141
- const contract = getContract(config);
12142
- return contract.get_order_details(orderHash);
12143
- }
12144
- async function getCounter1155(address, config) {
12145
- const contract = getContract(config);
12146
- return BigInt((await contract.get_counter(address)).toString());
12147
- }
12148
- async function incrementCounter1155(account, config) {
12149
- const contract = getContract(config);
12150
- const provider = getProvider(config);
12151
- const call = contract.populate("increment_counter", []);
12152
- try {
12153
- const tx = await account.execute(call);
12154
- await provider.waitForTransaction(tx.transaction_hash);
12155
- return { txHash: tx.transaction_hash };
12156
- } catch (err) {
12157
- throw new MedialaneError("Failed to increment counter (1155)", "TRANSACTION_FAILED", err);
12158
- }
12159
- }
12160
-
12161
- // src/starknet/marketplace1155/index.ts
12162
- var Medialane1155Module = class {
12163
- constructor(config) {
12164
- this.config = config;
12165
- }
12166
- // ─── Writes ───────────────────────────────────────────────────────────────
12167
- /**
12168
- * Create an ERC-1155 sell listing.
12169
- * Optionally grants `set_approval_for_all` if not already approved.
12170
- */
12171
- createListing(account, params) {
12172
- return createListing1155(account, params, this.config);
12173
- }
12174
- /**
12175
- * Make an offer (bid) on an ERC-1155 token.
12176
- * Approves the ERC-20 spend then calls `register_order` atomically.
12177
- */
12178
- makeOffer(account, params) {
12179
- return makeOffer1155(account, params, this.config);
12180
- }
12181
- /**
12182
- * Fulfill (buy) an ERC-1155 listing.
12183
- * Approves the payment token then calls `fulfill_order` atomically.
12184
- */
12185
- fulfillOrder(account, params) {
12186
- return fulfillOrder1155(account, params, this.config);
12187
- }
12188
- /**
12189
- * Cancel an ERC-1155 listing (offerer only).
12190
- */
12191
- cancelOrder(account, params) {
12192
- return cancelOrder1155(account, params, this.config);
12193
- }
12194
- /**
12195
- * Checkout a cart of ERC-1155 orders atomically.
12196
- * Signs one fulfillment per item (with quantity), sums ERC-20 approvals by token.
12197
- */
12198
- checkoutCart(account, items) {
12199
- return checkoutCart1155(account, items, this.config);
12200
- }
12201
- /** Bulk-cancel on the 1155 venue: bump the caller's counter. */
12202
- incrementCounter(account) {
12203
- return incrementCounter1155(account, this.config);
12204
- }
12205
- // ─── View calls ───────────────────────────────────────────────────────────
12206
- getOrderDetails(orderHash) {
12207
- return getOrderDetails1155(orderHash, this.config);
12208
- }
12209
- getCounter(address) {
12210
- return getCounter1155(address, this.config);
12211
- }
12212
- // ─── Typed data builders (for ChipiPay / custom signing flows) ───────────
12213
- buildListingTypedData(params, chainId) {
12214
- return build1155OrderTypedData(params, chainId);
12215
- }
12216
- buildCancellationTypedData(params, chainId) {
12217
- return build1155CancellationTypedData(params, chainId);
12218
- }
12219
- };
12220
- var PopService = class {
12221
- constructor(config) {
12222
- this.factoryAddress = getStarknetCoordinates(config.chain).popFactory;
12223
- }
12224
- _collection(address, account) {
12225
- return new Contract(POPCollectionABI, normalizeAddress("STARKNET", address), account);
12226
- }
12227
- async claim(account, collectionAddress) {
12228
- const call = this._collection(collectionAddress, account).populate("claim", []);
12229
- const res = await account.execute([call]);
12230
- return { txHash: res.transaction_hash };
12231
- }
12232
- async adminMint(account, params) {
12233
- const call = this._collection(params.collection, account).populate("admin_mint", [
12234
- params.recipient,
12235
- params.customUri ?? ""
12236
- ]);
12237
- const res = await account.execute([call]);
12238
- return { txHash: res.transaction_hash };
12239
- }
12240
- async addToAllowlist(account, params) {
12241
- const call = this._collection(params.collection, account).populate("add_to_allowlist", [params.address]);
12242
- const res = await account.execute([call]);
12243
- return { txHash: res.transaction_hash };
12244
- }
12245
- async batchAddToAllowlist(account, params) {
12246
- const collection = this._collection(params.collection, account);
12247
- const CHUNK = 200;
12248
- const calls = [];
12249
- for (let i = 0; i < params.addresses.length; i += CHUNK) {
12250
- calls.push(collection.populate("batch_add_to_allowlist", [params.addresses.slice(i, i + CHUNK)]));
12251
- }
12252
- const res = await account.execute(calls);
12253
- return { txHash: res.transaction_hash };
12254
- }
12255
- async removeFromAllowlist(account, params) {
12256
- const call = this._collection(params.collection, account).populate("remove_from_allowlist", [params.address]);
12257
- const res = await account.execute([call]);
12258
- return { txHash: res.transaction_hash };
12259
- }
12260
- async setTokenUri(account, params) {
12261
- const call = this._collection(params.collection, account).populate("set_token_uri", [
12262
- BigInt(params.tokenId),
12263
- params.uri
12264
- ]);
12265
- const res = await account.execute([call]);
12266
- return { txHash: res.transaction_hash };
12267
- }
12268
- async setPaused(account, params) {
12269
- const call = this._collection(params.collection, account).populate("set_paused", [params.paused]);
12270
- const res = await account.execute([call]);
12271
- return { txHash: res.transaction_hash };
12272
- }
12273
- async createCollection(account, params) {
12274
- const factory = new Contract(POPFactoryABI, this.factoryAddress, account);
12275
- const call = factory.populate("create_collection", [
12276
- params.name,
12277
- params.symbol,
12278
- params.baseUri,
12279
- params.claimEndTime,
12280
- { [params.eventType]: {} }
12281
- ]);
12282
- const res = await account.execute([call]);
12283
- return { txHash: res.transaction_hash };
12284
- }
12285
- };
12286
- function toContractConditions(c) {
12287
- return {
12288
- start_time: c.startTime,
12289
- end_time: c.endTime,
12290
- price: BigInt(c.price),
12291
- payment_token: c.paymentToken,
12292
- max_quantity_per_wallet: BigInt(c.maxQuantityPerWallet)
12293
- };
12294
- }
12295
- var DropService = class {
12296
- constructor(config) {
12297
- this.factoryAddress = getStarknetCoordinates(config.chain).dropFactory;
12298
- this.config = config;
12299
- }
12300
- _collection(address, account) {
12301
- return new Contract(DropCollectionABI, normalizeAddress("STARKNET", address), account);
12302
- }
12303
- async claim(account, collectionAddress, quantity = 1) {
12304
- const collection = this._collection(collectionAddress, account);
12305
- const qty = BigInt(quantity);
12306
- const claimCall = collection.populate("claim", [qty]);
12307
- const conditions = await collection.get_claim_conditions();
12308
- const price = BigInt(conditions.price);
12309
- const paymentToken = typeof conditions.payment_token === "bigint" ? "0x" + conditions.payment_token.toString(16) : conditions.payment_token;
12310
- const feeCall = price > 0n ? buildFeeCall(
12311
- { surface: "launchpad", token: paymentToken, grossAmount: price * qty },
12312
- this.config.feeConfig
12313
- ) : null;
12314
- const calls = feeCall ? [claimCall, feeCall] : [claimCall];
12315
- const res = await account.execute(calls);
12316
- return { txHash: res.transaction_hash };
11426
+ async claim(account, collectionAddress, quantity = 1) {
11427
+ const collection = this._collection(collectionAddress, account);
11428
+ const qty = BigInt(quantity);
11429
+ const claimCall = collection.populate("claim", [qty]);
11430
+ const conditions = await collection.get_claim_conditions();
11431
+ const price = BigInt(conditions.price);
11432
+ const paymentToken = typeof conditions.payment_token === "bigint" ? "0x" + conditions.payment_token.toString(16) : conditions.payment_token;
11433
+ const feeCall = price > 0n ? buildFeeCall(
11434
+ { surface: "launchpad", token: paymentToken, grossAmount: price * qty },
11435
+ this.config.feeConfig
11436
+ ) : null;
11437
+ const calls = feeCall ? [claimCall, feeCall] : [claimCall];
11438
+ const res = await account.execute(calls);
11439
+ return { txHash: res.transaction_hash };
12317
11440
  }
12318
11441
  async adminMint(account, params) {
12319
11442
  const call = this._collection(params.collection, account).populate("admin_mint", [
@@ -12939,8 +12062,6 @@ var SponsorshipService = class {
12939
12062
  var MedialaneClient = class {
12940
12063
  constructor(rawConfig = {}) {
12941
12064
  this.config = resolveConfig(rawConfig);
12942
- this.marketplace = new MarketplaceModule(this.config);
12943
- this.marketplace1155 = new Medialane1155Module(this.config);
12944
12065
  this.services = {
12945
12066
  pop: new PopService(this.config),
12946
12067
  drop: new DropService(this.config),
@@ -12983,99 +12104,512 @@ var MedialaneClient = class {
12983
12104
  return this.config.marketplaceContract;
12984
12105
  }
12985
12106
  };
12107
+
12108
+ // src/starknet/marketplace/errors.ts
12109
+ var MedialaneError = class extends Error {
12110
+ constructor(message, code = "UNKNOWN", cause) {
12111
+ super(message);
12112
+ this.code = code;
12113
+ this.cause = cause;
12114
+ this.name = "MedialaneError";
12115
+ }
12116
+ };
12117
+ var START_TIME_BUFFER_SECS = 30;
12118
+ function newContract(abi, address, providerOrAccount) {
12119
+ const C = Contract;
12120
+ return C.length === 1 ? new Contract({ abi, address, providerOrAccount }) : new Contract(
12121
+ abi,
12122
+ address,
12123
+ providerOrAccount
12124
+ );
12125
+ }
12126
+ function getChainId(config) {
12127
+ if (config.chain !== "STARKNET") {
12128
+ throw new Error(`SNIP-12 signing is Starknet-only; got chain "${config.chain}"`);
12129
+ }
12130
+ return constants.StarknetChainId.SN_MAIN;
12131
+ }
12132
+ function resolveToken(currency) {
12133
+ const token = SUPPORTED_TOKENS.find(
12134
+ (t) => t.symbol === currency.toUpperCase() || t.address.toLowerCase() === currency.toLowerCase()
12135
+ );
12136
+ if (!token) throw new MedialaneError(`Unsupported currency: ${currency}`, "INVALID_PARAMS");
12137
+ return token;
12138
+ }
12139
+ var _providerCache = /* @__PURE__ */ new WeakMap();
12140
+ function getProvider(config) {
12141
+ let p = _providerCache.get(config);
12142
+ if (!p) {
12143
+ const urls = Array.from(/* @__PURE__ */ new Set([config.rpcUrl, ...PUBLIC_RPC_FALLBACKS]));
12144
+ p = new RpcProvider({ nodeUrl: urls[0], baseFetch: createFailoverFetch(urls) });
12145
+ _providerCache.set(config, p);
12146
+ }
12147
+ return p;
12148
+ }
12149
+
12150
+ // src/starknet/marketplace/orders.ts
12151
+ var _contractCache = /* @__PURE__ */ new WeakMap();
12152
+ function makeContract(config) {
12153
+ const cached = _contractCache.get(config);
12154
+ if (cached) return cached;
12155
+ const contract = newContract(
12156
+ IPMarketplaceABI,
12157
+ config.marketplaceContract,
12158
+ getProvider(config)
12159
+ );
12160
+ const entry = { contract };
12161
+ _contractCache.set(config, entry);
12162
+ return entry;
12163
+ }
12164
+ async function getOrderDetails(orderHash, config) {
12165
+ const { contract } = makeContract(config);
12166
+ return contract.get_order_details(orderHash);
12167
+ }
12168
+ async function getCounter(address, config) {
12169
+ const { contract } = makeContract(config);
12170
+ return BigInt((await contract.get_counter(address)).toString());
12171
+ }
12172
+
12173
+ // src/starknet/marketplace1155/orders.ts
12174
+ var _contractCache2 = /* @__PURE__ */ new WeakMap();
12175
+ function getContract(config) {
12176
+ let c = _contractCache2.get(config);
12177
+ if (!c) {
12178
+ c = newContract(Medialane1155ABI, config.marketplace1155Contract, getProvider(config));
12179
+ _contractCache2.set(config, c);
12180
+ }
12181
+ return c;
12182
+ }
12183
+ async function getOrderDetails1155(orderHash, config) {
12184
+ const contract = getContract(config);
12185
+ return contract.get_order_details(orderHash);
12186
+ }
12187
+ async function getCounter1155(address, config) {
12188
+ const contract = getContract(config);
12189
+ return BigInt((await contract.get_counter(address)).toString());
12190
+ }
12191
+ var STARKNET_DOMAIN = [
12192
+ { name: "name", type: "shortstring" },
12193
+ { name: "version", type: "shortstring" },
12194
+ { name: "chainId", type: "shortstring" },
12195
+ { name: "revision", type: "shortstring" }
12196
+ ];
12197
+ var OFFER_ITEM = [
12198
+ { name: "item_type", type: "shortstring" },
12199
+ { name: "token", type: "ContractAddress" },
12200
+ { name: "identifier_or_criteria", type: "felt" },
12201
+ { name: "amount", type: "felt" }
12202
+ ];
12203
+ var CONSIDERATION_ITEM = [
12204
+ { name: "item_type", type: "shortstring" },
12205
+ { name: "token", type: "ContractAddress" },
12206
+ { name: "identifier_or_criteria", type: "felt" },
12207
+ { name: "amount", type: "felt" },
12208
+ { name: "recipient", type: "ContractAddress" }
12209
+ ];
12210
+ var ORDER_PARAMETERS = [
12211
+ { name: "offerer", type: "ContractAddress" },
12212
+ { name: "marketplace", type: "ContractAddress" },
12213
+ { name: "offer", type: "OfferItem" },
12214
+ { name: "consideration", type: "ConsiderationItem" },
12215
+ { name: "royalty_max_bps", type: "felt" },
12216
+ { name: "start_time", type: "felt" },
12217
+ { name: "end_time", type: "felt" },
12218
+ { name: "salt", type: "felt" },
12219
+ { name: "counter", type: "felt" }
12220
+ ];
12221
+ var ORDER_CANCELLATION = [
12222
+ { name: "order_hash", type: "felt" },
12223
+ { name: "offerer", type: "ContractAddress" }
12224
+ ];
12225
+ var DOMAIN_VERSION = {
12226
+ erc721: "5",
12227
+ erc1155: "4"
12228
+ };
12229
+ function buildDomain(standard, chainId) {
12230
+ return {
12231
+ name: "Medialane",
12232
+ version: DOMAIN_VERSION[standard],
12233
+ chainId,
12234
+ revision: TypedDataRevision.ACTIVE
12235
+ };
12236
+ }
12237
+ function buildOrderTypedData(message, chainId) {
12238
+ return {
12239
+ domain: buildDomain("erc721", chainId),
12240
+ primaryType: "OrderParameters",
12241
+ types: {
12242
+ StarknetDomain: STARKNET_DOMAIN,
12243
+ OrderParameters: ORDER_PARAMETERS,
12244
+ OfferItem: OFFER_ITEM,
12245
+ ConsiderationItem: CONSIDERATION_ITEM
12246
+ },
12247
+ message
12248
+ };
12249
+ }
12250
+ function build1155OrderTypedData(message, chainId) {
12251
+ return {
12252
+ domain: buildDomain("erc1155", chainId),
12253
+ primaryType: "OrderParameters",
12254
+ types: {
12255
+ StarknetDomain: STARKNET_DOMAIN,
12256
+ OrderParameters: ORDER_PARAMETERS,
12257
+ OfferItem: OFFER_ITEM,
12258
+ ConsiderationItem: CONSIDERATION_ITEM
12259
+ },
12260
+ message
12261
+ };
12262
+ }
12263
+ function buildCancellationTypedData(message, chainId) {
12264
+ return {
12265
+ domain: buildDomain("erc721", chainId),
12266
+ primaryType: "OrderCancellation",
12267
+ types: {
12268
+ StarknetDomain: STARKNET_DOMAIN,
12269
+ OrderCancellation: ORDER_CANCELLATION
12270
+ },
12271
+ message
12272
+ };
12273
+ }
12274
+ function build1155CancellationTypedData(message, chainId) {
12275
+ return {
12276
+ domain: buildDomain("erc1155", chainId),
12277
+ primaryType: "OrderCancellation",
12278
+ types: {
12279
+ StarknetDomain: STARKNET_DOMAIN,
12280
+ OrderCancellation: ORDER_CANCELLATION
12281
+ },
12282
+ message
12283
+ };
12284
+ }
12285
+
12286
+ // src/starknet/marketplace/build.ts
12287
+ function contractFor(cfg) {
12288
+ return newContract(IPMarketplaceABI, cfg.marketplaceContract, getProvider(cfg));
12289
+ }
12290
+ function buildListingOrder(i, cfg) {
12291
+ const orderParams = {
12292
+ offerer: i.offerer,
12293
+ marketplace: cfg.marketplaceContract,
12294
+ offer: { item_type: "ERC721", token: i.nftContract, identifier_or_criteria: i.tokenId, amount: "1" },
12295
+ consideration: {
12296
+ item_type: "ERC20",
12297
+ token: i.paymentTokenAddress,
12298
+ identifier_or_criteria: "0",
12299
+ amount: i.priceWei,
12300
+ recipient: i.offerer
12301
+ },
12302
+ royalty_max_bps: i.royaltyMaxBps,
12303
+ start_time: String(i.startTime),
12304
+ end_time: String(i.endTime),
12305
+ salt: i.salt,
12306
+ counter: i.counter
12307
+ };
12308
+ const typedData = stringifyBigInts(buildOrderTypedData(orderParams, getChainId(cfg)));
12309
+ return { orderParams, typedData };
12310
+ }
12311
+ function buildOfferOrder(i, cfg) {
12312
+ const orderParams = {
12313
+ offerer: i.offerer,
12314
+ marketplace: cfg.marketplaceContract,
12315
+ offer: { item_type: "ERC20", token: i.paymentTokenAddress, identifier_or_criteria: "0", amount: i.priceWei },
12316
+ consideration: {
12317
+ item_type: "ERC721",
12318
+ token: i.nftContract,
12319
+ identifier_or_criteria: i.tokenId,
12320
+ amount: "1",
12321
+ recipient: i.offerer
12322
+ },
12323
+ royalty_max_bps: i.royaltyMaxBps,
12324
+ start_time: String(i.startTime),
12325
+ end_time: String(i.endTime),
12326
+ salt: i.salt,
12327
+ counter: i.counter
12328
+ };
12329
+ const typedData = stringifyBigInts(buildOrderTypedData(orderParams, getChainId(cfg)));
12330
+ return { orderParams, typedData };
12331
+ }
12332
+ function registerPayload(orderParams, signature) {
12333
+ return stringifyBigInts({
12334
+ parameters: {
12335
+ ...orderParams,
12336
+ offer: { ...orderParams.offer, item_type: shortString.encodeShortString(orderParams.offer.item_type) },
12337
+ consideration: {
12338
+ ...orderParams.consideration,
12339
+ item_type: shortString.encodeShortString(orderParams.consideration.item_type)
12340
+ }
12341
+ },
12342
+ signature
12343
+ });
12344
+ }
12345
+ function buildRegisterCalls(a, cfg) {
12346
+ const registerCall = contractFor(cfg).populate("register_order", [registerPayload(a.orderParams, a.signature)]);
12347
+ return a.approvalNeeded ? [a.approve, registerCall] : [registerCall];
12348
+ }
12349
+ function buildFulfillCalls(a, cfg) {
12350
+ const u = cairo.uint256(a.totalPrice);
12351
+ const approve = {
12352
+ contractAddress: a.paymentToken,
12353
+ entrypoint: "approve",
12354
+ calldata: [cfg.marketplaceContract, u.low.toString(), u.high.toString()]
12355
+ };
12356
+ const fulfill = contractFor(cfg).populate("fulfill_order", [a.orderHash]);
12357
+ const fee = buildFeeCall(
12358
+ { surface: "marketplace", token: a.paymentToken, grossAmount: BigInt(a.totalPrice) },
12359
+ cfg.feeConfig
12360
+ );
12361
+ return fee ? [approve, fulfill, fee] : [approve, fulfill];
12362
+ }
12363
+ function buildCancelCalls(a, cfg) {
12364
+ const cancelRequest = stringifyBigInts({
12365
+ cancelation: { order_hash: a.orderHash, offerer: a.offerer },
12366
+ signature: a.signature
12367
+ });
12368
+ return [contractFor(cfg).populate("cancel_order", [cancelRequest])];
12369
+ }
12370
+ function buildCancelTypedData(orderHash, offerer, cfg) {
12371
+ return stringifyBigInts(buildCancellationTypedData({ order_hash: orderHash, offerer }, getChainId(cfg)));
12372
+ }
12373
+ function contractFor2(cfg) {
12374
+ return newContract(Medialane1155ABI, cfg.marketplace1155Contract, getProvider(cfg));
12375
+ }
12376
+ function buildListing1155Order(i, cfg) {
12377
+ const orderParams = {
12378
+ offerer: i.offerer,
12379
+ marketplace: cfg.marketplace1155Contract,
12380
+ offer: { item_type: "ERC1155", token: i.nftContract, identifier_or_criteria: i.tokenId, amount: i.quantity },
12381
+ consideration: {
12382
+ item_type: "ERC20",
12383
+ token: i.paymentTokenAddress,
12384
+ identifier_or_criteria: "0",
12385
+ amount: i.priceWeiPerUnit,
12386
+ recipient: i.offerer
12387
+ },
12388
+ royalty_max_bps: i.royaltyMaxBps,
12389
+ start_time: String(i.startTime),
12390
+ end_time: String(i.endTime),
12391
+ salt: i.salt,
12392
+ counter: i.counter
12393
+ };
12394
+ const typedData = stringifyBigInts(
12395
+ build1155OrderTypedData(orderParams, getChainId(cfg))
12396
+ );
12397
+ return { orderParams, typedData };
12398
+ }
12399
+ function buildOffer1155Order(i, cfg) {
12400
+ const orderParams = {
12401
+ offerer: i.offerer,
12402
+ marketplace: cfg.marketplace1155Contract,
12403
+ offer: { item_type: "ERC20", token: i.paymentTokenAddress, identifier_or_criteria: "0", amount: i.priceWeiPerUnit },
12404
+ consideration: {
12405
+ item_type: "ERC1155",
12406
+ token: i.nftContract,
12407
+ identifier_or_criteria: i.tokenId,
12408
+ amount: i.quantity,
12409
+ recipient: i.offerer
12410
+ },
12411
+ royalty_max_bps: i.royaltyMaxBps,
12412
+ start_time: String(i.startTime),
12413
+ end_time: String(i.endTime),
12414
+ salt: i.salt,
12415
+ counter: i.counter
12416
+ };
12417
+ const typedData = stringifyBigInts(
12418
+ build1155OrderTypedData(orderParams, getChainId(cfg))
12419
+ );
12420
+ return { orderParams, typedData };
12421
+ }
12422
+ function registerPayload2(orderParams, signature) {
12423
+ return stringifyBigInts({
12424
+ parameters: {
12425
+ ...orderParams,
12426
+ offer: { ...orderParams.offer, item_type: shortString.encodeShortString(orderParams.offer.item_type) },
12427
+ consideration: {
12428
+ ...orderParams.consideration,
12429
+ item_type: shortString.encodeShortString(orderParams.consideration.item_type)
12430
+ }
12431
+ },
12432
+ signature
12433
+ });
12434
+ }
12435
+ function buildRegister1155Calls(a, cfg) {
12436
+ const registerCall = contractFor2(cfg).populate("register_order", [registerPayload2(a.orderParams, a.signature)]);
12437
+ return a.approvalNeeded ? [a.approve, registerCall] : [registerCall];
12438
+ }
12439
+ function buildFulfill1155Calls(a, cfg) {
12440
+ const u = cairo.uint256(a.totalPrice);
12441
+ const approve = {
12442
+ contractAddress: a.paymentToken,
12443
+ entrypoint: "approve",
12444
+ calldata: [cfg.marketplace1155Contract, u.low.toString(), u.high.toString()]
12445
+ };
12446
+ const fulfill = contractFor2(cfg).populate("fulfill_order", [a.orderHash, a.quantity]);
12447
+ const fee = buildFeeCall(
12448
+ { surface: "marketplace", token: a.paymentToken, grossAmount: BigInt(a.totalPrice) },
12449
+ cfg.feeConfig
12450
+ );
12451
+ return fee ? [approve, fulfill, fee] : [approve, fulfill];
12452
+ }
12453
+ function buildCancel1155Calls(a, cfg) {
12454
+ const cancelPayload = stringifyBigInts({
12455
+ cancelation: { order_hash: a.orderHash, offerer: a.offerer },
12456
+ signature: a.signature
12457
+ });
12458
+ return [contractFor2(cfg).populate("cancel_order", [cancelPayload])];
12459
+ }
12460
+ function buildCancel1155TypedData(orderHash, offerer, cfg) {
12461
+ return stringifyBigInts(
12462
+ build1155CancellationTypedData({ order_hash: orderHash, offerer }, getChainId(cfg))
12463
+ );
12464
+ }
12465
+
12466
+ // src/starknet/venue.ts
12986
12467
  var NO_EXPIRY_SECONDS = 100 * 365 * 24 * 3600;
12987
12468
  var StarknetVenue = class {
12988
12469
  constructor(deps) {
12989
12470
  this.deps = deps;
12990
12471
  this.chain = "STARKNET";
12991
- this.m721 = new MarketplaceModule(deps.config);
12992
- this.m1155 = new Medialane1155Module(deps.config);
12993
12472
  }
12994
- incrementCounter(signer) {
12995
- return this.m721.incrementCounter(signer);
12473
+ async incrementCounter(signer) {
12474
+ return signer.execute([
12475
+ { contractAddress: this.deps.config.marketplaceContract, entrypoint: "increment_counter", calldata: [] }
12476
+ ]);
12996
12477
  }
12997
12478
  getOrderDetails(orderRef) {
12998
- return this.m721.getOrderDetails(orderRef);
12479
+ return getOrderDetails(orderRef, this.deps.config);
12999
12480
  }
13000
- getCounter(address) {
13001
- return this.m721.getCounter(address);
12481
+ async getCounter(address) {
12482
+ return this.readCounter(this.deps.config.marketplaceContract, address);
13002
12483
  }
13003
12484
  async fulfillOrder(signer, orderRef, opts) {
13004
12485
  const o = await this.deps.resolveOrder(orderRef);
13005
12486
  const quantity = opts?.quantity ?? "1";
13006
12487
  const totalPrice = (BigInt(o.unitPrice) * BigInt(quantity)).toString();
13007
- if (o.standard === "ERC1155") {
13008
- return this.m1155.fulfillOrder(signer, {
13009
- orderHash: orderRef,
13010
- paymentToken: o.paymentToken,
13011
- totalPrice,
13012
- quantity
13013
- });
13014
- }
13015
- return this.m721.fulfillOrder(signer, {
13016
- orderHash: orderRef,
13017
- paymentToken: o.paymentToken,
13018
- totalPrice
13019
- });
12488
+ const calls = o.standard === "ERC1155" ? buildFulfill1155Calls({ orderHash: orderRef, paymentToken: o.paymentToken, totalPrice, quantity }, this.deps.config) : buildFulfillCalls({ orderHash: orderRef, paymentToken: o.paymentToken, totalPrice }, this.deps.config);
12489
+ return signer.execute(calls);
13020
12490
  }
13021
12491
  async cancelOrder(signer, orderRef) {
13022
12492
  const o = await this.deps.resolveOrder(orderRef);
13023
- if (o.standard === "ERC1155") {
13024
- return this.m1155.cancelOrder(signer, { orderHash: orderRef });
13025
- }
13026
- return this.m721.cancelOrder(signer, { orderHash: orderRef });
12493
+ const typedData = o.standard === "ERC1155" ? buildCancel1155TypedData(orderRef, signer.address, this.deps.config) : buildCancelTypedData(orderRef, signer.address, this.deps.config);
12494
+ const signature = await signer.signTypedData(typedData);
12495
+ const calls = o.standard === "ERC1155" ? buildCancel1155Calls({ orderHash: orderRef, offerer: signer.address, signature }, this.deps.config) : buildCancelCalls({ orderHash: orderRef, offerer: signer.address, signature }, this.deps.config);
12496
+ return signer.execute(calls);
13027
12497
  }
13028
12498
  async registerOrder(signer, p) {
13029
12499
  const standard = await this.deps.resolveStandard(p.asset.contract);
13030
- const token = resolveToken(p.paymentToken);
13031
- const humanPrice = formatAmount(p.amount, token.decimals);
13032
- const durationSeconds = this.durationSeconds(p.endTime);
12500
+ const paymentTokenAddress = resolveToken(p.paymentToken).address;
13033
12501
  const royaltyMaxBps = String(p.royaltyMaxBps);
12502
+ const startTime = Math.floor(Date.now() / 1e3) + START_TIME_BUFFER_SECS;
12503
+ const endTime = p.endTime && p.endTime > 0 ? p.endTime : startTime + NO_EXPIRY_SECONDS;
13034
12504
  const quantity = p.quantity ?? "1";
13035
- let txHash;
12505
+ const marketplace = standard === "ERC1155" ? this.deps.config.marketplace1155Contract : this.deps.config.marketplaceContract;
12506
+ const counter = String(await this.readCounter(marketplace, signer.address));
12507
+ let typedData;
12508
+ let buildCalls;
13036
12509
  if (standard === "ERC1155") {
13037
- if (p.side === "listing") {
13038
- const res = await this.m1155.createListing(signer, {
12510
+ const built = (p.side === "listing" ? buildListing1155Order : buildOffer1155Order)(
12511
+ {
12512
+ offerer: signer.address,
13039
12513
  nftContract: p.asset.contract,
13040
12514
  tokenId: p.asset.tokenId,
13041
- amount: quantity,
13042
- pricePerUnit: humanPrice,
13043
- currency: p.paymentToken,
13044
- durationSeconds,
13045
- royaltyMaxBps
13046
- });
13047
- txHash = res.txHash;
13048
- } else {
13049
- const totalHuman = formatAmount((BigInt(p.amount) * BigInt(quantity)).toString(), token.decimals);
13050
- const res = await this.m1155.makeOffer(signer, {
12515
+ quantity,
12516
+ priceWeiPerUnit: p.amount,
12517
+ paymentTokenAddress,
12518
+ royaltyMaxBps,
12519
+ startTime,
12520
+ endTime,
12521
+ salt: p.salt,
12522
+ counter
12523
+ },
12524
+ this.deps.config
12525
+ );
12526
+ typedData = built.typedData;
12527
+ const approval = p.side === "listing" ? await this.approval1155ForListing(signer.address, p.asset.contract) : this.approvalForErc20(paymentTokenAddress, (BigInt(p.amount) * BigInt(quantity)).toString(), marketplace);
12528
+ buildCalls = (sig) => buildRegister1155Calls({ orderParams: built.orderParams, signature: sig, ...approval }, this.deps.config);
12529
+ } else {
12530
+ const built = (p.side === "listing" ? buildListingOrder : buildOfferOrder)(
12531
+ {
12532
+ offerer: signer.address,
13051
12533
  nftContract: p.asset.contract,
13052
12534
  tokenId: p.asset.tokenId,
13053
- amount: quantity,
13054
- price: totalHuman,
13055
- currency: p.paymentToken,
13056
- durationSeconds,
13057
- royaltyMaxBps
13058
- });
13059
- txHash = res.txHash;
13060
- }
13061
- } else {
13062
- const params = {
13063
- nftContract: p.asset.contract,
13064
- tokenId: p.asset.tokenId,
13065
- price: humanPrice,
13066
- currency: p.paymentToken,
13067
- durationSeconds,
13068
- royaltyMaxBps
13069
- };
13070
- const res = p.side === "listing" ? await this.m721.createListing(signer, params) : await this.m721.makeOffer(signer, params);
13071
- txHash = res.txHash;
12535
+ priceWei: p.amount,
12536
+ paymentTokenAddress,
12537
+ royaltyMaxBps,
12538
+ startTime,
12539
+ endTime,
12540
+ salt: p.salt,
12541
+ counter
12542
+ },
12543
+ this.deps.config
12544
+ );
12545
+ typedData = built.typedData;
12546
+ const approval = p.side === "listing" ? await this.approval721ForListing(signer.address, p.asset.contract, p.asset.tokenId) : this.approvalForErc20(paymentTokenAddress, p.amount, marketplace);
12547
+ buildCalls = (sig) => buildRegisterCalls({ orderParams: built.orderParams, signature: sig, ...approval }, this.deps.config);
13072
12548
  }
12549
+ const signature = await signer.signTypedData(typedData);
12550
+ const { txHash } = await signer.execute(buildCalls(signature));
13073
12551
  const orderRef = await this.orderRefFromReceipt(txHash);
13074
12552
  return { txHash, orderRef };
13075
12553
  }
13076
- durationSeconds(endTime) {
13077
- if (!endTime) return NO_EXPIRY_SECONDS;
13078
- return Math.max(1, endTime - Math.floor(Date.now() / 1e3));
12554
+ // ─── reads (all on deps.provider) ─────────────────────────────────────────
12555
+ async readCounter(marketplace, address) {
12556
+ const res = await this.deps.provider.callContract({
12557
+ contractAddress: marketplace,
12558
+ entrypoint: "get_counter",
12559
+ calldata: [address]
12560
+ });
12561
+ return BigInt(res[0] ?? "0");
12562
+ }
12563
+ /** 721 listing approval: `get_approved(tokenId) == marketplace` ⇒ no approve. */
12564
+ async approval721ForListing(_owner, nftContract, tokenId) {
12565
+ const id = cairo.uint256(tokenId);
12566
+ const approve = {
12567
+ contractAddress: nftContract,
12568
+ entrypoint: "approve",
12569
+ calldata: [this.deps.config.marketplaceContract, id.low.toString(), id.high.toString()]
12570
+ };
12571
+ let approved = false;
12572
+ try {
12573
+ const res = await this.deps.provider.callContract({
12574
+ contractAddress: nftContract,
12575
+ entrypoint: "get_approved",
12576
+ calldata: [id.low.toString(), id.high.toString()]
12577
+ });
12578
+ approved = BigInt(res[0]).toString() === BigInt(this.deps.config.marketplaceContract).toString();
12579
+ } catch {
12580
+ }
12581
+ return { approvalNeeded: !approved, approve };
12582
+ }
12583
+ /** 1155 listing approval: `is_approved_for_all(owner, marketplace)`. */
12584
+ async approval1155ForListing(owner, nftContract) {
12585
+ const approve = {
12586
+ contractAddress: nftContract,
12587
+ entrypoint: "set_approval_for_all",
12588
+ calldata: [this.deps.config.marketplace1155Contract, "1"]
12589
+ };
12590
+ let approved = false;
12591
+ try {
12592
+ const res = await this.deps.provider.callContract({
12593
+ contractAddress: nftContract,
12594
+ entrypoint: "is_approved_for_all",
12595
+ calldata: [owner, this.deps.config.marketplace1155Contract]
12596
+ });
12597
+ approved = BigInt(res[0]) === 1n;
12598
+ } catch {
12599
+ }
12600
+ return { approvalNeeded: !approved, approve };
12601
+ }
12602
+ /** Offers always approve the ERC-20 spend (no read). */
12603
+ approvalForErc20(token, amountWei, marketplace) {
12604
+ const u = cairo.uint256(amountWei);
12605
+ return {
12606
+ approvalNeeded: true,
12607
+ approve: {
12608
+ contractAddress: token,
12609
+ entrypoint: "approve",
12610
+ calldata: [marketplace, u.low.toString(), u.high.toString()]
12611
+ }
12612
+ };
13079
12613
  }
13080
12614
  /** The canonical Starknet order id = the contract-emitted `OrderCreated`
13081
12615
  * hash (`keys[1]`), which is exactly what the indexer stores. */
@@ -13348,7 +12882,31 @@ function buybackQuoteRaw(teamCoinsRawValue, quoteDecimals) {
13348
12882
  function fdvHuman(supplyHuman) {
13349
12883
  return supplyHuman * LAUNCH_PRICE_QUOTE_PER_COIN;
13350
12884
  }
12885
+ function encodeByteArray(str) {
12886
+ const bytes = new TextEncoder().encode(str);
12887
+ const fullChunks = [];
12888
+ let i = 0;
12889
+ while (i + 31 <= bytes.length) {
12890
+ let val = 0n;
12891
+ for (const b of bytes.slice(i, i + 31)) {
12892
+ val = val << 8n | BigInt(b);
12893
+ }
12894
+ fullChunks.push(num.toHex(val));
12895
+ i += 31;
12896
+ }
12897
+ const remaining = bytes.slice(i);
12898
+ let pendingVal = 0n;
12899
+ for (const b of remaining) {
12900
+ pendingVal = pendingVal << 8n | BigInt(b);
12901
+ }
12902
+ return [
12903
+ fullChunks.length.toString(),
12904
+ ...fullChunks,
12905
+ num.toHex(pendingVal),
12906
+ remaining.length.toString()
12907
+ ];
12908
+ }
13351
12909
 
13352
- export { ADMIN_HEADERS, ADMIN_SCOPE, ApiClient, CHAINS, MAX_SUPPLY as COIN_MAX_SUPPLY, MIN_SUPPLY as COIN_MIN_SUPPLY, ClubService, CreatorCoinFactoryABI, CreatorCoinService, DEFAULT_CHAIN, DEFAULT_CURRENCY, DropCollectionABI, DropFactoryABI, DropService, ERC1155CollectionService, FeeConfigSchema, IPClubABI, IPClubCollectionABI, IPClubFactoryABI, IPClubNFTABI, IPCollection1155ABI, IPCollection1155FactoryABI, IPCollectionABI, IPGenesisABI, IPMarketplaceABI, IPNftABI, IPSponsorshipABI, IPSponsorshipLicenseABI, IPTicketCollectionABI, IPTicketCollectionFactoryABI, LAUNCH_PRICE_QUOTE_PER_COIN, MarketplaceModule, Medialane1155ABI, Medialane1155Module, MedialaneApiError, MedialaneClient, MedialaneError, OPEN_LICENSES, POPCollectionABI, POPFactoryABI, PUBLIC_RPC_FALLBACKS, PopService, STARKNET_COLLECTION_1155_CLASS_HASH, STARKNET_COLLECTION_1155_CONTRACT, STARKNET_COLLECTION_1155_FACTORY_CLASS_HASH, STARKNET_COLLECTION_1155_START_BLOCK, STARKNET_COLLECTION_721_CONTRACT, STARKNET_COLLECTION_721_START_BLOCK, STARKNET_CREATOR_COIN_CLASS_HASH, STARKNET_CREATOR_COIN_EKUBO_LAUNCHER, STARKNET_CREATOR_COIN_FACTORY_CLASS_HASH, STARKNET_CREATOR_COIN_FACTORY_CONTRACT, STARKNET_CREATOR_COIN_START_BLOCK, STARKNET_DROP_COLLECTION_CLASS_HASH, STARKNET_DROP_FACTORY_CONTRACT, STARKNET_EKUBO_CORE, STARKNET_IPCOLLECTION_CLASS_HASH, STARKNET_IPNFT_CLASS_HASH, STARKNET_IP_CLUB_COLLECTION_CLASS_HASH, STARKNET_IP_CLUB_FACTORY_CONTRACT, STARKNET_IP_CLUB_NFT_CLASS_HASH, STARKNET_IP_CLUB_REGISTRY_CONTRACT, STARKNET_IP_SPONSORSHIP_CONTRACT, STARKNET_IP_SPONSORSHIP_LICENSE_CONTRACT, STARKNET_IP_TICKETS_FACTORY_CONTRACT, STARKNET_IP_TICKET_COLLECTION_CLASS_HASH, STARKNET_MARKETPLACE_1155_CLASS_HASH, STARKNET_MARKETPLACE_1155_CONTRACT, STARKNET_MARKETPLACE_1155_START_BLOCK, STARKNET_MARKETPLACE_721_CLASS_HASH, STARKNET_MARKETPLACE_721_CONTRACT, STARKNET_MARKETPLACE_721_START_BLOCK, STARKNET_NFTCOMMENTS_CONTRACT, STARKNET_POP_COLLECTION_CLASS_HASH, STARKNET_POP_FACTORY_CONTRACT, SUPPORTED_TOKENS, SponsorshipService, StarknetVenue, TicketService, VALIDATED_EKUBO_PARAMS, adminRequestDigest, build1155CancellationTypedData, build1155OrderTypedData, buildAdminSessionTypedData, buildCancellationTypedData, buildCreateCreatorCoinCall, buildFeeCall, buildLaunchOnEkuboCalls, buildOrderTypedData, buybackQuoteRaw, toRaw as coinToRaw, createAdminSessionGrant, createFailoverFetch, encodeAdminHeaders, encodeByteArray, fdvHuman, formatAmount, getCoordinates, getCreatorCoinPrice, getListableTokens, getService, getServicesByCapability, getSiwsStorageKey, getStarknetCoordinates, getStoredSiwsToken, getTokenByAddress, getTokenBySymbol, hasCapability, isServiceId, isSiwsTokenValid, isTransientRpcError, listServices, normalizeAddress, normalizeHash, normalizeSiwsSignature, parseAdminHeaders, parseAmount, parseCreatorCoinCreated, randomNonce, requestSiwsToken, resolveConfig, resolveFeeConfig, sessionKeyHashOf, shortenAddress, signAdminRequest, storeSiwsToken, stringifyBigInts, teamCoinsRaw, u256ToBigInt, validateName as validateCoinName, validateSupply as validateCoinSupply, validateSymbol as validateCoinSymbol, verifyAdminRequestSig };
12910
+ export { ADMIN_HEADERS, ADMIN_SCOPE, ApiClient, CHAINS, MAX_SUPPLY as COIN_MAX_SUPPLY, MIN_SUPPLY as COIN_MIN_SUPPLY, ClubService, CreatorCoinFactoryABI, CreatorCoinService, DEFAULT_CHAIN, DEFAULT_CURRENCY, DropCollectionABI, DropFactoryABI, DropService, ERC1155CollectionService, FeeConfigSchema, IPClubABI, IPClubCollectionABI, IPClubFactoryABI, IPClubNFTABI, IPCollection1155ABI, IPCollection1155FactoryABI, IPCollectionABI, IPGenesisABI, IPMarketplaceABI, IPNftABI, IPSponsorshipABI, IPSponsorshipLicenseABI, IPTicketCollectionABI, IPTicketCollectionFactoryABI, LAUNCH_PRICE_QUOTE_PER_COIN, Medialane1155ABI, MedialaneApiError, MedialaneClient, MedialaneError, OPEN_LICENSES, POPCollectionABI, POPFactoryABI, PUBLIC_RPC_FALLBACKS, PopService, STARKNET_COLLECTION_1155_CLASS_HASH, STARKNET_COLLECTION_1155_CONTRACT, STARKNET_COLLECTION_1155_FACTORY_CLASS_HASH, STARKNET_COLLECTION_1155_START_BLOCK, STARKNET_COLLECTION_721_CONTRACT, STARKNET_COLLECTION_721_START_BLOCK, STARKNET_CREATOR_COIN_CLASS_HASH, STARKNET_CREATOR_COIN_EKUBO_LAUNCHER, STARKNET_CREATOR_COIN_FACTORY_CLASS_HASH, STARKNET_CREATOR_COIN_FACTORY_CONTRACT, STARKNET_CREATOR_COIN_START_BLOCK, STARKNET_DROP_COLLECTION_CLASS_HASH, STARKNET_DROP_FACTORY_CONTRACT, STARKNET_EKUBO_CORE, STARKNET_IPCOLLECTION_CLASS_HASH, STARKNET_IPNFT_CLASS_HASH, STARKNET_IP_CLUB_COLLECTION_CLASS_HASH, STARKNET_IP_CLUB_FACTORY_CONTRACT, STARKNET_IP_CLUB_NFT_CLASS_HASH, STARKNET_IP_CLUB_REGISTRY_CONTRACT, STARKNET_IP_SPONSORSHIP_CONTRACT, STARKNET_IP_SPONSORSHIP_LICENSE_CONTRACT, STARKNET_IP_TICKETS_FACTORY_CONTRACT, STARKNET_IP_TICKET_COLLECTION_CLASS_HASH, STARKNET_MARKETPLACE_1155_CLASS_HASH, STARKNET_MARKETPLACE_1155_CONTRACT, STARKNET_MARKETPLACE_1155_START_BLOCK, STARKNET_MARKETPLACE_721_CLASS_HASH, STARKNET_MARKETPLACE_721_CONTRACT, STARKNET_MARKETPLACE_721_START_BLOCK, STARKNET_NFTCOMMENTS_CONTRACT, STARKNET_POP_COLLECTION_CLASS_HASH, STARKNET_POP_FACTORY_CONTRACT, SUPPORTED_TOKENS, SponsorshipService, StarknetVenue, TicketService, VALIDATED_EKUBO_PARAMS, adminRequestDigest, build1155CancellationTypedData, build1155OrderTypedData, buildAdminSessionTypedData, buildCancellationTypedData, buildCreateCreatorCoinCall, buildFeeCall, buildLaunchOnEkuboCalls, buildOrderTypedData, buybackQuoteRaw, toRaw as coinToRaw, createAdminSessionGrant, createFailoverFetch, encodeAdminHeaders, encodeByteArray, fdvHuman, formatAmount, getCoordinates, getCounter, getCounter1155, getCreatorCoinPrice, getListableTokens, getOrderDetails, getOrderDetails1155, getService, getServicesByCapability, getSiwsStorageKey, getStarknetCoordinates, getStoredSiwsToken, getTokenByAddress, getTokenBySymbol, hasCapability, isServiceId, isSiwsTokenValid, isTransientRpcError, listServices, normalizeAddress, normalizeHash, normalizeSiwsSignature, parseAdminHeaders, parseAmount, parseCreatorCoinCreated, randomNonce, requestSiwsToken, resolveConfig, resolveFeeConfig, sessionKeyHashOf, shortenAddress, signAdminRequest, storeSiwsToken, stringifyBigInts, teamCoinsRaw, u256ToBigInt, validateName as validateCoinName, validateSupply as validateCoinSupply, validateSymbol as validateCoinSymbol, verifyAdminRequestSig };
13353
12911
  //# sourceMappingURL=index.js.map
13354
12912
  //# sourceMappingURL=index.js.map