@imtbl/orderbook 2.16.1-alpha.1 → 2.16.1-alpha.3

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.
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var metrics = require('@imtbl/metrics');
4
- var le = require('axios');
5
- var pe = require('form-data');
4
+ var ce = require('axios');
5
+ var ue = require('form-data');
6
6
  var ethers = require('ethers');
7
7
  var merkletreejs = require('merkletreejs');
8
8
  var config = require('@imtbl/config');
@@ -10,15 +10,15 @@ var seaportJs = require('@opensea/seaport-js');
10
10
 
11
11
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
12
 
13
- var le__default = /*#__PURE__*/_interopDefault(le);
14
- var pe__default = /*#__PURE__*/_interopDefault(pe);
13
+ var ce__default = /*#__PURE__*/_interopDefault(ce);
14
+ var ue__default = /*#__PURE__*/_interopDefault(ue);
15
15
 
16
- var b=class{constructor(t){this.config=t;}};var T=class extends Error{url;status;statusText;body;request;constructor(t,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=t;}};var v=class extends Error{constructor(t){super(t),this.name="CancelError";}get isCancelled(){return !0}},L=class{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(t){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((r,s)=>{this._resolve=r,this._reject=s;let n=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(d));},i=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(d));},o=d=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(d);};return Object.defineProperty(o,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(o,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(o,"isCancelled",{get:()=>this._isCancelled}),t(n,i,o)});}then(t,r){return this._promise.then(t,r)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let t of this._cancelHandlers)t();}catch(t){console.warn("Cancellation threw an error",t);return}this._cancelHandlers.length=0,this._reject?.(new v("Request aborted"));}}get isCancelled(){return this._isCancelled}};var ee=e=>e!=null,F=e=>typeof e=="string",Q=e=>F(e)&&e!=="",ce=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof pe__default.default,qe=e=>e>=200&&e<300,He=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Me=e=>{let t=[],r=(n,i)=>{t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`);},s=(n,i)=>{ee(i)&&(Array.isArray(i)?i.forEach(o=>{s(n,o);}):typeof i=="object"?Object.entries(i).forEach(([o,d])=>{s(`${n}[${o}]`,d);}):r(n,i));};return Object.entries(e).forEach(([n,i])=>{s(n,i);}),t.length>0?`?${t.join("&")}`:""},Ve=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(i,o)=>t.path?.hasOwnProperty(o)?r(String(t.path[o])):i),n=`${e.BASE}${s}`;return t.query?`${n}${Me(t.query)}`:n},Ue=e=>{if(e.formData){let t=new pe__default.default,r=(s,n)=>{F(n)||ce(n)?t.append(s,n):t.append(s,JSON.stringify(n));};return Object.entries(e.formData).filter(([s,n])=>ee(n)).forEach(([s,n])=>{Array.isArray(n)?n.forEach(i=>r(s,i)):r(s,n);}),t}},D=async(e,t)=>typeof t=="function"?t(e):t,ze=async(e,t,r)=>{let s=await D(t,e.TOKEN),n=await D(t,e.USERNAME),i=await D(t,e.PASSWORD),o=await D(t,e.HEADERS),d=typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...o,...t.headers,...d}).filter(([a,l])=>ee(l)).reduce((a,[l,u])=>({...a,[l]:String(u)}),{});if(Q(s)&&(p.Authorization=`Bearer ${s}`),Q(n)&&Q(i)){let a=He(`${n}:${i}`);p.Authorization=`Basic ${a}`;}return t.body&&(t.mediaType?p["Content-Type"]=t.mediaType:ce(t.body)?p["Content-Type"]=t.body.type||"application/octet-stream":F(t.body)?p["Content-Type"]="text/plain":Fe(t.body)||(p["Content-Type"]="application/json")),p},$e=e=>{if(e.body)return e.body},Ge=async(e,t,r,s,n,i,o)=>{let d=le__default.default.CancelToken.source(),p={url:r,headers:i,data:s??n,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:d.token};o(()=>d.cancel("The user aborted a request."));try{return await le__default.default.request(p)}catch(a){let l=a;if(l.response)return l.response;throw a}},je=(e,t)=>{if(t){let r=e.headers[t];if(F(r))return r}},We=e=>{if(e.status!==204)return e.data},Ke=(e,t)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(s)throw new T(e,t,s);if(!t.ok)throw new T(e,t,"Generic Error")},ue=(e,t)=>new L(async(r,s,n)=>{try{let i=Ve(e,t),o=Ue(t),d=$e(t),p=await ze(e,t,o);if(!n.isCancelled){let a=await Ge(e,t,i,d,o,p,n),l=We(a),u=je(a,t.responseHeader),c={url:i,ok:qe(a.status),status:a.status,statusText:a.statusText,body:u??l};Ke(t,c),r(c.body);}}catch(i){s(i);}});var q=class extends b{constructor(t){super(t);}request(t){return ue(this.config,t)}};var S=class{constructor(t){this.httpRequest=t;}cancelOrders({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",401:"Unauthorised Request (401)",404:"The specified resource was not found (404)",429:"Too Many Requests (429)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listListings({chainName:t,status:r,sellItemContractAddress:s,buyItemType:n,buyItemContractAddress:i,accountAddress:o,sellItemMetadataId:d,sellItemTokenId:p,fromUpdatedAt:a,pageSize:l,sortBy:u,sortDirection:c,pageCursor:m}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},query:{status:r,sell_item_contract_address:s,buy_item_type:n,buy_item_contract_address:i,account_address:o,sell_item_metadata_id:d,sell_item_token_id:p,from_updated_at:a,page_size:l,sort_by:u,sort_direction:c,page_cursor:m},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,buyItemMetadataId:o,buyItemTokenId:d,fromUpdatedAt:p,pageSize:a,sortBy:l,sortDirection:u,pageCursor:c}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,buy_item_metadata_id:o,buy_item_token_id:d,from_updated_at:p,page_size:a,sort_by:l,sort_direction:u,page_cursor:c},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listCollectionBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,fromUpdatedAt:o,pageSize:d,sortBy:p,sortDirection:a,pageCursor:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,from_updated_at:o,page_size:d,sort_by:p,sort_direction:a,page_cursor:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createCollectionBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}getListing({chainName:t,listingId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:t,listing_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getBid({chainName:t,bidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids/{bid_id}",path:{chain_name:t,bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getCollectionBid({chainName:t,collectionBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids/{collection_bid_id}",path:{chain_name:t,collection_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:t,accountAddress:r,sellItemContractAddress:s,fromIndexedAt:n,pageSize:i,sortBy:o,sortDirection:d,pageCursor:p}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:t},query:{account_address:r,sell_item_contract_address:s,from_indexed_at:n,page_size:i,sort_by:o,sort_direction:d,page_cursor:p},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:t,tradeId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:t,trade_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}};var P=class{orders;request;constructor(t,r=q){this.request=new r({BASE:t?.BASE??"https://api.immutable.com",VERSION:t?.VERSION??"1.0.0",WITH_CREDENTIALS:t?.WITH_CREDENTIALS??!1,CREDENTIALS:t?.CREDENTIALS??"include",TOKEN:t?.TOKEN,USERNAME:t?.USERNAME,PASSWORD:t?.PASSWORD,HEADERS:t?.HEADERS,ENCODE_PATH:t?.ENCODE_PATH}),this.orders=new S(this.request);}};var me;(t=>{(i=>(i.ON_CHAIN="ON_CHAIN",i.OFF_CHAIN="OFF_CHAIN",i.UNDERFUNDED="UNDERFUNDED"))(t.cancellation_type||={});})(me||={});var fe;(t=>{(s=>s.FILLED="FILLED")(t.reason_code||={});})(fe||={});var f;(t=>{(o=>(o.ROYALTY="ROYALTY",o.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",o.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",o.PROTOCOL="PROTOCOL"))(t.type||={});})(f||={});var R;(t=>{(i=>(i.LISTING="LISTING",i.BID="BID",i.COLLECTION_BID="COLLECTION_BID"))(t.type||={});})(R||={});var H=(o=>(o.PENDING="PENDING",o.ACTIVE="ACTIVE",o.INACTIVE="INACTIVE",o.FILLED="FILLED",o.EXPIRED="EXPIRED",o.CANCELLED="CANCELLED",o))(H||{});var y;(t=>{(n=>(n.FULL_RESTRICTED="FULL_RESTRICTED",n.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(t.order_type||={});})(y||={});function C(e){throw new Error("Unreachable")}function h(e){if(e.type!==R.type.LISTING)throw new Error("Order type must be LISTING");let t=e.sell.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Listing sell items must either ERC721 or ERC1155")}),r=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Listing buy items must be either NATIVE or ERC20")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function B(e){if(e.type!==R.type.BID)throw new Error("Order type must be BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Bid buy items must either ERC721 or ERC1155")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function x(e){if(e.type!==R.type.COLLECTION_BID)throw new Error("Order type must be COLLECTION_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function N(e){switch(e.type){case R.type.LISTING:return h(e);case R.type.BID:return B(e);case R.type.COLLECTION_BID:return x(e);default:return C(e.type)}}function te(e){let t=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Buy items must be NATIVE, ERC20, ERC721 or ERC1155")}),r=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Sell items must be ERC20, ERC721 or ERC1155")});return {id:e.id,orderId:e.order_id,buy:t,sell:r,buyerFees:e.buyer_fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),chain:e.chain,indexedAt:e.indexed_at,blockchainMetadata:{blockNumber:e.blockchain_metadata.block_number,logIndex:e.blockchain_metadata.log_index,transactionHash:e.blockchain_metadata.transaction_hash,transactionIndex:e.blockchain_metadata.transaction_index},buyerAddress:e.buyer_address,makerAddress:e.maker_address,sellerAddress:e.seller_address,takerAddress:e.taker_address}}function k(e){return {nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}var Ye=(n=>(n[n.MAKER_ECOSYSTEM=f.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",n[n.TAKER_ECOSYSTEM=f.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",n[n.PROTOCOL=f.type.PROTOCOL]="PROTOCOL",n[n.ROYALTY=f.type.ROYALTY]="ROYALTY",n))(Ye||{}),re=(r=>(r.TRANSACTION="TRANSACTION",r.SIGNABLE="SIGNABLE",r))(re||{}),Ce=(s=>(s.APPROVAL="APPROVAL",s.FULFILL_ORDER="FULFILL_ORDER",s.CANCEL="CANCEL",s))(Ce||{}),se=(s=>(s.CREATE_LISTING="CREATE_ORDER",s.CREATE_ORDER="CREATE_ORDER",s.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",s))(se||{});var oe="ImmutableSeaport",O="1.5",M={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]};var Je={integer:0,address:ethers.zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},ne=e=>e===void 0?!1:e!=null&&(["string","number"].includes(typeof e)&&BigInt(e)===0n||Array.isArray(e)&&e.every(ne)||typeof e=="object"&&Object.values(e).every(ne)||typeof e=="boolean"&&e===!1);function Ze(e){let[,t]=e.match(/^bytes(\d+)$/)??[];return t?ethers.zeroPadValue("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),Je[e])}var A=class e{constructor(t){this.types=t;for(let r in t){let s=this.getDefaultValue(r);if(this.defaultValues[r]=s,!ne(s))throw new Error(`Got non-empty value for type ${r} in default generator: ${s}`)}}defaultValues={};static from(t,r){let{defaultValues:s}=new e(t);return r?s[r]:s}getDefaultValue(t){if(this.defaultValues[t])return this.defaultValues[t];let r=Ze(t);if(r!==void 0)return r;let s=t.match(/^(.*)(\x5b(\d*)\x5d)$/);if(s){let i=s[1],o=parseInt(s[3]);if(o>0){let d=this.getDefaultValue(i);return Array(o).fill(d)}return []}let n=this.types[t];if(n)return n.reduce((i,{name:o,type:d})=>({...i,[o]:this.getDefaultValue(d)}),{});throw new Error(`unknown type: ${t}`)}};var tt=(e,t)=>Array(e).fill(0).map((r,s)=>t(s)),ie=(e,t)=>tt(Math.ceil(e.length/t),r=>e.slice(r*t,(r+1)*t)),ye=e=>ethers.toBeHex(e.toString("hex")),_=e=>Buffer.from(e.slice(2),"hex"),V=e=>_(ethers.keccak256(e)),rt=e=>V(ethers.concat(e)),w=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),ge=(e,t=!0)=>{if(e.length===0)throw new Error("empty tree");let s=[e.map(n=>{let i=Buffer.isBuffer(n)?n:_(n);return t?V(i):i})];for(;s[s.length-1].length>1;)s.push(st(s[s.length-1]));return s[s.length-1][0]},st=e=>ie(e,2).map(rt);var dt=(e,t)=>new merkletreejs.MerkleTree(e.map(_),V,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:_(t)}),lt=(e,t,r=`0x${"ff".repeat(64)}`)=>ethers.concat([r,`0x${e.toString(16).padStart(6,"0")}`,ethers.AbiCoder.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]),U=class{constructor(t,r,s,n,i){this.types=t;this.rootType=r;this.leafType=s;this.elements=n;this.depth=i;let o=ethers.TypedDataEncoder.from(t);this.encoder=o,this.leafHasher=d=>o.hashStruct(s,d),this.defaultNode=A.from(t,s),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=dt(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:t}=this;return w([...t],this.completedSize,this.defaultNode)}getCompleteLeaves(){let t=this.elements.map(this.leafHasher);return w([...t],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(t){let s=this.getCompleteLeaves()[t],n=this.tree.getHexProof(s,t),i=this.tree.getHexRoot();return {leaf:s,proof:n,root:i}}getEncodedProofAndSignature(t,r){let{proof:s}=this.getProof(t);return lt(t,s,r)}getDataToSign(){let t=this.getCompleteElements();for(;t.length>2;)t=ie(t,2);return t}add(t){this.elements.push(t);}getBulkOrderHash(){let t=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),r=this.getCompleteLeaves().map(_),s=ye(ge(r,!1)),n=ethers.keccak256(ethers.toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(ethers.keccak256(ethers.concat([n,s]))!==t)throw new Error("expected derived bulk order hash to match");return t}};function pt(e){return {...M,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}function ct(e){return Math.max(Math.ceil(Math.log2(e)),1)}function Oe(e,t=0,r=ct(e.length+t)){let s=pt(r),n=A.from(s,"OrderComponents"),i=[...e];return t>0&&(i=[...w([],t,n),...e]),new U(s,"BulkOrder","OrderComponents",i,r)}function Ae(e){if([0,1,2,3].includes(Number(e)))return Number(e);throw new Error(`Unknown order type ${e}`)}function z(e){if([0,1,2,3,4,5].includes(Number(e)))return Number(e);throw new Error(`Unknown item type ${e}`)}function _e(e){let r=JSON.parse(e).message;return {...r,orderType:Ae(r.orderType),salt:ethers.toBeHex(BigInt(r.salt)),offer:r.offer.map(s=>({...s,itemType:z(s.itemType)})),consideration:r.consideration.map(s=>({...s,itemType:z(s.itemType)}))}}function be(e){let t=JSON.parse(e);return {components:t.message.tree.flat(1/0).filter(s=>s.offerer!=="0x0000000000000000000000000000000000000000").map(s=>({...s,orderType:Ae(s.orderType),salt:ethers.toBeHex(BigInt(s.salt)),offer:s.offer.map(n=>({...n,itemType:z(n.itemType)})),consideration:s.consideration.map(n=>({...n,itemType:z(n.itemType)}))})),types:t.types,value:t.message}}function Le(e,t){let r=Oe(t);return t.map((s,n)=>r.getEncodedProofAndSignature(n,e))}function mt(e){switch(e.type){case"NATIVE":throw new Error("NATIVE items are not supported in the offer");case"ERC20":return {itemType:1 .valueOf(),token:e.contract_address,identifierOrCriteria:"0",startAmount:e.amount,endAmount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:"1",endAmount:"1"};case"ERC1155":return {itemType:3 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:e.amount,endAmount:e.amount};case"ERC721_COLLECTION":throw new Error("ERC721_COLLECTION items are not supported in the offer");case"ERC1155_COLLECTION":throw new Error("ERC1155_COLLECTION items are not supported in the offer");default:return C()}}function ft(e,t){switch(e.type){case"NATIVE":return {itemType:0 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:ethers.ZeroAddress,identifierOrCriteria:"0",recipient:t};case"ERC20":return {itemType:1 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC721":return {itemType:2 .valueOf(),startAmount:"1",endAmount:"1",token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC721_COLLECTION":return {itemType:4 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC1155_COLLECTION":return {itemType:5 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};default:return C()}}function G(e){let t=e.sell.map(mt),r=e.buy.map(o=>ft(o,e.account_address)),s=function(o){switch(o){case R.type.LISTING:return r[0];case R.type.BID:case R.type.COLLECTION_BID:return t[0];default:return C()}}(e.type),n=function(o){switch(o){case y.order_type.FULL_RESTRICTED:return 2;case y.order_type.PARTIAL_RESTRICTED:return 3;default:return C()}}(e.protocol_data.order_type),i=e.fees.map(o=>({amount:o.amount,itemType:s.itemType,recipient:o.recipient_address,token:s.token,identifierOrCriteria:s.identifierOrCriteria}));return {orderComponents:{offerer:e.account_address,zone:e.protocol_data.zone_address,offer:t,consideration:r,orderType:n.valueOf(),startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),zoneHash:ethers.ZeroHash,salt:e.salt,conduitKey:ethers.ZeroHash,counter:e.protocol_data.counter,totalOriginalConsiderationItems:r.length},tips:i}}function g(e,t,r){return async()=>{let s=await e.buildTransaction(),n={to:s.to,from:r,type:s.type,maxFeePerGas:s.maxFeePerGas?BigInt(s.maxFeePerGas):void 0,maxPriorityFeePerGas:s.maxPriorityFeePerGas?BigInt(s.maxPriorityFeePerGas):void 0,value:s.value?BigInt(s.value):void 0,data:s.data,nonce:s.nonce,chainId:t};return n.gasLimit=BigInt(await e.estimateGas()),n.gasLimit+=n.gasLimit/BigInt(5),n}}function Pe(e){switch(e.type){case"ERC20":return {token:e.contractAddress,amount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount};default:return C()}}function Be(e,t){switch(e.type){case"NATIVE":return {amount:e.amount,recipient:t};case"ERC20":return {token:e.contractAddress,amount:e.amount,recipient:t};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount,recipient:t};case"ERC721_COLLECTION":return {itemType:2 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};case"ERC1155_COLLECTION":return {itemType:3 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};default:return C()}}var j=class e{constructor(t,r,s,n,i){this.seaportLibFactory=t;this.provider=r;this.seaportContractAddress=s;this.zoneContractAddress=n;this.rateLimitingKey=i;}async prepareBulkSeaportOrders(t,r){let{actions:s}=await this.createSeaportOrders(t,r),n=s.filter(c=>c.type==="approval"),i=await this.provider.getNetwork(),o=n.map(c=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(c.transactionMethods,i.chainId,t)})),d=s.find(c=>c.type==="createBulk");if(!d)throw new Error("No create bulk order action found");let p=await d.getMessageToSign(),{components:a,types:l,value:u}=be(p);return o.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(l,u)}),{actions:o,preparedOrders:a.map(c=>({orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}))}}async prepareSeaportOrder(t,r,s,n,i,o){let{actions:d}=await this.createSeaportOrder(t,r,s,n,i,o),p=[],a=d.find(m=>m.type==="approval");a&&p.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(a.transactionMethods,(await this.provider.getNetwork()).chainId,t)});let l=d.find(m=>m.type==="create");if(!l)throw new Error("No create order action found");let u=await l.getMessageToSign(),c=_e(u);return p.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromOrderComponents(c)}),{actions:p,orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}}async fulfillOrder(t,r,s,n,i){let{orderComponents:o,tips:d}=G(t),p=this.getSeaportLib(t),a=(await this.provider.getNetwork()).chainId,l={order:{parameters:o,signature:t.signature},unitsToFill:n,extraData:s,tips:d};i&&(l.considerationCriteria=i);let{actions:u}=await p.fulfillOrders({accountAddress:r,fulfillOrderDetails:[l]}),c=[],m=u.filter(E=>E.type==="approval");m.length>0&&m.forEach(E=>{c.push({type:"TRANSACTION",buildTransaction:g(E.transactionMethods,a,r),purpose:"APPROVAL"});});let I=u.find(E=>E.type==="exchange");if(!I)throw new Error("No exchange action found");return c.push({type:"TRANSACTION",buildTransaction:g(I.transactionMethods,a,r),purpose:"FULFILL_ORDER"}),{actions:c,expiration:e.getExpirationISOTimeFromExtraData(s),order:N(t)}}async fulfillBulkOrders(t,r){let s=t.map(a=>{let{orderComponents:l,tips:u}=G(a.order),c={order:{parameters:l,signature:a.order.signature},unitsToFill:a.unitsToFill,extraData:a.extraData,tips:u};return a.considerationCriteria&&a.considerationCriteria.length>0&&(c.considerationCriteria=a.considerationCriteria),c}),{actions:n}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:s,accountAddress:r}),i=[],o=n.filter(a=>a.type==="approval"),d=(await this.provider.getNetwork()).chainId;o.length>0&&o.forEach(a=>{i.push({type:"TRANSACTION",buildTransaction:g(a.transactionMethods,d,r),purpose:"APPROVAL"});});let p=n.find(a=>a.type==="exchange");if(!p)throw new Error("No exchange action found");return i.push({type:"TRANSACTION",buildTransaction:g(p.transactionMethods,(await this.provider.getNetwork()).chainId,r),purpose:"FULFILL_ORDER"}),{actions:i,expiration:s.map(a=>e.getExpirationISOTimeFromExtraData(a.extraData)).reduce((a,l)=>new Date(a)<new Date(l)?a:l)}}async cancelOrders(t,r){let s=t.map(o=>G(o).orderComponents),i=await this.getSeaportLib(t[0]).cancelOrders(s,r);return {type:"TRANSACTION",buildTransaction:g(i,(await this.provider.getNetwork()).chainId,r),purpose:"CANCEL"}}createSeaportOrders(t,r){return this.getSeaportLib().createBulkOrders(r.map(n=>{let{offerItem:i,considerationItem:o,allowPartialFills:d,orderStart:p,orderExpiry:a}=n;return {allowPartialFills:d,offer:[Pe(i)],consideration:[Be(o,t)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(a.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),t)}createSeaportOrder(t,r,s,n,i,o){return this.getSeaportLib().createOrder({allowPartialFills:n,offer:[Pe(r)],consideration:[Be(s,t)],startTime:(i.getTime()/1e3).toFixed(0),endTime:(o.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},t)}async getTypedDataFromBulkOrderComponents(t,r){delete t.EIP712Domain;let{chainId:s}=await this.provider.getNetwork();return {domain:{name:oe,version:O,chainId:s,verifyingContract:this.seaportContractAddress},types:t,value:r}}async getTypedDataFromOrderComponents(t){let{chainId:r}=await this.provider.getNetwork();return {domain:{name:oe,version:O,chainId:r,verifyingContract:this.seaportContractAddress},types:M,value:t}}getSeaportLib(t){let r=t?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(r)}static getExpirationISOTimeFromExtraData(t){let r=t.slice(44,60),s=parseInt(r,16);return new Date(s*1e3).toISOString()}};function W(e){switch(e.itemType){case 0:return {type:"NATIVE",amount:e.startAmount};case 1:return {type:"ERC20",contract_address:e.token,amount:e.startAmount};case 2:return {type:"ERC721",contract_address:e.token,token_id:e.identifierOrCriteria};case 3:return {type:"ERC1155",contract_address:e.token,token_id:e.identifierOrCriteria,amount:e.startAmount};case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};default:return C(e.itemType)}}function ae(e){if(e.itemType!==1)throw new Error(`Expected ERC20 item, got ${e.itemType}`);return {type:"ERC20",contract_address:e.token,amount:e.startAmount}}function xe(e){switch(e.itemType){case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};case 1:case 0:case 2:case 3:throw new Error(`Unsupported item type ${e.itemType}`);default:return C(e.itemType)}}function K(e){switch(e){case 2:return y.order_type.FULL_RESTRICTED;case 3:return y.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${e}`);default:return C()}}var Y=class{constructor(t,r,s){this.orderbookService=t;this.chainName=r;this.seaportAddress=s;}async fulfillmentData(t){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:t})}async getListing(t){return this.orderbookService.getListing({chainName:this.chainName,listingId:t})}async getBid(t){return this.orderbookService.getBid({chainName:this.chainName,bidId:t})}async getCollectionBid(t){return this.orderbookService.getCollectionBid({chainName:this.chainName,collectionBidId:t})}async getTrade(t){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:t})}async listListings(t){return this.orderbookService.listListings({chainName:this.chainName,...t})}async listBids(t){return this.orderbookService.listBids({chainName:this.chainName,...t})}async listCollectionBids(t){return this.orderbookService.listCollectionBids({chainName:this.chainName,...t})}async listTrades(t){return this.orderbookService.listTrades({chainName:this.chainName,...t})}async cancelOrders(t,r,s){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:r,orders:t,signature:s}})}async createListing({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a listing");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a listing");if(![2,3].includes(r.offer[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be listed");if(![0,1].includes(r.consideration[0].itemType))throw new Error("Only Native / ERC20 tokens can be used as currency items in a listing");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(W),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a bid");if(![2,3].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be bid against");return this.orderbookService.createBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a collection bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a collection bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a collection bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");return this.orderbookService.createCollectionBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(xe),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}};var J=class{constructor(t,r,s,n){this.chainName=r;this.seaportAddress=s;this.orderbookClient=new P({BASE:t,HEADERS:n?{"x-api-key":n}:void 0});}orderbookClient;create(){return new Y(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var yt="imtbl-zkevm-testnet",gt="imtbl-zkevm-mainnet";function Z(e,t){let r=new ethers.FetchRequest(e);return t&&r.setHeader("x-api-key",t),new ethers.JsonRpcProvider(r)}function ke(e){switch(e.baseConfig.environment){case config.Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:yt,provider:Z("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case config.Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:gt,provider:Z("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}var X=class{constructor(t,r){this.defaultSeaportContractAddress=t;this.provider=r;}create(t){let r=t??this.defaultSeaportContractAddress,s=this.provider;return s.getSigner=async function(i){i==null&&(i=0);let o=this.send("eth_accounts",[]);if(typeof i=="number"){let d=await o;if(i>=d.length)throw new Error("no such account");return new ethers.JsonRpcSigner(this,d[i])}return new ethers.JsonRpcSigner(this,i)},new seaportJs.Seaport(s,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}};var de=class e{apiClient;seaport;orderbookConfig;constructor(t){let s={...ke(t),...t.overrides};if(t.overrides?.jsonRpcProviderUrl&&(s.provider=Z(t.overrides?.jsonRpcProviderUrl,t.baseConfig.rateLimitingKey)),!s)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=s;let{apiEndpoint:n,chainName:i}=this.orderbookConfig;if(!n)throw new Error("API endpoint must be provided");this.apiClient=new J(n,i,this.orderbookConfig.seaportContractAddress,t.baseConfig.rateLimitingKey).create();let o=new X(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new j(o,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,t.baseConfig.rateLimitingKey);}static defaultOrderExpiry(){return new Date(Date.now()+1e3*60*60*24*365*2)}config(){return this.orderbookConfig}async getListing(t){let r=await this.apiClient.getListing(t);return {result:h(r.result)}}async getBid(t){let r=await this.apiClient.getBid(t);return {result:B(r.result)}}async getCollectionBid(t){let r=await this.apiClient.getCollectionBid(t);return {result:x(r.result)}}async getTrade(t){let r=await this.apiClient.getTrade(t);return {result:te(r.result)}}async listListings(t){let r=await this.apiClient.listListings(t);return {page:k(r.page),result:r.result.map(h)}}async listBids(t){let r=await this.apiClient.listBids(t);return {page:k(r.page),result:r.result.map(B)}}async listCollectionBids(t){let r=await this.apiClient.listCollectionBids(t);return {page:k(r.page),result:r.result.map(x)}}async listTrades(t){let r=await this.apiClient.listTrades(t);return {page:k(r.page),result:r.result.map(te)}}async prepareBulkListings({makerAddress:t,listingParams:r}){if(r.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(r.length===1){let o=await this.seaport.prepareSeaportOrder(t,r[0].sell,r[0].buy,r[0].sell.type==="ERC1155",r[0].orderStart||new Date,r[0].orderExpiry||e.defaultOrderExpiry());return {actions:o.actions,completeListings:async d=>{let p=await this.createListing({makerFees:r[0].makerFees,orderComponents:o.orderComponents,orderHash:o.orderHash,orderSignature:typeof d=="string"?d:d[0]});return {result:[{success:!0,orderHash:o.orderHash,order:p.result}]}}}}if(await this.orderbookConfig.provider.getCode(t)!=="0x"){metrics.track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:t,listingsCount:r.length});let o=await Promise.all(r.map(a=>this.seaport.prepareSeaportOrder(t,a.sell,a.buy,a.sell.type==="ERC1155",a.orderStart||new Date,a.orderExpiry||e.defaultOrderExpiry()))),d=[];return {actions:o.flatMap(a=>{let l=[];return a.actions.forEach(u=>{if(u.type==="TRANSACTION"){let c=a.orderComponents.offer[0].token;d.includes(c)||(d.push(c),l.push(u));}else l.push(u);}),l}),completeListings:async a=>{if(typeof a=="string")throw new Error("A signature per listing must be provided for smart contract wallets");return {result:(await Promise.all(o.map((c,m)=>{let I=a[m];return this.apiClient.createListing({makerFees:r[m].makerFees,orderComponents:c.orderComponents,orderHash:c.orderHash,orderSignature:I}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:o[m].orderHash,order:c?h(c.result):void 0}))}}}}metrics.track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:t,listingsCount:r.length});let{actions:n,preparedOrders:i}=await this.seaport.prepareBulkSeaportOrders(t,r.map(o=>({offerItem:o.sell,considerationItem:o.buy,allowPartialFills:o.sell.type==="ERC1155",orderStart:o.orderStart||new Date,orderExpiry:o.orderExpiry||e.defaultOrderExpiry()})));return {actions:n,completeListings:async o=>{let d=typeof o=="object";if(d&&o.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let p=i.map(c=>c.orderComponents),a=d?o[0]:o,l=Le(a,p);return {result:(await Promise.all(p.map((c,m)=>{let I=l[m],E=i[m],De=r[m];return this.apiClient.createListing({orderComponents:c,orderHash:E.orderHash,orderSignature:I,makerFees:De.makerFees}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:i[m].orderHash,order:c?h(c.result):void 0}))}}}}async prepareListing({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,r.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createListing(t){let r=await this.apiClient.createListing(t);return {result:h(r.result)}}async prepareBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,s.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createBid(t){let r=await this.apiClient.createBid(t);return {result:B(r.result)}}async prepareCollectionBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,!0,n||new Date,i||e.defaultOrderExpiry())}async createCollectionBid(t){let r=await this.apiClient.createCollectionBid(t);return {result:x(r.result)}}async fulfillOrder(t,r,s,n,i){let o={order_id:t,taker_address:r,fees:s.map(u=>({type:f.type.TAKER_ECOSYSTEM,amount:u.amount,recipient_address:u.recipientAddress}))},d=i?[{identifier:i,proof:[]}]:void 0;i&&(o.token_id=i);let p=await this.apiClient.fulfillmentData([o]);if(p.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment data: ${p.result.unfulfillable_orders[0].reason}`);if(p.result.fulfillable_orders?.length!==1)throw new Error("unexpected fulfillable order result length");let a=p.result.fulfillable_orders[0].extra_data,l=p.result.fulfillable_orders[0].order;if(l.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${l.status}`);return this.seaport.fulfillOrder(l,r,a,n,d)}async fulfillBulkOrders(t,r){let s=t.map(i=>{let o="listingId"in i;return {orderId:o?i.listingId:i.orderId,takerFees:i.takerFees,amountToFill:i.amountToFill,tokenId:o?void 0:i.tokenId}}),n=await this.apiClient.fulfillmentData(s.map(i=>({order_id:i.orderId,taker_address:r,fees:i.takerFees.map(o=>({type:f.type.TAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),token_id:i?.tokenId})));try{let i=n.result.fulfillable_orders.map(o=>{let d=s.find(a=>a.orderId===o.order.id&&a.tokenId===o.token_id);if(!d){let a=`Could not find order for order ${o.order.id}`;throw o.token_id&&(a+=` and token ID ${o.token_id}`),new Error(a)}let p=[];return d.tokenId&&p.push({identifier:d.tokenId,proof:[]}),{extraData:o.extra_data,order:o.order,unitsToFill:d.amountToFill,considerationCriteria:p}});return {...await this.seaport.fulfillBulkOrders(i,r),fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,tokenId:o.token_id,reason:o.reason})),sufficientBalance:!0}}catch(i){if(String(i).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,reason:o.reason})),sufficientBalance:!1};throw i}}async prepareOrderCancellations(t){let r=await this.orderbookConfig.provider.getNetwork(),s={name:"imtbl-order-book",chainId:Number(r.chainId),verifyingContract:this.orderbookConfig.seaportContractAddress},n={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},i={orders:t.map(o=>({id:o}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:s,types:n,value:i}}}}async cancelOrders(t,r,s){return this.apiClient.cancelOrders(t,r,s)}async cancelOrdersOnChain(t,r){let s=Promise.all(t.map(l=>this.apiClient.getListing(l).catch(u=>{if(u.status!==404)throw u}))),n=Promise.all(t.map(l=>this.apiClient.getBid(l).catch(u=>{if(u.status!==404)throw u}))),i=Promise.all(t.map(l=>this.apiClient.getCollectionBid(l).catch(u=>{if(u.status!==404)throw u}))),o=[await Promise.all([s,n,i])].flat(2).filter(l=>l!==void 0).map(l=>l.result);if(o.length!==t.length){let l=t.filter(u=>!o.some(c=>c.id===u));throw new Error(`Orders ${l} not found`)}for(let l of o)if(l.account_address!==r.toLowerCase())throw new Error(`Only account ${l.account_address} can cancel order ${l.id}`);let d=o.map(l=>l.protocol_data.seaport_address);if(new Set(d).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(o,r)}}};var ht={estimatedFulfillmentGasGwei:4e5};
16
+ var B=class{constructor(t){this.config=t;}};var I=class extends Error{url;status;statusText;body;request;constructor(t,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=t;}};var F=class extends Error{constructor(t){super(t),this.name="CancelError";}get isCancelled(){return !0}},L=class{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(t){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((r,s)=>{this._resolve=r,this._reject=s;let o=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(d));},a=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(d));},i=d=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(d);};return Object.defineProperty(i,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(i,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(i,"isCancelled",{get:()=>this._isCancelled}),t(o,a,i)});}then(t,r){return this._promise.then(t,r)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let t of this._cancelHandlers)t();}catch(t){console.warn("Cancellation threw an error",t);return}this._cancelHandlers.length=0,this._reject?.(new F("Request aborted"));}}get isCancelled(){return this._isCancelled}};var re=e=>e!=null,H=e=>typeof e=="string",te=e=>H(e)&&e!=="",me=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),qe=e=>e instanceof ue__default.default,He=e=>e>=200&&e<300,Me=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Ve=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`);},s=(o,a)=>{re(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i);}):typeof a=="object"?Object.entries(a).forEach(([i,d])=>{s(`${o}[${i}]`,d);}):r(o,a));};return Object.entries(e).forEach(([o,a])=>{s(o,a);}),t.length>0?`?${t.join("&")}`:""},Ue=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${Ve(t.query)}`:o},ze=e=>{if(e.formData){let t=new ue__default.default,r=(s,o)=>{H(o)||me(o)?t.append(s,o):t.append(s,JSON.stringify(o));};return Object.entries(e.formData).filter(([s,o])=>re(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o);}),t}},q=async(e,t)=>typeof t=="function"?t(e):t,$e=async(e,t,r)=>{let s=await q(t,e.TOKEN),o=await q(t,e.USERNAME),a=await q(t,e.PASSWORD),i=await q(t,e.HEADERS),d=typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...i,...t.headers,...d}).filter(([n,u])=>re(u)).reduce((n,[u,c])=>({...n,[u]:String(c)}),{});if(te(s)&&(p.Authorization=`Bearer ${s}`),te(o)&&te(a)){let n=Me(`${o}:${a}`);p.Authorization=`Basic ${n}`;}return t.body&&(t.mediaType?p["Content-Type"]=t.mediaType:me(t.body)?p["Content-Type"]=t.body.type||"application/octet-stream":H(t.body)?p["Content-Type"]="text/plain":qe(t.body)||(p["Content-Type"]="application/json")),p},Ge=e=>{if(e.body)return e.body},je=async(e,t,r,s,o,a,i)=>{let d=ce__default.default.CancelToken.source(),p={url:r,headers:a,data:s??o,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:d.token};i(()=>d.cancel("The user aborted a request."));try{return await ce__default.default.request(p)}catch(n){let u=n;if(u.response)return u.response;throw n}},We=(e,t)=>{if(t){let r=e.headers[t];if(H(r))return r}},Ke=e=>{if(e.status!==204)return e.data},Ye=(e,t)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(s)throw new I(e,t,s);if(!t.ok)throw new I(e,t,"Generic Error")},fe=(e,t)=>new L(async(r,s,o)=>{try{let a=Ue(e,t),i=ze(t),d=Ge(t),p=await $e(e,t,i);if(!o.isCancelled){let n=await je(e,t,a,d,i,p,o),u=Ke(n),c=We(n,t.responseHeader),l={url:a,ok:He(n.status),status:n.status,statusText:n.statusText,body:c??u};Ye(t,l),r(l.body);}}catch(a){s(a);}});var M=class extends B{constructor(t){super(t);}request(t){return fe(this.config,t)}};var P=class{constructor(t){this.httpRequest=t;}cancelOrders({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",401:"Unauthorised Request (401)",404:"The specified resource was not found (404)",429:"Too Many Requests (429)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listListings({chainName:t,status:r,sellItemContractAddress:s,buyItemType:o,buyItemContractAddress:a,accountAddress:i,sellItemMetadataId:d,sellItemTokenId:p,fromUpdatedAt:n,pageSize:u,sortBy:c,sortDirection:l,pageCursor:m}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},query:{status:r,sell_item_contract_address:s,buy_item_type:o,buy_item_contract_address:a,account_address:i,sell_item_metadata_id:d,sell_item_token_id:p,from_updated_at:n,page_size:u,sort_by:c,sort_direction:l,page_cursor:m},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:o,accountAddress:a,buyItemMetadataId:i,buyItemTokenId:d,fromUpdatedAt:p,pageSize:n,sortBy:u,sortDirection:c,pageCursor:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:o,account_address:a,buy_item_metadata_id:i,buy_item_token_id:d,from_updated_at:p,page_size:n,sort_by:u,sort_direction:c,page_cursor:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listCollectionBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:o,accountAddress:a,fromUpdatedAt:i,pageSize:d,sortBy:p,sortDirection:n,pageCursor:u}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:o,account_address:a,from_updated_at:i,page_size:d,sort_by:p,sort_direction:n,page_cursor:u},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createCollectionBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listTraitBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:o,accountAddress:a,fromUpdatedAt:i,pageSize:d,sortBy:p,sortDirection:n,pageCursor:u}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/trait-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:o,account_address:a,from_updated_at:i,page_size:d,sort_by:p,sort_direction:n,page_cursor:u},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createTraitBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/trait-bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}getListing({chainName:t,listingId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:t,listing_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getBid({chainName:t,bidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids/{bid_id}",path:{chain_name:t,bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getCollectionBid({chainName:t,collectionBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids/{collection_bid_id}",path:{chain_name:t,collection_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTraitBid({chainName:t,traitBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/trait-bids/{trait_bid_id}",path:{chain_name:t,trait_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:t,accountAddress:r,sellItemContractAddress:s,fromIndexedAt:o,pageSize:a,sortBy:i,sortDirection:d,pageCursor:p}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:t},query:{account_address:r,sell_item_contract_address:s,from_indexed_at:o,page_size:a,sort_by:i,sort_direction:d,page_cursor:p},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:t,tradeId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:t,trade_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}};var S=class{orders;request;constructor(t,r=M){this.request=new r({BASE:t?.BASE??"https://api.immutable.com",VERSION:t?.VERSION??"1.0.0",WITH_CREDENTIALS:t?.WITH_CREDENTIALS??!1,CREDENTIALS:t?.CREDENTIALS??"include",TOKEN:t?.TOKEN,USERNAME:t?.USERNAME,PASSWORD:t?.PASSWORD,HEADERS:t?.HEADERS,ENCODE_PATH:t?.ENCODE_PATH}),this.orders=new P(this.request);}};var Ce;(t=>{(a=>(a.ON_CHAIN="ON_CHAIN",a.OFF_CHAIN="OFF_CHAIN",a.UNDERFUNDED="UNDERFUNDED"))(t.cancellation_type||={});})(Ce||={});var Re;(t=>{(s=>s.FILLED="FILLED")(t.reason_code||={});})(Re||={});var C;(t=>{(i=>(i.ROYALTY="ROYALTY",i.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",i.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",i.PROTOCOL="PROTOCOL"))(t.type||={});})(C||={});var f;(t=>{(i=>(i.LISTING="LISTING",i.BID="BID",i.COLLECTION_BID="COLLECTION_BID",i.TRAIT_BID="TRAIT_BID"))(t.type||={});})(f||={});var V=(i=>(i.PENDING="PENDING",i.ACTIVE="ACTIVE",i.INACTIVE="INACTIVE",i.FILLED="FILLED",i.EXPIRED="EXPIRED",i.CANCELLED="CANCELLED",i))(V||{});var y;(t=>{(o=>(o.FULL_RESTRICTED="FULL_RESTRICTED",o.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(t.order_type||={});})(y||={});function R(e){throw new Error("Unreachable")}function T(e){if(e.type!==f.type.LISTING)throw new Error("Order type must be LISTING");let t=e.sell.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Listing sell items must either ERC721 or ERC1155")}),r=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Listing buy items must be either NATIVE or ERC20")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function x(e){if(e.type!==f.type.BID)throw new Error("Order type must be BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Bid buy items must either ERC721 or ERC1155")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function Je(e){return e?.length?e.map(t=>({traitType:t.trait_type,values:[...t.values]})):[]}function N(e){if(e.type!==f.type.COLLECTION_BID)throw new Error("Order type must be COLLECTION_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function w(e){if(e.type!==f.type.TRAIT_BID)throw new Error("Order type must be TRAIT_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Trait bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:s.contract_address,amount:s.amount};throw new Error("Trait bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at,traitCriteria:Je(e.trait_criteria)}}function k(e){switch(e.type){case f.type.LISTING:return T(e);case f.type.BID:return x(e);case f.type.COLLECTION_BID:return N(e);case f.type.TRAIT_BID:return w(e);default:return R(e.type)}}function se(e){let t=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Buy items must be NATIVE, ERC20, ERC721 or ERC1155")}),r=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Sell items must be ERC20, ERC721 or ERC1155")});return {id:e.id,orderId:e.order_id,buy:t,sell:r,buyerFees:e.buyer_fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),chain:e.chain,indexedAt:e.indexed_at,blockchainMetadata:{blockNumber:e.blockchain_metadata.block_number,logIndex:e.blockchain_metadata.log_index,transactionHash:e.blockchain_metadata.transaction_hash,transactionIndex:e.blockchain_metadata.transaction_index},buyerAddress:e.buyer_address,makerAddress:e.maker_address,sellerAddress:e.seller_address,takerAddress:e.taker_address}}function _(e){return {nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}var Ze=(o=>(o[o.MAKER_ECOSYSTEM=C.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",o[o.TAKER_ECOSYSTEM=C.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",o[o.PROTOCOL=C.type.PROTOCOL]="PROTOCOL",o[o.ROYALTY=C.type.ROYALTY]="ROYALTY",o))(Ze||{}),ie=(r=>(r.TRANSACTION="TRANSACTION",r.SIGNABLE="SIGNABLE",r))(ie||{}),ye=(s=>(s.APPROVAL="APPROVAL",s.FULFILL_ORDER="FULFILL_ORDER",s.CANCEL="CANCEL",s))(ye||{}),oe=(s=>(s.CREATE_LISTING="CREATE_ORDER",s.CREATE_ORDER="CREATE_ORDER",s.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",s))(oe||{});var ae="ImmutableSeaport",g="1.5",U={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]};var Xe={integer:0,address:ethers.zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},ne=e=>e===void 0?!1:e!=null&&(["string","number"].includes(typeof e)&&BigInt(e)===0n||Array.isArray(e)&&e.every(ne)||typeof e=="object"&&Object.values(e).every(ne)||typeof e=="boolean"&&e===!1);function Qe(e){let[,t]=e.match(/^bytes(\d+)$/)??[];return t?ethers.zeroPadValue("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),Xe[e])}var A=class e{constructor(t){this.types=t;for(let r in t){let s=this.getDefaultValue(r);if(this.defaultValues[r]=s,!ne(s))throw new Error(`Got non-empty value for type ${r} in default generator: ${s}`)}}defaultValues={};static from(t,r){let{defaultValues:s}=new e(t);return r?s[r]:s}getDefaultValue(t){if(this.defaultValues[t])return this.defaultValues[t];let r=Qe(t);if(r!==void 0)return r;let s=t.match(/^(.*)(\x5b(\d*)\x5d)$/);if(s){let a=s[1],i=parseInt(s[3]);if(i>0){let d=this.getDefaultValue(a);return Array(i).fill(d)}return []}let o=this.types[t];if(o)return o.reduce((a,{name:i,type:d})=>({...a,[i]:this.getDefaultValue(d)}),{});throw new Error(`unknown type: ${t}`)}};var st=(e,t)=>Array(e).fill(0).map((r,s)=>t(s)),de=(e,t)=>st(Math.ceil(e.length/t),r=>e.slice(r*t,(r+1)*t)),he=e=>ethers.toBeHex(e.toString("hex")),b=e=>Buffer.from(e.slice(2),"hex"),z=e=>b(ethers.keccak256(e)),it=e=>z(ethers.concat(e)),v=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),Ee=(e,t=!0)=>{if(e.length===0)throw new Error("empty tree");let s=[e.map(o=>{let a=Buffer.isBuffer(o)?o:b(o);return t?z(a):a})];for(;s[s.length-1].length>1;)s.push(ot(s[s.length-1]));return s[s.length-1][0]},ot=e=>de(e,2).map(it);var pt=(e,t)=>new merkletreejs.MerkleTree(e.map(b),z,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:b(t)}),ct=(e,t,r=`0x${"ff".repeat(64)}`)=>ethers.concat([r,`0x${e.toString(16).padStart(6,"0")}`,ethers.AbiCoder.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]),$=class{constructor(t,r,s,o,a){this.types=t;this.rootType=r;this.leafType=s;this.elements=o;this.depth=a;let i=ethers.TypedDataEncoder.from(t);this.encoder=i,this.leafHasher=d=>i.hashStruct(s,d),this.defaultNode=A.from(t,s),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=pt(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:t}=this;return v([...t],this.completedSize,this.defaultNode)}getCompleteLeaves(){let t=this.elements.map(this.leafHasher);return v([...t],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(t){let s=this.getCompleteLeaves()[t],o=this.tree.getHexProof(s,t),a=this.tree.getHexRoot();return {leaf:s,proof:o,root:a}}getEncodedProofAndSignature(t,r){let{proof:s}=this.getProof(t);return ct(t,s,r)}getDataToSign(){let t=this.getCompleteElements();for(;t.length>2;)t=de(t,2);return t}add(t){this.elements.push(t);}getBulkOrderHash(){let t=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),r=this.getCompleteLeaves().map(b),s=he(Ee(r,!1)),o=ethers.keccak256(ethers.toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(ethers.keccak256(ethers.concat([o,s]))!==t)throw new Error("expected derived bulk order hash to match");return t}};function ut(e){return {...U,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}function mt(e){return Math.max(Math.ceil(Math.log2(e)),1)}function Ie(e,t=0,r=mt(e.length+t)){let s=ut(r),o=A.from(s,"OrderComponents"),a=[...e];return t>0&&(a=[...v([],t,o),...e]),new $(s,"BulkOrder","OrderComponents",a,r)}function be(e){if([0,1,2,3].includes(Number(e)))return Number(e);throw new Error(`Unknown order type ${e}`)}function G(e){if([0,1,2,3,4,5].includes(Number(e)))return Number(e);throw new Error(`Unknown item type ${e}`)}function Be(e){let r=JSON.parse(e).message;return {...r,orderType:be(r.orderType),salt:ethers.toBeHex(BigInt(r.salt)),offer:r.offer.map(s=>({...s,itemType:G(s.itemType)})),consideration:r.consideration.map(s=>({...s,itemType:G(s.itemType)}))}}function Le(e){let t=JSON.parse(e);return {components:t.message.tree.flat(1/0).filter(s=>s.offerer!=="0x0000000000000000000000000000000000000000").map(s=>({...s,orderType:be(s.orderType),salt:ethers.toBeHex(BigInt(s.salt)),offer:s.offer.map(o=>({...o,itemType:G(o.itemType)})),consideration:s.consideration.map(o=>({...o,itemType:G(o.itemType)}))})),types:t.types,value:t.message}}function Pe(e,t){let r=Ie(t);return t.map((s,o)=>r.getEncodedProofAndSignature(o,e))}function Ct(e){switch(e.type){case"NATIVE":throw new Error("NATIVE items are not supported in the offer");case"ERC20":return {itemType:1 .valueOf(),token:e.contract_address,identifierOrCriteria:"0",startAmount:e.amount,endAmount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:"1",endAmount:"1"};case"ERC1155":return {itemType:3 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:e.amount,endAmount:e.amount};case"ERC721_COLLECTION":throw new Error("ERC721_COLLECTION items are not supported in the offer");case"ERC1155_COLLECTION":throw new Error("ERC1155_COLLECTION items are not supported in the offer");default:return R()}}function Rt(e,t){switch(e.type){case"NATIVE":return {itemType:0 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:ethers.ZeroAddress,identifierOrCriteria:"0",recipient:t};case"ERC20":return {itemType:1 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC721":return {itemType:2 .valueOf(),startAmount:"1",endAmount:"1",token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC721_COLLECTION":return {itemType:4 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC1155_COLLECTION":return {itemType:5 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};default:return R()}}function W(e){let t=e.sell.map(Ct),r=e.buy.map(i=>Rt(i,e.account_address)),s=function(i){switch(i){case f.type.LISTING:return r[0];case f.type.BID:case f.type.COLLECTION_BID:case f.type.TRAIT_BID:return t[0];default:return R()}}(e.type),o=function(i){switch(i){case y.order_type.FULL_RESTRICTED:return 2;case y.order_type.PARTIAL_RESTRICTED:return 3;default:return R()}}(e.protocol_data.order_type),a=e.fees.map(i=>({amount:i.amount,itemType:s.itemType,recipient:i.recipient_address,token:s.token,identifierOrCriteria:s.identifierOrCriteria}));return {orderComponents:{offerer:e.account_address,zone:e.protocol_data.zone_address,offer:t,consideration:r,orderType:o.valueOf(),startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),zoneHash:ethers.ZeroHash,salt:e.salt,conduitKey:ethers.ZeroHash,counter:e.protocol_data.counter,totalOriginalConsiderationItems:r.length},tips:a}}function h(e,t,r){return async()=>{let s=await e.buildTransaction(),o={to:s.to,from:r,type:s.type,maxFeePerGas:s.maxFeePerGas?BigInt(s.maxFeePerGas):void 0,maxPriorityFeePerGas:s.maxPriorityFeePerGas?BigInt(s.maxPriorityFeePerGas):void 0,value:s.value?BigInt(s.value):void 0,data:s.data,nonce:s.nonce,chainId:t};return o.gasLimit=BigInt(await e.estimateGas()),o.gasLimit+=o.gasLimit/BigInt(5),o}}function xe(e){switch(e.type){case"ERC20":return {token:e.contractAddress,amount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount};default:return R()}}function Ne(e,t){switch(e.type){case"NATIVE":return {amount:e.amount,recipient:t};case"ERC20":return {token:e.contractAddress,amount:e.amount,recipient:t};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount,recipient:t};case"ERC721_COLLECTION":return {itemType:2 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};case"ERC1155_COLLECTION":return {itemType:3 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};default:return R()}}var K=class e{constructor(t,r,s,o,a){this.seaportLibFactory=t;this.provider=r;this.seaportContractAddress=s;this.zoneContractAddress=o;this.rateLimitingKey=a;}async prepareBulkSeaportOrders(t,r){let{actions:s}=await this.createSeaportOrders(t,r),o=s.filter(l=>l.type==="approval"),a=await this.provider.getNetwork(),i=o.map(l=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:h(l.transactionMethods,a.chainId,t)})),d=s.find(l=>l.type==="createBulk");if(!d)throw new Error("No create bulk order action found");let p=await d.getMessageToSign(),{components:n,types:u,value:c}=Le(p);return i.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(u,c)}),{actions:i,preparedOrders:n.map(l=>({orderComponents:l,orderHash:this.getSeaportLib().getOrderHash(l)}))}}async prepareSeaportOrder(t,r,s,o,a,i){let{actions:d}=await this.createSeaportOrder(t,r,s,o,a,i),p=[],n=d.find(m=>m.type==="approval");n&&p.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:h(n.transactionMethods,(await this.provider.getNetwork()).chainId,t)});let u=d.find(m=>m.type==="create");if(!u)throw new Error("No create order action found");let c=await u.getMessageToSign(),l=Be(c);return p.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromOrderComponents(l)}),{actions:p,orderComponents:l,orderHash:this.getSeaportLib().getOrderHash(l)}}async fulfillOrder(t,r,s,o,a){let{orderComponents:i,tips:d}=W(t),p=this.getSeaportLib(t),n=(await this.provider.getNetwork()).chainId,u={order:{parameters:i,signature:t.signature},unitsToFill:o,extraData:s,tips:d};a&&(u.considerationCriteria=a);let{actions:c}=await p.fulfillOrders({accountAddress:r,fulfillOrderDetails:[u]}),l=[],m=c.filter(E=>E.type==="approval");m.length>0&&m.forEach(E=>{l.push({type:"TRANSACTION",buildTransaction:h(E.transactionMethods,n,r),purpose:"APPROVAL"});});let O=c.find(E=>E.type==="exchange");if(!O)throw new Error("No exchange action found");return l.push({type:"TRANSACTION",buildTransaction:h(O.transactionMethods,n,r),purpose:"FULFILL_ORDER"}),{actions:l,expiration:e.getExpirationISOTimeFromExtraData(s),order:k(t)}}async fulfillBulkOrders(t,r){let s=t.map(n=>{let{orderComponents:u,tips:c}=W(n.order),l={order:{parameters:u,signature:n.order.signature},unitsToFill:n.unitsToFill,extraData:n.extraData,tips:c};return n.considerationCriteria&&n.considerationCriteria.length>0&&(l.considerationCriteria=n.considerationCriteria),l}),{actions:o}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:s,accountAddress:r}),a=[],i=o.filter(n=>n.type==="approval"),d=(await this.provider.getNetwork()).chainId;i.length>0&&i.forEach(n=>{a.push({type:"TRANSACTION",buildTransaction:h(n.transactionMethods,d,r),purpose:"APPROVAL"});});let p=o.find(n=>n.type==="exchange");if(!p)throw new Error("No exchange action found");return a.push({type:"TRANSACTION",buildTransaction:h(p.transactionMethods,(await this.provider.getNetwork()).chainId,r),purpose:"FULFILL_ORDER"}),{actions:a,expiration:s.map(n=>e.getExpirationISOTimeFromExtraData(n.extraData)).reduce((n,u)=>new Date(n)<new Date(u)?n:u)}}async cancelOrders(t,r){let s=t.map(i=>W(i).orderComponents),a=await this.getSeaportLib(t[0]).cancelOrders(s,r);return {type:"TRANSACTION",buildTransaction:h(a,(await this.provider.getNetwork()).chainId,r),purpose:"CANCEL"}}createSeaportOrders(t,r){return this.getSeaportLib().createBulkOrders(r.map(o=>{let{offerItem:a,considerationItem:i,allowPartialFills:d,orderStart:p,orderExpiry:n}=o;return {allowPartialFills:d,offer:[xe(a)],consideration:[Ne(i,t)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(n.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),t)}createSeaportOrder(t,r,s,o,a,i){return this.getSeaportLib().createOrder({allowPartialFills:o,offer:[xe(r)],consideration:[Ne(s,t)],startTime:(a.getTime()/1e3).toFixed(0),endTime:(i.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},t)}async getTypedDataFromBulkOrderComponents(t,r){delete t.EIP712Domain;let{chainId:s}=await this.provider.getNetwork();return {domain:{name:ae,version:g,chainId:s,verifyingContract:this.seaportContractAddress},types:t,value:r}}async getTypedDataFromOrderComponents(t){let{chainId:r}=await this.provider.getNetwork();return {domain:{name:ae,version:g,chainId:r,verifyingContract:this.seaportContractAddress},types:U,value:t}}getSeaportLib(t){let r=t?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(r)}static getExpirationISOTimeFromExtraData(t){let r=t.slice(44,60),s=parseInt(r,16);return new Date(s*1e3).toISOString()}};function Y(e){switch(e.itemType){case 0:return {type:"NATIVE",amount:e.startAmount};case 1:return {type:"ERC20",contract_address:e.token,amount:e.startAmount};case 2:return {type:"ERC721",contract_address:e.token,token_id:e.identifierOrCriteria};case 3:return {type:"ERC1155",contract_address:e.token,token_id:e.identifierOrCriteria,amount:e.startAmount};case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};default:return R(e.itemType)}}function J(e){if(e.itemType!==1)throw new Error(`Expected ERC20 item, got ${e.itemType}`);return {type:"ERC20",contract_address:e.token,amount:e.startAmount}}function le(e){switch(e.itemType){case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};case 1:case 0:case 2:case 3:throw new Error(`Unsupported item type ${e.itemType}`);default:return R(e.itemType)}}function D(e){switch(e){case 2:return y.order_type.FULL_RESTRICTED;case 3:return y.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${e}`);default:return R()}}var Z=class{constructor(t,r,s){this.orderbookService=t;this.chainName=r;this.seaportAddress=s;}async fulfillmentData(t){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:t})}async getListing(t){return this.orderbookService.getListing({chainName:this.chainName,listingId:t})}async getBid(t){return this.orderbookService.getBid({chainName:this.chainName,bidId:t})}async getCollectionBid(t){return this.orderbookService.getCollectionBid({chainName:this.chainName,collectionBidId:t})}async getTraitBid(t){return this.orderbookService.getTraitBid({chainName:this.chainName,traitBidId:t})}async getTrade(t){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:t})}async listListings(t){return this.orderbookService.listListings({chainName:this.chainName,...t})}async listBids(t){return this.orderbookService.listBids({chainName:this.chainName,...t})}async listCollectionBids(t){return this.orderbookService.listCollectionBids({chainName:this.chainName,...t})}async listTraitBids(t){return this.orderbookService.listTraitBids({chainName:this.chainName,...t})}async listTrades(t){return this.orderbookService.listTrades({chainName:this.chainName,...t})}async cancelOrders(t,r,s){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:r,orders:t,signature:s}})}async createListing({orderHash:t,orderComponents:r,orderSignature:s,makerFees:o}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a listing");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a listing");if(![2,3].includes(r.offer[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be listed");if(![0,1].includes(r.consideration[0].itemType))throw new Error("Only Native / ERC20 tokens can be used as currency items in a listing");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(Y),fees:o.map(a=>({type:C.type.MAKER_ECOSYSTEM,amount:a.amount,recipient_address:a.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:D(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:g,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(Y),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:o}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a bid");if(![2,3].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be bid against");return this.orderbookService.createBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(Y),fees:o.map(a=>({type:C.type.MAKER_ECOSYSTEM,amount:a.amount,recipient_address:a.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:D(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:g,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(J),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:o}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a collection bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a collection bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a collection bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");return this.orderbookService.createCollectionBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(le),fees:o.map(a=>({type:C.type.MAKER_ECOSYSTEM,amount:a.amount,recipient_address:a.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:D(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:g,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(J),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createTraitBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:o,traitCriteria:a}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a trait bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a trait bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a trait bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");if(!a?.length)throw new Error("At least one trait criterion is required for a trait bid");return this.orderbookService.createTraitBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(le),fees:o.map(i=>({type:C.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:D(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:g,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(J),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString(),trait_criteria:a.map(i=>({trait_type:i.traitType,values:i.values}))}})}};var X=class{constructor(t,r,s,o){this.chainName=r;this.seaportAddress=s;this.orderbookClient=new S({BASE:t,HEADERS:o?{"x-api-key":o}:void 0});}orderbookClient;create(){return new Z(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var ht="imtbl-zkevm-testnet",Et="imtbl-zkevm-mainnet";function Q(e,t){let r=new ethers.FetchRequest(e);return t&&r.setHeader("x-api-key",t),new ethers.JsonRpcProvider(r)}function ke(e){switch(e.baseConfig.environment){case config.Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:ht,provider:Q("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case config.Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:Et,provider:Q("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}var ee=class{constructor(t,r){this.defaultSeaportContractAddress=t;this.provider=r;}create(t){let r=t??this.defaultSeaportContractAddress,s=this.provider;return s.getSigner=async function(a){a==null&&(a=0);let i=this.send("eth_accounts",[]);if(typeof a=="number"){let d=await i;if(a>=d.length)throw new Error("no such account");return new ethers.JsonRpcSigner(this,d[a])}return new ethers.JsonRpcSigner(this,a)},new seaportJs.Seaport(s,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}};var pe=class e{apiClient;seaport;orderbookConfig;constructor(t){let s={...ke(t),...t.overrides};if(t.overrides?.jsonRpcProviderUrl&&(s.provider=Q(t.overrides?.jsonRpcProviderUrl,t.baseConfig.rateLimitingKey)),!s)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=s;let{apiEndpoint:o,chainName:a}=this.orderbookConfig;if(!o)throw new Error("API endpoint must be provided");this.apiClient=new X(o,a,this.orderbookConfig.seaportContractAddress,t.baseConfig.rateLimitingKey).create();let i=new ee(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new K(i,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,t.baseConfig.rateLimitingKey);}static defaultOrderExpiry(){return new Date(Date.now()+1e3*60*60*24*365*2)}config(){return this.orderbookConfig}async getListing(t){let r=await this.apiClient.getListing(t);return {result:T(r.result)}}async getBid(t){let r=await this.apiClient.getBid(t);return {result:x(r.result)}}async getCollectionBid(t){let r=await this.apiClient.getCollectionBid(t);return {result:N(r.result)}}async getTraitBid(t){let r=await this.apiClient.getTraitBid(t);return {result:w(r.result)}}async getTrade(t){let r=await this.apiClient.getTrade(t);return {result:se(r.result)}}async listListings(t){let r=await this.apiClient.listListings(t);return {page:_(r.page),result:r.result.map(T)}}async listBids(t){let r=await this.apiClient.listBids(t);return {page:_(r.page),result:r.result.map(x)}}async listCollectionBids(t){let r=await this.apiClient.listCollectionBids(t);return {page:_(r.page),result:r.result.map(N)}}async listTraitBids(t){let r=await this.apiClient.listTraitBids(t);return {page:_(r.page),result:r.result.map(w)}}async listTrades(t){let r=await this.apiClient.listTrades(t);return {page:_(r.page),result:r.result.map(se)}}async prepareBulkListings({makerAddress:t,listingParams:r}){if(r.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(r.length===1){let i=await this.seaport.prepareSeaportOrder(t,r[0].sell,r[0].buy,r[0].sell.type==="ERC1155",r[0].orderStart||new Date,r[0].orderExpiry||e.defaultOrderExpiry());return {actions:i.actions,completeListings:async d=>{let p=await this.createListing({makerFees:r[0].makerFees,orderComponents:i.orderComponents,orderHash:i.orderHash,orderSignature:typeof d=="string"?d:d[0]});return {result:[{success:!0,orderHash:i.orderHash,order:p.result}]}}}}if(await this.orderbookConfig.provider.getCode(t)!=="0x"){metrics.track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:t,listingsCount:r.length});let i=await Promise.all(r.map(n=>this.seaport.prepareSeaportOrder(t,n.sell,n.buy,n.sell.type==="ERC1155",n.orderStart||new Date,n.orderExpiry||e.defaultOrderExpiry()))),d=[];return {actions:i.flatMap(n=>{let u=[];return n.actions.forEach(c=>{if(c.type==="TRANSACTION"){let l=n.orderComponents.offer[0].token;d.includes(l)||(d.push(l),u.push(c));}else u.push(c);}),u}),completeListings:async n=>{if(typeof n=="string")throw new Error("A signature per listing must be provided for smart contract wallets");return {result:(await Promise.all(i.map((l,m)=>{let O=n[m];return this.apiClient.createListing({makerFees:r[m].makerFees,orderComponents:l.orderComponents,orderHash:l.orderHash,orderSignature:O}).catch(()=>{})}))).map((l,m)=>({success:!!l,orderHash:i[m].orderHash,order:l?T(l.result):void 0}))}}}}metrics.track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:t,listingsCount:r.length});let{actions:o,preparedOrders:a}=await this.seaport.prepareBulkSeaportOrders(t,r.map(i=>({offerItem:i.sell,considerationItem:i.buy,allowPartialFills:i.sell.type==="ERC1155",orderStart:i.orderStart||new Date,orderExpiry:i.orderExpiry||e.defaultOrderExpiry()})));return {actions:o,completeListings:async i=>{let d=typeof i=="object";if(d&&i.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let p=a.map(l=>l.orderComponents),n=d?i[0]:i,u=Pe(n,p);return {result:(await Promise.all(p.map((l,m)=>{let O=u[m],E=a[m],Fe=r[m];return this.apiClient.createListing({orderComponents:l,orderHash:E.orderHash,orderSignature:O,makerFees:Fe.makerFees}).catch(()=>{})}))).map((l,m)=>({success:!!l,orderHash:a[m].orderHash,order:l?T(l.result):void 0}))}}}}async prepareListing({makerAddress:t,sell:r,buy:s,orderStart:o,orderExpiry:a}){return this.seaport.prepareSeaportOrder(t,r,s,r.type==="ERC1155",o||new Date,a||e.defaultOrderExpiry())}async createListing(t){let r=await this.apiClient.createListing(t);return {result:T(r.result)}}async prepareBid({makerAddress:t,sell:r,buy:s,orderStart:o,orderExpiry:a}){return this.seaport.prepareSeaportOrder(t,r,s,s.type==="ERC1155",o||new Date,a||e.defaultOrderExpiry())}async createBid(t){let r=await this.apiClient.createBid(t);return {result:x(r.result)}}async prepareCollectionBid({makerAddress:t,sell:r,buy:s,orderStart:o,orderExpiry:a}){return this.seaport.prepareSeaportOrder(t,r,s,!0,o||new Date,a||e.defaultOrderExpiry())}async createCollectionBid(t){let r=await this.apiClient.createCollectionBid(t);return {result:N(r.result)}}async prepareTraitBid({makerAddress:t,sell:r,buy:s,orderStart:o,orderExpiry:a}){return this.seaport.prepareSeaportOrder(t,r,s,!0,o||new Date,a||e.defaultOrderExpiry())}async createTraitBid(t){let r=await this.apiClient.createTraitBid(t);return {result:w(r.result)}}async fulfillOrder(t,r,s,o,a){let i={order_id:t,taker_address:r,fees:s.map(c=>({type:C.type.TAKER_ECOSYSTEM,amount:c.amount,recipient_address:c.recipientAddress}))},d=a?[{identifier:a,proof:[]}]:void 0;a&&(i.token_id=a);let p=await this.apiClient.fulfillmentData([i]);if(p.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment data: ${p.result.unfulfillable_orders[0].reason}`);if(p.result.fulfillable_orders?.length!==1)throw new Error("unexpected fulfillable order result length");let n=p.result.fulfillable_orders[0].extra_data,u=p.result.fulfillable_orders[0].order;if(u.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${u.status}`);return this.seaport.fulfillOrder(u,r,n,o,d)}async fulfillBulkOrders(t,r){let s=t.map(a=>{let i="listingId"in a;return {orderId:i?a.listingId:a.orderId,takerFees:a.takerFees,amountToFill:a.amountToFill,tokenId:i?void 0:a.tokenId}}),o=await this.apiClient.fulfillmentData(s.map(a=>({order_id:a.orderId,taker_address:r,fees:a.takerFees.map(i=>({type:C.type.TAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),token_id:a?.tokenId})));try{let a=o.result.fulfillable_orders.map(i=>{let d=s.find(n=>n.orderId===i.order.id&&n.tokenId===i.token_id);if(!d){let n=`Could not find order for order ${i.order.id}`;throw i.token_id&&(n+=` and token ID ${i.token_id}`),new Error(n)}let p=[];return d.tokenId&&p.push({identifier:d.tokenId,proof:[]}),{extraData:i.extra_data,order:i.order,unitsToFill:d.amountToFill,considerationCriteria:p}});return {...await this.seaport.fulfillBulkOrders(a,r),fulfillableOrders:o.result.fulfillable_orders.map(i=>k(i.order)),unfulfillableOrders:o.result.unfulfillable_orders.map(i=>({orderId:i.order_id,tokenId:i.token_id,reason:i.reason})),sufficientBalance:!0}}catch(a){if(String(a).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:o.result.fulfillable_orders.map(i=>k(i.order)),unfulfillableOrders:o.result.unfulfillable_orders.map(i=>({orderId:i.order_id,reason:i.reason})),sufficientBalance:!1};throw a}}async prepareOrderCancellations(t){let r=await this.orderbookConfig.provider.getNetwork(),s={name:"imtbl-order-book",chainId:Number(r.chainId),verifyingContract:this.orderbookConfig.seaportContractAddress},o={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},a={orders:t.map(i=>({id:i}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:s,types:o,value:a}}}}async cancelOrders(t,r,s){return this.apiClient.cancelOrders(t,r,s)}async cancelOrdersOnChain(t,r){let s=Promise.all(t.map(c=>this.apiClient.getListing(c).catch(l=>{if(l.status!==404)throw l}))),o=Promise.all(t.map(c=>this.apiClient.getBid(c).catch(l=>{if(l.status!==404)throw l}))),a=Promise.all(t.map(c=>this.apiClient.getCollectionBid(c).catch(l=>{if(l.status!==404)throw l}))),i=Promise.all(t.map(c=>this.apiClient.getTraitBid(c).catch(l=>{if(l.status!==404)throw l}))),d=[await Promise.all([s,o,a,i])].flat(2).filter(c=>c!==void 0).map(c=>c.result);if(d.length!==t.length){let c=t.filter(l=>!d.some(m=>m.id===l));throw new Error(`Orders ${c} not found`)}for(let c of d)if(c.account_address!==r.toLowerCase())throw new Error(`Only account ${c.account_address} can cancel order ${c.id}`);let p=d.map(c=>c.protocol_data.seaport_address);if(new Set(p).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(d,r)}}};var Ot={estimatedFulfillmentGasGwei:4e5};
17
17
 
18
- exports.ActionType = re;
19
- exports.FeeType = Ye;
20
- exports.OrderStatusName = H;
21
- exports.Orderbook = de;
22
- exports.SignablePurpose = se;
23
- exports.TransactionPurpose = Ce;
24
- exports.constants = ht;
18
+ exports.ActionType = ie;
19
+ exports.FeeType = Ze;
20
+ exports.OrderStatusName = V;
21
+ exports.Orderbook = pe;
22
+ exports.SignablePurpose = oe;
23
+ exports.TransactionPurpose = ye;
24
+ exports.constants = Ot;
@@ -1,11 +1,11 @@
1
1
  import { track } from '@imtbl/metrics';
2
- import le from 'axios';
3
- import pe from 'form-data';
2
+ import ce from 'axios';
3
+ import ue from 'form-data';
4
4
  import { zeroPadValue, FetchRequest, JsonRpcProvider, JsonRpcSigner, toBeHex, ZeroHash, TypedDataEncoder, keccak256, toUtf8Bytes, concat, ZeroAddress, AbiCoder } from 'ethers';
5
5
  import { MerkleTree } from 'merkletreejs';
6
6
  import { Environment } from '@imtbl/config';
7
7
  import { Seaport } from '@opensea/seaport-js';
8
8
 
9
- var b=class{constructor(t){this.config=t;}};var T=class extends Error{url;status;statusText;body;request;constructor(t,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=t;}};var v=class extends Error{constructor(t){super(t),this.name="CancelError";}get isCancelled(){return !0}},L=class{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(t){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((r,s)=>{this._resolve=r,this._reject=s;let n=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(d));},i=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(d));},o=d=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(d);};return Object.defineProperty(o,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(o,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(o,"isCancelled",{get:()=>this._isCancelled}),t(n,i,o)});}then(t,r){return this._promise.then(t,r)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let t of this._cancelHandlers)t();}catch(t){console.warn("Cancellation threw an error",t);return}this._cancelHandlers.length=0,this._reject?.(new v("Request aborted"));}}get isCancelled(){return this._isCancelled}};var ee=e=>e!=null,F=e=>typeof e=="string",Q=e=>F(e)&&e!=="",ce=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof pe,qe=e=>e>=200&&e<300,He=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Me=e=>{let t=[],r=(n,i)=>{t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`);},s=(n,i)=>{ee(i)&&(Array.isArray(i)?i.forEach(o=>{s(n,o);}):typeof i=="object"?Object.entries(i).forEach(([o,d])=>{s(`${n}[${o}]`,d);}):r(n,i));};return Object.entries(e).forEach(([n,i])=>{s(n,i);}),t.length>0?`?${t.join("&")}`:""},Ve=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(i,o)=>t.path?.hasOwnProperty(o)?r(String(t.path[o])):i),n=`${e.BASE}${s}`;return t.query?`${n}${Me(t.query)}`:n},Ue=e=>{if(e.formData){let t=new pe,r=(s,n)=>{F(n)||ce(n)?t.append(s,n):t.append(s,JSON.stringify(n));};return Object.entries(e.formData).filter(([s,n])=>ee(n)).forEach(([s,n])=>{Array.isArray(n)?n.forEach(i=>r(s,i)):r(s,n);}),t}},D=async(e,t)=>typeof t=="function"?t(e):t,ze=async(e,t,r)=>{let s=await D(t,e.TOKEN),n=await D(t,e.USERNAME),i=await D(t,e.PASSWORD),o=await D(t,e.HEADERS),d=typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...o,...t.headers,...d}).filter(([a,l])=>ee(l)).reduce((a,[l,u])=>({...a,[l]:String(u)}),{});if(Q(s)&&(p.Authorization=`Bearer ${s}`),Q(n)&&Q(i)){let a=He(`${n}:${i}`);p.Authorization=`Basic ${a}`;}return t.body&&(t.mediaType?p["Content-Type"]=t.mediaType:ce(t.body)?p["Content-Type"]=t.body.type||"application/octet-stream":F(t.body)?p["Content-Type"]="text/plain":Fe(t.body)||(p["Content-Type"]="application/json")),p},$e=e=>{if(e.body)return e.body},Ge=async(e,t,r,s,n,i,o)=>{let d=le.CancelToken.source(),p={url:r,headers:i,data:s??n,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:d.token};o(()=>d.cancel("The user aborted a request."));try{return await le.request(p)}catch(a){let l=a;if(l.response)return l.response;throw a}},je=(e,t)=>{if(t){let r=e.headers[t];if(F(r))return r}},We=e=>{if(e.status!==204)return e.data},Ke=(e,t)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(s)throw new T(e,t,s);if(!t.ok)throw new T(e,t,"Generic Error")},ue=(e,t)=>new L(async(r,s,n)=>{try{let i=Ve(e,t),o=Ue(t),d=$e(t),p=await ze(e,t,o);if(!n.isCancelled){let a=await Ge(e,t,i,d,o,p,n),l=We(a),u=je(a,t.responseHeader),c={url:i,ok:qe(a.status),status:a.status,statusText:a.statusText,body:u??l};Ke(t,c),r(c.body);}}catch(i){s(i);}});var q=class extends b{constructor(t){super(t);}request(t){return ue(this.config,t)}};var S=class{constructor(t){this.httpRequest=t;}cancelOrders({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",401:"Unauthorised Request (401)",404:"The specified resource was not found (404)",429:"Too Many Requests (429)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listListings({chainName:t,status:r,sellItemContractAddress:s,buyItemType:n,buyItemContractAddress:i,accountAddress:o,sellItemMetadataId:d,sellItemTokenId:p,fromUpdatedAt:a,pageSize:l,sortBy:u,sortDirection:c,pageCursor:m}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},query:{status:r,sell_item_contract_address:s,buy_item_type:n,buy_item_contract_address:i,account_address:o,sell_item_metadata_id:d,sell_item_token_id:p,from_updated_at:a,page_size:l,sort_by:u,sort_direction:c,page_cursor:m},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,buyItemMetadataId:o,buyItemTokenId:d,fromUpdatedAt:p,pageSize:a,sortBy:l,sortDirection:u,pageCursor:c}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,buy_item_metadata_id:o,buy_item_token_id:d,from_updated_at:p,page_size:a,sort_by:l,sort_direction:u,page_cursor:c},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listCollectionBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,fromUpdatedAt:o,pageSize:d,sortBy:p,sortDirection:a,pageCursor:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,from_updated_at:o,page_size:d,sort_by:p,sort_direction:a,page_cursor:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createCollectionBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}getListing({chainName:t,listingId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:t,listing_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getBid({chainName:t,bidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids/{bid_id}",path:{chain_name:t,bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getCollectionBid({chainName:t,collectionBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids/{collection_bid_id}",path:{chain_name:t,collection_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:t,accountAddress:r,sellItemContractAddress:s,fromIndexedAt:n,pageSize:i,sortBy:o,sortDirection:d,pageCursor:p}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:t},query:{account_address:r,sell_item_contract_address:s,from_indexed_at:n,page_size:i,sort_by:o,sort_direction:d,page_cursor:p},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:t,tradeId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:t,trade_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}};var P=class{orders;request;constructor(t,r=q){this.request=new r({BASE:t?.BASE??"https://api.immutable.com",VERSION:t?.VERSION??"1.0.0",WITH_CREDENTIALS:t?.WITH_CREDENTIALS??!1,CREDENTIALS:t?.CREDENTIALS??"include",TOKEN:t?.TOKEN,USERNAME:t?.USERNAME,PASSWORD:t?.PASSWORD,HEADERS:t?.HEADERS,ENCODE_PATH:t?.ENCODE_PATH}),this.orders=new S(this.request);}};var me;(t=>{(i=>(i.ON_CHAIN="ON_CHAIN",i.OFF_CHAIN="OFF_CHAIN",i.UNDERFUNDED="UNDERFUNDED"))(t.cancellation_type||={});})(me||={});var fe;(t=>{(s=>s.FILLED="FILLED")(t.reason_code||={});})(fe||={});var f;(t=>{(o=>(o.ROYALTY="ROYALTY",o.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",o.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",o.PROTOCOL="PROTOCOL"))(t.type||={});})(f||={});var R;(t=>{(i=>(i.LISTING="LISTING",i.BID="BID",i.COLLECTION_BID="COLLECTION_BID"))(t.type||={});})(R||={});var H=(o=>(o.PENDING="PENDING",o.ACTIVE="ACTIVE",o.INACTIVE="INACTIVE",o.FILLED="FILLED",o.EXPIRED="EXPIRED",o.CANCELLED="CANCELLED",o))(H||{});var y;(t=>{(n=>(n.FULL_RESTRICTED="FULL_RESTRICTED",n.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(t.order_type||={});})(y||={});function C(e){throw new Error("Unreachable")}function h(e){if(e.type!==R.type.LISTING)throw new Error("Order type must be LISTING");let t=e.sell.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Listing sell items must either ERC721 or ERC1155")}),r=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Listing buy items must be either NATIVE or ERC20")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function B(e){if(e.type!==R.type.BID)throw new Error("Order type must be BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Bid buy items must either ERC721 or ERC1155")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function x(e){if(e.type!==R.type.COLLECTION_BID)throw new Error("Order type must be COLLECTION_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function N(e){switch(e.type){case R.type.LISTING:return h(e);case R.type.BID:return B(e);case R.type.COLLECTION_BID:return x(e);default:return C(e.type)}}function te(e){let t=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Buy items must be NATIVE, ERC20, ERC721 or ERC1155")}),r=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Sell items must be ERC20, ERC721 or ERC1155")});return {id:e.id,orderId:e.order_id,buy:t,sell:r,buyerFees:e.buyer_fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),chain:e.chain,indexedAt:e.indexed_at,blockchainMetadata:{blockNumber:e.blockchain_metadata.block_number,logIndex:e.blockchain_metadata.log_index,transactionHash:e.blockchain_metadata.transaction_hash,transactionIndex:e.blockchain_metadata.transaction_index},buyerAddress:e.buyer_address,makerAddress:e.maker_address,sellerAddress:e.seller_address,takerAddress:e.taker_address}}function k(e){return {nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}var Ye=(n=>(n[n.MAKER_ECOSYSTEM=f.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",n[n.TAKER_ECOSYSTEM=f.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",n[n.PROTOCOL=f.type.PROTOCOL]="PROTOCOL",n[n.ROYALTY=f.type.ROYALTY]="ROYALTY",n))(Ye||{}),re=(r=>(r.TRANSACTION="TRANSACTION",r.SIGNABLE="SIGNABLE",r))(re||{}),Ce=(s=>(s.APPROVAL="APPROVAL",s.FULFILL_ORDER="FULFILL_ORDER",s.CANCEL="CANCEL",s))(Ce||{}),se=(s=>(s.CREATE_LISTING="CREATE_ORDER",s.CREATE_ORDER="CREATE_ORDER",s.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",s))(se||{});var oe="ImmutableSeaport",O="1.5",M={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]};var Je={integer:0,address:zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},ne=e=>e===void 0?!1:e!=null&&(["string","number"].includes(typeof e)&&BigInt(e)===0n||Array.isArray(e)&&e.every(ne)||typeof e=="object"&&Object.values(e).every(ne)||typeof e=="boolean"&&e===!1);function Ze(e){let[,t]=e.match(/^bytes(\d+)$/)??[];return t?zeroPadValue("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),Je[e])}var A=class e{constructor(t){this.types=t;for(let r in t){let s=this.getDefaultValue(r);if(this.defaultValues[r]=s,!ne(s))throw new Error(`Got non-empty value for type ${r} in default generator: ${s}`)}}defaultValues={};static from(t,r){let{defaultValues:s}=new e(t);return r?s[r]:s}getDefaultValue(t){if(this.defaultValues[t])return this.defaultValues[t];let r=Ze(t);if(r!==void 0)return r;let s=t.match(/^(.*)(\x5b(\d*)\x5d)$/);if(s){let i=s[1],o=parseInt(s[3]);if(o>0){let d=this.getDefaultValue(i);return Array(o).fill(d)}return []}let n=this.types[t];if(n)return n.reduce((i,{name:o,type:d})=>({...i,[o]:this.getDefaultValue(d)}),{});throw new Error(`unknown type: ${t}`)}};var tt=(e,t)=>Array(e).fill(0).map((r,s)=>t(s)),ie=(e,t)=>tt(Math.ceil(e.length/t),r=>e.slice(r*t,(r+1)*t)),ye=e=>toBeHex(e.toString("hex")),_=e=>Buffer.from(e.slice(2),"hex"),V=e=>_(keccak256(e)),rt=e=>V(concat(e)),w=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),ge=(e,t=!0)=>{if(e.length===0)throw new Error("empty tree");let s=[e.map(n=>{let i=Buffer.isBuffer(n)?n:_(n);return t?V(i):i})];for(;s[s.length-1].length>1;)s.push(st(s[s.length-1]));return s[s.length-1][0]},st=e=>ie(e,2).map(rt);var dt=(e,t)=>new MerkleTree(e.map(_),V,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:_(t)}),lt=(e,t,r=`0x${"ff".repeat(64)}`)=>concat([r,`0x${e.toString(16).padStart(6,"0")}`,AbiCoder.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]),U=class{constructor(t,r,s,n,i){this.types=t;this.rootType=r;this.leafType=s;this.elements=n;this.depth=i;let o=TypedDataEncoder.from(t);this.encoder=o,this.leafHasher=d=>o.hashStruct(s,d),this.defaultNode=A.from(t,s),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=dt(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:t}=this;return w([...t],this.completedSize,this.defaultNode)}getCompleteLeaves(){let t=this.elements.map(this.leafHasher);return w([...t],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(t){let s=this.getCompleteLeaves()[t],n=this.tree.getHexProof(s,t),i=this.tree.getHexRoot();return {leaf:s,proof:n,root:i}}getEncodedProofAndSignature(t,r){let{proof:s}=this.getProof(t);return lt(t,s,r)}getDataToSign(){let t=this.getCompleteElements();for(;t.length>2;)t=ie(t,2);return t}add(t){this.elements.push(t);}getBulkOrderHash(){let t=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),r=this.getCompleteLeaves().map(_),s=ye(ge(r,!1)),n=keccak256(toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(keccak256(concat([n,s]))!==t)throw new Error("expected derived bulk order hash to match");return t}};function pt(e){return {...M,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}function ct(e){return Math.max(Math.ceil(Math.log2(e)),1)}function Oe(e,t=0,r=ct(e.length+t)){let s=pt(r),n=A.from(s,"OrderComponents"),i=[...e];return t>0&&(i=[...w([],t,n),...e]),new U(s,"BulkOrder","OrderComponents",i,r)}function Ae(e){if([0,1,2,3].includes(Number(e)))return Number(e);throw new Error(`Unknown order type ${e}`)}function z(e){if([0,1,2,3,4,5].includes(Number(e)))return Number(e);throw new Error(`Unknown item type ${e}`)}function _e(e){let r=JSON.parse(e).message;return {...r,orderType:Ae(r.orderType),salt:toBeHex(BigInt(r.salt)),offer:r.offer.map(s=>({...s,itemType:z(s.itemType)})),consideration:r.consideration.map(s=>({...s,itemType:z(s.itemType)}))}}function be(e){let t=JSON.parse(e);return {components:t.message.tree.flat(1/0).filter(s=>s.offerer!=="0x0000000000000000000000000000000000000000").map(s=>({...s,orderType:Ae(s.orderType),salt:toBeHex(BigInt(s.salt)),offer:s.offer.map(n=>({...n,itemType:z(n.itemType)})),consideration:s.consideration.map(n=>({...n,itemType:z(n.itemType)}))})),types:t.types,value:t.message}}function Le(e,t){let r=Oe(t);return t.map((s,n)=>r.getEncodedProofAndSignature(n,e))}function mt(e){switch(e.type){case"NATIVE":throw new Error("NATIVE items are not supported in the offer");case"ERC20":return {itemType:1 .valueOf(),token:e.contract_address,identifierOrCriteria:"0",startAmount:e.amount,endAmount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:"1",endAmount:"1"};case"ERC1155":return {itemType:3 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:e.amount,endAmount:e.amount};case"ERC721_COLLECTION":throw new Error("ERC721_COLLECTION items are not supported in the offer");case"ERC1155_COLLECTION":throw new Error("ERC1155_COLLECTION items are not supported in the offer");default:return C()}}function ft(e,t){switch(e.type){case"NATIVE":return {itemType:0 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:ZeroAddress,identifierOrCriteria:"0",recipient:t};case"ERC20":return {itemType:1 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC721":return {itemType:2 .valueOf(),startAmount:"1",endAmount:"1",token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC721_COLLECTION":return {itemType:4 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC1155_COLLECTION":return {itemType:5 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};default:return C()}}function G(e){let t=e.sell.map(mt),r=e.buy.map(o=>ft(o,e.account_address)),s=function(o){switch(o){case R.type.LISTING:return r[0];case R.type.BID:case R.type.COLLECTION_BID:return t[0];default:return C()}}(e.type),n=function(o){switch(o){case y.order_type.FULL_RESTRICTED:return 2;case y.order_type.PARTIAL_RESTRICTED:return 3;default:return C()}}(e.protocol_data.order_type),i=e.fees.map(o=>({amount:o.amount,itemType:s.itemType,recipient:o.recipient_address,token:s.token,identifierOrCriteria:s.identifierOrCriteria}));return {orderComponents:{offerer:e.account_address,zone:e.protocol_data.zone_address,offer:t,consideration:r,orderType:n.valueOf(),startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),zoneHash:ZeroHash,salt:e.salt,conduitKey:ZeroHash,counter:e.protocol_data.counter,totalOriginalConsiderationItems:r.length},tips:i}}function g(e,t,r){return async()=>{let s=await e.buildTransaction(),n={to:s.to,from:r,type:s.type,maxFeePerGas:s.maxFeePerGas?BigInt(s.maxFeePerGas):void 0,maxPriorityFeePerGas:s.maxPriorityFeePerGas?BigInt(s.maxPriorityFeePerGas):void 0,value:s.value?BigInt(s.value):void 0,data:s.data,nonce:s.nonce,chainId:t};return n.gasLimit=BigInt(await e.estimateGas()),n.gasLimit+=n.gasLimit/BigInt(5),n}}function Pe(e){switch(e.type){case"ERC20":return {token:e.contractAddress,amount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount};default:return C()}}function Be(e,t){switch(e.type){case"NATIVE":return {amount:e.amount,recipient:t};case"ERC20":return {token:e.contractAddress,amount:e.amount,recipient:t};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount,recipient:t};case"ERC721_COLLECTION":return {itemType:2 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};case"ERC1155_COLLECTION":return {itemType:3 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};default:return C()}}var j=class e{constructor(t,r,s,n,i){this.seaportLibFactory=t;this.provider=r;this.seaportContractAddress=s;this.zoneContractAddress=n;this.rateLimitingKey=i;}async prepareBulkSeaportOrders(t,r){let{actions:s}=await this.createSeaportOrders(t,r),n=s.filter(c=>c.type==="approval"),i=await this.provider.getNetwork(),o=n.map(c=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(c.transactionMethods,i.chainId,t)})),d=s.find(c=>c.type==="createBulk");if(!d)throw new Error("No create bulk order action found");let p=await d.getMessageToSign(),{components:a,types:l,value:u}=be(p);return o.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(l,u)}),{actions:o,preparedOrders:a.map(c=>({orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}))}}async prepareSeaportOrder(t,r,s,n,i,o){let{actions:d}=await this.createSeaportOrder(t,r,s,n,i,o),p=[],a=d.find(m=>m.type==="approval");a&&p.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(a.transactionMethods,(await this.provider.getNetwork()).chainId,t)});let l=d.find(m=>m.type==="create");if(!l)throw new Error("No create order action found");let u=await l.getMessageToSign(),c=_e(u);return p.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromOrderComponents(c)}),{actions:p,orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}}async fulfillOrder(t,r,s,n,i){let{orderComponents:o,tips:d}=G(t),p=this.getSeaportLib(t),a=(await this.provider.getNetwork()).chainId,l={order:{parameters:o,signature:t.signature},unitsToFill:n,extraData:s,tips:d};i&&(l.considerationCriteria=i);let{actions:u}=await p.fulfillOrders({accountAddress:r,fulfillOrderDetails:[l]}),c=[],m=u.filter(E=>E.type==="approval");m.length>0&&m.forEach(E=>{c.push({type:"TRANSACTION",buildTransaction:g(E.transactionMethods,a,r),purpose:"APPROVAL"});});let I=u.find(E=>E.type==="exchange");if(!I)throw new Error("No exchange action found");return c.push({type:"TRANSACTION",buildTransaction:g(I.transactionMethods,a,r),purpose:"FULFILL_ORDER"}),{actions:c,expiration:e.getExpirationISOTimeFromExtraData(s),order:N(t)}}async fulfillBulkOrders(t,r){let s=t.map(a=>{let{orderComponents:l,tips:u}=G(a.order),c={order:{parameters:l,signature:a.order.signature},unitsToFill:a.unitsToFill,extraData:a.extraData,tips:u};return a.considerationCriteria&&a.considerationCriteria.length>0&&(c.considerationCriteria=a.considerationCriteria),c}),{actions:n}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:s,accountAddress:r}),i=[],o=n.filter(a=>a.type==="approval"),d=(await this.provider.getNetwork()).chainId;o.length>0&&o.forEach(a=>{i.push({type:"TRANSACTION",buildTransaction:g(a.transactionMethods,d,r),purpose:"APPROVAL"});});let p=n.find(a=>a.type==="exchange");if(!p)throw new Error("No exchange action found");return i.push({type:"TRANSACTION",buildTransaction:g(p.transactionMethods,(await this.provider.getNetwork()).chainId,r),purpose:"FULFILL_ORDER"}),{actions:i,expiration:s.map(a=>e.getExpirationISOTimeFromExtraData(a.extraData)).reduce((a,l)=>new Date(a)<new Date(l)?a:l)}}async cancelOrders(t,r){let s=t.map(o=>G(o).orderComponents),i=await this.getSeaportLib(t[0]).cancelOrders(s,r);return {type:"TRANSACTION",buildTransaction:g(i,(await this.provider.getNetwork()).chainId,r),purpose:"CANCEL"}}createSeaportOrders(t,r){return this.getSeaportLib().createBulkOrders(r.map(n=>{let{offerItem:i,considerationItem:o,allowPartialFills:d,orderStart:p,orderExpiry:a}=n;return {allowPartialFills:d,offer:[Pe(i)],consideration:[Be(o,t)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(a.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),t)}createSeaportOrder(t,r,s,n,i,o){return this.getSeaportLib().createOrder({allowPartialFills:n,offer:[Pe(r)],consideration:[Be(s,t)],startTime:(i.getTime()/1e3).toFixed(0),endTime:(o.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},t)}async getTypedDataFromBulkOrderComponents(t,r){delete t.EIP712Domain;let{chainId:s}=await this.provider.getNetwork();return {domain:{name:oe,version:O,chainId:s,verifyingContract:this.seaportContractAddress},types:t,value:r}}async getTypedDataFromOrderComponents(t){let{chainId:r}=await this.provider.getNetwork();return {domain:{name:oe,version:O,chainId:r,verifyingContract:this.seaportContractAddress},types:M,value:t}}getSeaportLib(t){let r=t?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(r)}static getExpirationISOTimeFromExtraData(t){let r=t.slice(44,60),s=parseInt(r,16);return new Date(s*1e3).toISOString()}};function W(e){switch(e.itemType){case 0:return {type:"NATIVE",amount:e.startAmount};case 1:return {type:"ERC20",contract_address:e.token,amount:e.startAmount};case 2:return {type:"ERC721",contract_address:e.token,token_id:e.identifierOrCriteria};case 3:return {type:"ERC1155",contract_address:e.token,token_id:e.identifierOrCriteria,amount:e.startAmount};case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};default:return C(e.itemType)}}function ae(e){if(e.itemType!==1)throw new Error(`Expected ERC20 item, got ${e.itemType}`);return {type:"ERC20",contract_address:e.token,amount:e.startAmount}}function xe(e){switch(e.itemType){case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};case 1:case 0:case 2:case 3:throw new Error(`Unsupported item type ${e.itemType}`);default:return C(e.itemType)}}function K(e){switch(e){case 2:return y.order_type.FULL_RESTRICTED;case 3:return y.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${e}`);default:return C()}}var Y=class{constructor(t,r,s){this.orderbookService=t;this.chainName=r;this.seaportAddress=s;}async fulfillmentData(t){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:t})}async getListing(t){return this.orderbookService.getListing({chainName:this.chainName,listingId:t})}async getBid(t){return this.orderbookService.getBid({chainName:this.chainName,bidId:t})}async getCollectionBid(t){return this.orderbookService.getCollectionBid({chainName:this.chainName,collectionBidId:t})}async getTrade(t){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:t})}async listListings(t){return this.orderbookService.listListings({chainName:this.chainName,...t})}async listBids(t){return this.orderbookService.listBids({chainName:this.chainName,...t})}async listCollectionBids(t){return this.orderbookService.listCollectionBids({chainName:this.chainName,...t})}async listTrades(t){return this.orderbookService.listTrades({chainName:this.chainName,...t})}async cancelOrders(t,r,s){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:r,orders:t,signature:s}})}async createListing({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a listing");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a listing");if(![2,3].includes(r.offer[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be listed");if(![0,1].includes(r.consideration[0].itemType))throw new Error("Only Native / ERC20 tokens can be used as currency items in a listing");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(W),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a bid");if(![2,3].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be bid against");return this.orderbookService.createBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a collection bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a collection bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a collection bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");return this.orderbookService.createCollectionBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(xe),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}};var J=class{constructor(t,r,s,n){this.chainName=r;this.seaportAddress=s;this.orderbookClient=new P({BASE:t,HEADERS:n?{"x-api-key":n}:void 0});}orderbookClient;create(){return new Y(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var yt="imtbl-zkevm-testnet",gt="imtbl-zkevm-mainnet";function Z(e,t){let r=new FetchRequest(e);return t&&r.setHeader("x-api-key",t),new JsonRpcProvider(r)}function ke(e){switch(e.baseConfig.environment){case Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:yt,provider:Z("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:gt,provider:Z("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}var X=class{constructor(t,r){this.defaultSeaportContractAddress=t;this.provider=r;}create(t){let r=t??this.defaultSeaportContractAddress,s=this.provider;return s.getSigner=async function(i){i==null&&(i=0);let o=this.send("eth_accounts",[]);if(typeof i=="number"){let d=await o;if(i>=d.length)throw new Error("no such account");return new JsonRpcSigner(this,d[i])}return new JsonRpcSigner(this,i)},new Seaport(s,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}};var de=class e{apiClient;seaport;orderbookConfig;constructor(t){let s={...ke(t),...t.overrides};if(t.overrides?.jsonRpcProviderUrl&&(s.provider=Z(t.overrides?.jsonRpcProviderUrl,t.baseConfig.rateLimitingKey)),!s)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=s;let{apiEndpoint:n,chainName:i}=this.orderbookConfig;if(!n)throw new Error("API endpoint must be provided");this.apiClient=new J(n,i,this.orderbookConfig.seaportContractAddress,t.baseConfig.rateLimitingKey).create();let o=new X(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new j(o,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,t.baseConfig.rateLimitingKey);}static defaultOrderExpiry(){return new Date(Date.now()+1e3*60*60*24*365*2)}config(){return this.orderbookConfig}async getListing(t){let r=await this.apiClient.getListing(t);return {result:h(r.result)}}async getBid(t){let r=await this.apiClient.getBid(t);return {result:B(r.result)}}async getCollectionBid(t){let r=await this.apiClient.getCollectionBid(t);return {result:x(r.result)}}async getTrade(t){let r=await this.apiClient.getTrade(t);return {result:te(r.result)}}async listListings(t){let r=await this.apiClient.listListings(t);return {page:k(r.page),result:r.result.map(h)}}async listBids(t){let r=await this.apiClient.listBids(t);return {page:k(r.page),result:r.result.map(B)}}async listCollectionBids(t){let r=await this.apiClient.listCollectionBids(t);return {page:k(r.page),result:r.result.map(x)}}async listTrades(t){let r=await this.apiClient.listTrades(t);return {page:k(r.page),result:r.result.map(te)}}async prepareBulkListings({makerAddress:t,listingParams:r}){if(r.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(r.length===1){let o=await this.seaport.prepareSeaportOrder(t,r[0].sell,r[0].buy,r[0].sell.type==="ERC1155",r[0].orderStart||new Date,r[0].orderExpiry||e.defaultOrderExpiry());return {actions:o.actions,completeListings:async d=>{let p=await this.createListing({makerFees:r[0].makerFees,orderComponents:o.orderComponents,orderHash:o.orderHash,orderSignature:typeof d=="string"?d:d[0]});return {result:[{success:!0,orderHash:o.orderHash,order:p.result}]}}}}if(await this.orderbookConfig.provider.getCode(t)!=="0x"){track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:t,listingsCount:r.length});let o=await Promise.all(r.map(a=>this.seaport.prepareSeaportOrder(t,a.sell,a.buy,a.sell.type==="ERC1155",a.orderStart||new Date,a.orderExpiry||e.defaultOrderExpiry()))),d=[];return {actions:o.flatMap(a=>{let l=[];return a.actions.forEach(u=>{if(u.type==="TRANSACTION"){let c=a.orderComponents.offer[0].token;d.includes(c)||(d.push(c),l.push(u));}else l.push(u);}),l}),completeListings:async a=>{if(typeof a=="string")throw new Error("A signature per listing must be provided for smart contract wallets");return {result:(await Promise.all(o.map((c,m)=>{let I=a[m];return this.apiClient.createListing({makerFees:r[m].makerFees,orderComponents:c.orderComponents,orderHash:c.orderHash,orderSignature:I}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:o[m].orderHash,order:c?h(c.result):void 0}))}}}}track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:t,listingsCount:r.length});let{actions:n,preparedOrders:i}=await this.seaport.prepareBulkSeaportOrders(t,r.map(o=>({offerItem:o.sell,considerationItem:o.buy,allowPartialFills:o.sell.type==="ERC1155",orderStart:o.orderStart||new Date,orderExpiry:o.orderExpiry||e.defaultOrderExpiry()})));return {actions:n,completeListings:async o=>{let d=typeof o=="object";if(d&&o.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let p=i.map(c=>c.orderComponents),a=d?o[0]:o,l=Le(a,p);return {result:(await Promise.all(p.map((c,m)=>{let I=l[m],E=i[m],De=r[m];return this.apiClient.createListing({orderComponents:c,orderHash:E.orderHash,orderSignature:I,makerFees:De.makerFees}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:i[m].orderHash,order:c?h(c.result):void 0}))}}}}async prepareListing({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,r.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createListing(t){let r=await this.apiClient.createListing(t);return {result:h(r.result)}}async prepareBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,s.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createBid(t){let r=await this.apiClient.createBid(t);return {result:B(r.result)}}async prepareCollectionBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,!0,n||new Date,i||e.defaultOrderExpiry())}async createCollectionBid(t){let r=await this.apiClient.createCollectionBid(t);return {result:x(r.result)}}async fulfillOrder(t,r,s,n,i){let o={order_id:t,taker_address:r,fees:s.map(u=>({type:f.type.TAKER_ECOSYSTEM,amount:u.amount,recipient_address:u.recipientAddress}))},d=i?[{identifier:i,proof:[]}]:void 0;i&&(o.token_id=i);let p=await this.apiClient.fulfillmentData([o]);if(p.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment data: ${p.result.unfulfillable_orders[0].reason}`);if(p.result.fulfillable_orders?.length!==1)throw new Error("unexpected fulfillable order result length");let a=p.result.fulfillable_orders[0].extra_data,l=p.result.fulfillable_orders[0].order;if(l.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${l.status}`);return this.seaport.fulfillOrder(l,r,a,n,d)}async fulfillBulkOrders(t,r){let s=t.map(i=>{let o="listingId"in i;return {orderId:o?i.listingId:i.orderId,takerFees:i.takerFees,amountToFill:i.amountToFill,tokenId:o?void 0:i.tokenId}}),n=await this.apiClient.fulfillmentData(s.map(i=>({order_id:i.orderId,taker_address:r,fees:i.takerFees.map(o=>({type:f.type.TAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),token_id:i?.tokenId})));try{let i=n.result.fulfillable_orders.map(o=>{let d=s.find(a=>a.orderId===o.order.id&&a.tokenId===o.token_id);if(!d){let a=`Could not find order for order ${o.order.id}`;throw o.token_id&&(a+=` and token ID ${o.token_id}`),new Error(a)}let p=[];return d.tokenId&&p.push({identifier:d.tokenId,proof:[]}),{extraData:o.extra_data,order:o.order,unitsToFill:d.amountToFill,considerationCriteria:p}});return {...await this.seaport.fulfillBulkOrders(i,r),fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,tokenId:o.token_id,reason:o.reason})),sufficientBalance:!0}}catch(i){if(String(i).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,reason:o.reason})),sufficientBalance:!1};throw i}}async prepareOrderCancellations(t){let r=await this.orderbookConfig.provider.getNetwork(),s={name:"imtbl-order-book",chainId:Number(r.chainId),verifyingContract:this.orderbookConfig.seaportContractAddress},n={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},i={orders:t.map(o=>({id:o}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:s,types:n,value:i}}}}async cancelOrders(t,r,s){return this.apiClient.cancelOrders(t,r,s)}async cancelOrdersOnChain(t,r){let s=Promise.all(t.map(l=>this.apiClient.getListing(l).catch(u=>{if(u.status!==404)throw u}))),n=Promise.all(t.map(l=>this.apiClient.getBid(l).catch(u=>{if(u.status!==404)throw u}))),i=Promise.all(t.map(l=>this.apiClient.getCollectionBid(l).catch(u=>{if(u.status!==404)throw u}))),o=[await Promise.all([s,n,i])].flat(2).filter(l=>l!==void 0).map(l=>l.result);if(o.length!==t.length){let l=t.filter(u=>!o.some(c=>c.id===u));throw new Error(`Orders ${l} not found`)}for(let l of o)if(l.account_address!==r.toLowerCase())throw new Error(`Only account ${l.account_address} can cancel order ${l.id}`);let d=o.map(l=>l.protocol_data.seaport_address);if(new Set(d).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(o,r)}}};var ht={estimatedFulfillmentGasGwei:4e5};
9
+ var B=class{constructor(t){this.config=t;}};var I=class extends Error{url;status;statusText;body;request;constructor(t,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=t;}};var F=class extends Error{constructor(t){super(t),this.name="CancelError";}get isCancelled(){return !0}},L=class{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(t){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((r,s)=>{this._resolve=r,this._reject=s;let o=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(d));},a=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(d));},i=d=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(d);};return Object.defineProperty(i,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(i,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(i,"isCancelled",{get:()=>this._isCancelled}),t(o,a,i)});}then(t,r){return this._promise.then(t,r)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let t of this._cancelHandlers)t();}catch(t){console.warn("Cancellation threw an error",t);return}this._cancelHandlers.length=0,this._reject?.(new F("Request aborted"));}}get isCancelled(){return this._isCancelled}};var re=e=>e!=null,H=e=>typeof e=="string",te=e=>H(e)&&e!=="",me=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),qe=e=>e instanceof ue,He=e=>e>=200&&e<300,Me=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Ve=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`);},s=(o,a)=>{re(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i);}):typeof a=="object"?Object.entries(a).forEach(([i,d])=>{s(`${o}[${i}]`,d);}):r(o,a));};return Object.entries(e).forEach(([o,a])=>{s(o,a);}),t.length>0?`?${t.join("&")}`:""},Ue=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${Ve(t.query)}`:o},ze=e=>{if(e.formData){let t=new ue,r=(s,o)=>{H(o)||me(o)?t.append(s,o):t.append(s,JSON.stringify(o));};return Object.entries(e.formData).filter(([s,o])=>re(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o);}),t}},q=async(e,t)=>typeof t=="function"?t(e):t,$e=async(e,t,r)=>{let s=await q(t,e.TOKEN),o=await q(t,e.USERNAME),a=await q(t,e.PASSWORD),i=await q(t,e.HEADERS),d=typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...i,...t.headers,...d}).filter(([n,u])=>re(u)).reduce((n,[u,c])=>({...n,[u]:String(c)}),{});if(te(s)&&(p.Authorization=`Bearer ${s}`),te(o)&&te(a)){let n=Me(`${o}:${a}`);p.Authorization=`Basic ${n}`;}return t.body&&(t.mediaType?p["Content-Type"]=t.mediaType:me(t.body)?p["Content-Type"]=t.body.type||"application/octet-stream":H(t.body)?p["Content-Type"]="text/plain":qe(t.body)||(p["Content-Type"]="application/json")),p},Ge=e=>{if(e.body)return e.body},je=async(e,t,r,s,o,a,i)=>{let d=ce.CancelToken.source(),p={url:r,headers:a,data:s??o,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:d.token};i(()=>d.cancel("The user aborted a request."));try{return await ce.request(p)}catch(n){let u=n;if(u.response)return u.response;throw n}},We=(e,t)=>{if(t){let r=e.headers[t];if(H(r))return r}},Ke=e=>{if(e.status!==204)return e.data},Ye=(e,t)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(s)throw new I(e,t,s);if(!t.ok)throw new I(e,t,"Generic Error")},fe=(e,t)=>new L(async(r,s,o)=>{try{let a=Ue(e,t),i=ze(t),d=Ge(t),p=await $e(e,t,i);if(!o.isCancelled){let n=await je(e,t,a,d,i,p,o),u=Ke(n),c=We(n,t.responseHeader),l={url:a,ok:He(n.status),status:n.status,statusText:n.statusText,body:c??u};Ye(t,l),r(l.body);}}catch(a){s(a);}});var M=class extends B{constructor(t){super(t);}request(t){return fe(this.config,t)}};var P=class{constructor(t){this.httpRequest=t;}cancelOrders({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",401:"Unauthorised Request (401)",404:"The specified resource was not found (404)",429:"Too Many Requests (429)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listListings({chainName:t,status:r,sellItemContractAddress:s,buyItemType:o,buyItemContractAddress:a,accountAddress:i,sellItemMetadataId:d,sellItemTokenId:p,fromUpdatedAt:n,pageSize:u,sortBy:c,sortDirection:l,pageCursor:m}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},query:{status:r,sell_item_contract_address:s,buy_item_type:o,buy_item_contract_address:a,account_address:i,sell_item_metadata_id:d,sell_item_token_id:p,from_updated_at:n,page_size:u,sort_by:c,sort_direction:l,page_cursor:m},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:o,accountAddress:a,buyItemMetadataId:i,buyItemTokenId:d,fromUpdatedAt:p,pageSize:n,sortBy:u,sortDirection:c,pageCursor:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:o,account_address:a,buy_item_metadata_id:i,buy_item_token_id:d,from_updated_at:p,page_size:n,sort_by:u,sort_direction:c,page_cursor:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listCollectionBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:o,accountAddress:a,fromUpdatedAt:i,pageSize:d,sortBy:p,sortDirection:n,pageCursor:u}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:o,account_address:a,from_updated_at:i,page_size:d,sort_by:p,sort_direction:n,page_cursor:u},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createCollectionBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listTraitBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:o,accountAddress:a,fromUpdatedAt:i,pageSize:d,sortBy:p,sortDirection:n,pageCursor:u}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/trait-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:o,account_address:a,from_updated_at:i,page_size:d,sort_by:p,sort_direction:n,page_cursor:u},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createTraitBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/trait-bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}getListing({chainName:t,listingId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:t,listing_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getBid({chainName:t,bidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids/{bid_id}",path:{chain_name:t,bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getCollectionBid({chainName:t,collectionBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids/{collection_bid_id}",path:{chain_name:t,collection_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTraitBid({chainName:t,traitBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/trait-bids/{trait_bid_id}",path:{chain_name:t,trait_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:t,accountAddress:r,sellItemContractAddress:s,fromIndexedAt:o,pageSize:a,sortBy:i,sortDirection:d,pageCursor:p}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:t},query:{account_address:r,sell_item_contract_address:s,from_indexed_at:o,page_size:a,sort_by:i,sort_direction:d,page_cursor:p},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:t,tradeId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:t,trade_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}};var S=class{orders;request;constructor(t,r=M){this.request=new r({BASE:t?.BASE??"https://api.immutable.com",VERSION:t?.VERSION??"1.0.0",WITH_CREDENTIALS:t?.WITH_CREDENTIALS??!1,CREDENTIALS:t?.CREDENTIALS??"include",TOKEN:t?.TOKEN,USERNAME:t?.USERNAME,PASSWORD:t?.PASSWORD,HEADERS:t?.HEADERS,ENCODE_PATH:t?.ENCODE_PATH}),this.orders=new P(this.request);}};var Ce;(t=>{(a=>(a.ON_CHAIN="ON_CHAIN",a.OFF_CHAIN="OFF_CHAIN",a.UNDERFUNDED="UNDERFUNDED"))(t.cancellation_type||={});})(Ce||={});var Re;(t=>{(s=>s.FILLED="FILLED")(t.reason_code||={});})(Re||={});var C;(t=>{(i=>(i.ROYALTY="ROYALTY",i.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",i.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",i.PROTOCOL="PROTOCOL"))(t.type||={});})(C||={});var f;(t=>{(i=>(i.LISTING="LISTING",i.BID="BID",i.COLLECTION_BID="COLLECTION_BID",i.TRAIT_BID="TRAIT_BID"))(t.type||={});})(f||={});var V=(i=>(i.PENDING="PENDING",i.ACTIVE="ACTIVE",i.INACTIVE="INACTIVE",i.FILLED="FILLED",i.EXPIRED="EXPIRED",i.CANCELLED="CANCELLED",i))(V||{});var y;(t=>{(o=>(o.FULL_RESTRICTED="FULL_RESTRICTED",o.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(t.order_type||={});})(y||={});function R(e){throw new Error("Unreachable")}function T(e){if(e.type!==f.type.LISTING)throw new Error("Order type must be LISTING");let t=e.sell.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Listing sell items must either ERC721 or ERC1155")}),r=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Listing buy items must be either NATIVE or ERC20")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function x(e){if(e.type!==f.type.BID)throw new Error("Order type must be BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Bid buy items must either ERC721 or ERC1155")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function Je(e){return e?.length?e.map(t=>({traitType:t.trait_type,values:[...t.values]})):[]}function N(e){if(e.type!==f.type.COLLECTION_BID)throw new Error("Order type must be COLLECTION_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function w(e){if(e.type!==f.type.TRAIT_BID)throw new Error("Order type must be TRAIT_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Trait bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:s.contract_address,amount:s.amount};throw new Error("Trait bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at,traitCriteria:Je(e.trait_criteria)}}function k(e){switch(e.type){case f.type.LISTING:return T(e);case f.type.BID:return x(e);case f.type.COLLECTION_BID:return N(e);case f.type.TRAIT_BID:return w(e);default:return R(e.type)}}function se(e){let t=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Buy items must be NATIVE, ERC20, ERC721 or ERC1155")}),r=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Sell items must be ERC20, ERC721 or ERC1155")});return {id:e.id,orderId:e.order_id,buy:t,sell:r,buyerFees:e.buyer_fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),chain:e.chain,indexedAt:e.indexed_at,blockchainMetadata:{blockNumber:e.blockchain_metadata.block_number,logIndex:e.blockchain_metadata.log_index,transactionHash:e.blockchain_metadata.transaction_hash,transactionIndex:e.blockchain_metadata.transaction_index},buyerAddress:e.buyer_address,makerAddress:e.maker_address,sellerAddress:e.seller_address,takerAddress:e.taker_address}}function _(e){return {nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}var Ze=(o=>(o[o.MAKER_ECOSYSTEM=C.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",o[o.TAKER_ECOSYSTEM=C.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",o[o.PROTOCOL=C.type.PROTOCOL]="PROTOCOL",o[o.ROYALTY=C.type.ROYALTY]="ROYALTY",o))(Ze||{}),ie=(r=>(r.TRANSACTION="TRANSACTION",r.SIGNABLE="SIGNABLE",r))(ie||{}),ye=(s=>(s.APPROVAL="APPROVAL",s.FULFILL_ORDER="FULFILL_ORDER",s.CANCEL="CANCEL",s))(ye||{}),oe=(s=>(s.CREATE_LISTING="CREATE_ORDER",s.CREATE_ORDER="CREATE_ORDER",s.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",s))(oe||{});var ae="ImmutableSeaport",g="1.5",U={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]};var Xe={integer:0,address:zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},ne=e=>e===void 0?!1:e!=null&&(["string","number"].includes(typeof e)&&BigInt(e)===0n||Array.isArray(e)&&e.every(ne)||typeof e=="object"&&Object.values(e).every(ne)||typeof e=="boolean"&&e===!1);function Qe(e){let[,t]=e.match(/^bytes(\d+)$/)??[];return t?zeroPadValue("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),Xe[e])}var A=class e{constructor(t){this.types=t;for(let r in t){let s=this.getDefaultValue(r);if(this.defaultValues[r]=s,!ne(s))throw new Error(`Got non-empty value for type ${r} in default generator: ${s}`)}}defaultValues={};static from(t,r){let{defaultValues:s}=new e(t);return r?s[r]:s}getDefaultValue(t){if(this.defaultValues[t])return this.defaultValues[t];let r=Qe(t);if(r!==void 0)return r;let s=t.match(/^(.*)(\x5b(\d*)\x5d)$/);if(s){let a=s[1],i=parseInt(s[3]);if(i>0){let d=this.getDefaultValue(a);return Array(i).fill(d)}return []}let o=this.types[t];if(o)return o.reduce((a,{name:i,type:d})=>({...a,[i]:this.getDefaultValue(d)}),{});throw new Error(`unknown type: ${t}`)}};var st=(e,t)=>Array(e).fill(0).map((r,s)=>t(s)),de=(e,t)=>st(Math.ceil(e.length/t),r=>e.slice(r*t,(r+1)*t)),he=e=>toBeHex(e.toString("hex")),b=e=>Buffer.from(e.slice(2),"hex"),z=e=>b(keccak256(e)),it=e=>z(concat(e)),v=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),Ee=(e,t=!0)=>{if(e.length===0)throw new Error("empty tree");let s=[e.map(o=>{let a=Buffer.isBuffer(o)?o:b(o);return t?z(a):a})];for(;s[s.length-1].length>1;)s.push(ot(s[s.length-1]));return s[s.length-1][0]},ot=e=>de(e,2).map(it);var pt=(e,t)=>new MerkleTree(e.map(b),z,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:b(t)}),ct=(e,t,r=`0x${"ff".repeat(64)}`)=>concat([r,`0x${e.toString(16).padStart(6,"0")}`,AbiCoder.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]),$=class{constructor(t,r,s,o,a){this.types=t;this.rootType=r;this.leafType=s;this.elements=o;this.depth=a;let i=TypedDataEncoder.from(t);this.encoder=i,this.leafHasher=d=>i.hashStruct(s,d),this.defaultNode=A.from(t,s),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=pt(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:t}=this;return v([...t],this.completedSize,this.defaultNode)}getCompleteLeaves(){let t=this.elements.map(this.leafHasher);return v([...t],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(t){let s=this.getCompleteLeaves()[t],o=this.tree.getHexProof(s,t),a=this.tree.getHexRoot();return {leaf:s,proof:o,root:a}}getEncodedProofAndSignature(t,r){let{proof:s}=this.getProof(t);return ct(t,s,r)}getDataToSign(){let t=this.getCompleteElements();for(;t.length>2;)t=de(t,2);return t}add(t){this.elements.push(t);}getBulkOrderHash(){let t=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),r=this.getCompleteLeaves().map(b),s=he(Ee(r,!1)),o=keccak256(toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(keccak256(concat([o,s]))!==t)throw new Error("expected derived bulk order hash to match");return t}};function ut(e){return {...U,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}function mt(e){return Math.max(Math.ceil(Math.log2(e)),1)}function Ie(e,t=0,r=mt(e.length+t)){let s=ut(r),o=A.from(s,"OrderComponents"),a=[...e];return t>0&&(a=[...v([],t,o),...e]),new $(s,"BulkOrder","OrderComponents",a,r)}function be(e){if([0,1,2,3].includes(Number(e)))return Number(e);throw new Error(`Unknown order type ${e}`)}function G(e){if([0,1,2,3,4,5].includes(Number(e)))return Number(e);throw new Error(`Unknown item type ${e}`)}function Be(e){let r=JSON.parse(e).message;return {...r,orderType:be(r.orderType),salt:toBeHex(BigInt(r.salt)),offer:r.offer.map(s=>({...s,itemType:G(s.itemType)})),consideration:r.consideration.map(s=>({...s,itemType:G(s.itemType)}))}}function Le(e){let t=JSON.parse(e);return {components:t.message.tree.flat(1/0).filter(s=>s.offerer!=="0x0000000000000000000000000000000000000000").map(s=>({...s,orderType:be(s.orderType),salt:toBeHex(BigInt(s.salt)),offer:s.offer.map(o=>({...o,itemType:G(o.itemType)})),consideration:s.consideration.map(o=>({...o,itemType:G(o.itemType)}))})),types:t.types,value:t.message}}function Pe(e,t){let r=Ie(t);return t.map((s,o)=>r.getEncodedProofAndSignature(o,e))}function Ct(e){switch(e.type){case"NATIVE":throw new Error("NATIVE items are not supported in the offer");case"ERC20":return {itemType:1 .valueOf(),token:e.contract_address,identifierOrCriteria:"0",startAmount:e.amount,endAmount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:"1",endAmount:"1"};case"ERC1155":return {itemType:3 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:e.amount,endAmount:e.amount};case"ERC721_COLLECTION":throw new Error("ERC721_COLLECTION items are not supported in the offer");case"ERC1155_COLLECTION":throw new Error("ERC1155_COLLECTION items are not supported in the offer");default:return R()}}function Rt(e,t){switch(e.type){case"NATIVE":return {itemType:0 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:ZeroAddress,identifierOrCriteria:"0",recipient:t};case"ERC20":return {itemType:1 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC721":return {itemType:2 .valueOf(),startAmount:"1",endAmount:"1",token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC721_COLLECTION":return {itemType:4 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC1155_COLLECTION":return {itemType:5 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};default:return R()}}function W(e){let t=e.sell.map(Ct),r=e.buy.map(i=>Rt(i,e.account_address)),s=function(i){switch(i){case f.type.LISTING:return r[0];case f.type.BID:case f.type.COLLECTION_BID:case f.type.TRAIT_BID:return t[0];default:return R()}}(e.type),o=function(i){switch(i){case y.order_type.FULL_RESTRICTED:return 2;case y.order_type.PARTIAL_RESTRICTED:return 3;default:return R()}}(e.protocol_data.order_type),a=e.fees.map(i=>({amount:i.amount,itemType:s.itemType,recipient:i.recipient_address,token:s.token,identifierOrCriteria:s.identifierOrCriteria}));return {orderComponents:{offerer:e.account_address,zone:e.protocol_data.zone_address,offer:t,consideration:r,orderType:o.valueOf(),startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),zoneHash:ZeroHash,salt:e.salt,conduitKey:ZeroHash,counter:e.protocol_data.counter,totalOriginalConsiderationItems:r.length},tips:a}}function h(e,t,r){return async()=>{let s=await e.buildTransaction(),o={to:s.to,from:r,type:s.type,maxFeePerGas:s.maxFeePerGas?BigInt(s.maxFeePerGas):void 0,maxPriorityFeePerGas:s.maxPriorityFeePerGas?BigInt(s.maxPriorityFeePerGas):void 0,value:s.value?BigInt(s.value):void 0,data:s.data,nonce:s.nonce,chainId:t};return o.gasLimit=BigInt(await e.estimateGas()),o.gasLimit+=o.gasLimit/BigInt(5),o}}function xe(e){switch(e.type){case"ERC20":return {token:e.contractAddress,amount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount};default:return R()}}function Ne(e,t){switch(e.type){case"NATIVE":return {amount:e.amount,recipient:t};case"ERC20":return {token:e.contractAddress,amount:e.amount,recipient:t};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount,recipient:t};case"ERC721_COLLECTION":return {itemType:2 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};case"ERC1155_COLLECTION":return {itemType:3 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};default:return R()}}var K=class e{constructor(t,r,s,o,a){this.seaportLibFactory=t;this.provider=r;this.seaportContractAddress=s;this.zoneContractAddress=o;this.rateLimitingKey=a;}async prepareBulkSeaportOrders(t,r){let{actions:s}=await this.createSeaportOrders(t,r),o=s.filter(l=>l.type==="approval"),a=await this.provider.getNetwork(),i=o.map(l=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:h(l.transactionMethods,a.chainId,t)})),d=s.find(l=>l.type==="createBulk");if(!d)throw new Error("No create bulk order action found");let p=await d.getMessageToSign(),{components:n,types:u,value:c}=Le(p);return i.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(u,c)}),{actions:i,preparedOrders:n.map(l=>({orderComponents:l,orderHash:this.getSeaportLib().getOrderHash(l)}))}}async prepareSeaportOrder(t,r,s,o,a,i){let{actions:d}=await this.createSeaportOrder(t,r,s,o,a,i),p=[],n=d.find(m=>m.type==="approval");n&&p.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:h(n.transactionMethods,(await this.provider.getNetwork()).chainId,t)});let u=d.find(m=>m.type==="create");if(!u)throw new Error("No create order action found");let c=await u.getMessageToSign(),l=Be(c);return p.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromOrderComponents(l)}),{actions:p,orderComponents:l,orderHash:this.getSeaportLib().getOrderHash(l)}}async fulfillOrder(t,r,s,o,a){let{orderComponents:i,tips:d}=W(t),p=this.getSeaportLib(t),n=(await this.provider.getNetwork()).chainId,u={order:{parameters:i,signature:t.signature},unitsToFill:o,extraData:s,tips:d};a&&(u.considerationCriteria=a);let{actions:c}=await p.fulfillOrders({accountAddress:r,fulfillOrderDetails:[u]}),l=[],m=c.filter(E=>E.type==="approval");m.length>0&&m.forEach(E=>{l.push({type:"TRANSACTION",buildTransaction:h(E.transactionMethods,n,r),purpose:"APPROVAL"});});let O=c.find(E=>E.type==="exchange");if(!O)throw new Error("No exchange action found");return l.push({type:"TRANSACTION",buildTransaction:h(O.transactionMethods,n,r),purpose:"FULFILL_ORDER"}),{actions:l,expiration:e.getExpirationISOTimeFromExtraData(s),order:k(t)}}async fulfillBulkOrders(t,r){let s=t.map(n=>{let{orderComponents:u,tips:c}=W(n.order),l={order:{parameters:u,signature:n.order.signature},unitsToFill:n.unitsToFill,extraData:n.extraData,tips:c};return n.considerationCriteria&&n.considerationCriteria.length>0&&(l.considerationCriteria=n.considerationCriteria),l}),{actions:o}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:s,accountAddress:r}),a=[],i=o.filter(n=>n.type==="approval"),d=(await this.provider.getNetwork()).chainId;i.length>0&&i.forEach(n=>{a.push({type:"TRANSACTION",buildTransaction:h(n.transactionMethods,d,r),purpose:"APPROVAL"});});let p=o.find(n=>n.type==="exchange");if(!p)throw new Error("No exchange action found");return a.push({type:"TRANSACTION",buildTransaction:h(p.transactionMethods,(await this.provider.getNetwork()).chainId,r),purpose:"FULFILL_ORDER"}),{actions:a,expiration:s.map(n=>e.getExpirationISOTimeFromExtraData(n.extraData)).reduce((n,u)=>new Date(n)<new Date(u)?n:u)}}async cancelOrders(t,r){let s=t.map(i=>W(i).orderComponents),a=await this.getSeaportLib(t[0]).cancelOrders(s,r);return {type:"TRANSACTION",buildTransaction:h(a,(await this.provider.getNetwork()).chainId,r),purpose:"CANCEL"}}createSeaportOrders(t,r){return this.getSeaportLib().createBulkOrders(r.map(o=>{let{offerItem:a,considerationItem:i,allowPartialFills:d,orderStart:p,orderExpiry:n}=o;return {allowPartialFills:d,offer:[xe(a)],consideration:[Ne(i,t)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(n.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),t)}createSeaportOrder(t,r,s,o,a,i){return this.getSeaportLib().createOrder({allowPartialFills:o,offer:[xe(r)],consideration:[Ne(s,t)],startTime:(a.getTime()/1e3).toFixed(0),endTime:(i.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},t)}async getTypedDataFromBulkOrderComponents(t,r){delete t.EIP712Domain;let{chainId:s}=await this.provider.getNetwork();return {domain:{name:ae,version:g,chainId:s,verifyingContract:this.seaportContractAddress},types:t,value:r}}async getTypedDataFromOrderComponents(t){let{chainId:r}=await this.provider.getNetwork();return {domain:{name:ae,version:g,chainId:r,verifyingContract:this.seaportContractAddress},types:U,value:t}}getSeaportLib(t){let r=t?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(r)}static getExpirationISOTimeFromExtraData(t){let r=t.slice(44,60),s=parseInt(r,16);return new Date(s*1e3).toISOString()}};function Y(e){switch(e.itemType){case 0:return {type:"NATIVE",amount:e.startAmount};case 1:return {type:"ERC20",contract_address:e.token,amount:e.startAmount};case 2:return {type:"ERC721",contract_address:e.token,token_id:e.identifierOrCriteria};case 3:return {type:"ERC1155",contract_address:e.token,token_id:e.identifierOrCriteria,amount:e.startAmount};case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};default:return R(e.itemType)}}function J(e){if(e.itemType!==1)throw new Error(`Expected ERC20 item, got ${e.itemType}`);return {type:"ERC20",contract_address:e.token,amount:e.startAmount}}function le(e){switch(e.itemType){case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};case 1:case 0:case 2:case 3:throw new Error(`Unsupported item type ${e.itemType}`);default:return R(e.itemType)}}function D(e){switch(e){case 2:return y.order_type.FULL_RESTRICTED;case 3:return y.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${e}`);default:return R()}}var Z=class{constructor(t,r,s){this.orderbookService=t;this.chainName=r;this.seaportAddress=s;}async fulfillmentData(t){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:t})}async getListing(t){return this.orderbookService.getListing({chainName:this.chainName,listingId:t})}async getBid(t){return this.orderbookService.getBid({chainName:this.chainName,bidId:t})}async getCollectionBid(t){return this.orderbookService.getCollectionBid({chainName:this.chainName,collectionBidId:t})}async getTraitBid(t){return this.orderbookService.getTraitBid({chainName:this.chainName,traitBidId:t})}async getTrade(t){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:t})}async listListings(t){return this.orderbookService.listListings({chainName:this.chainName,...t})}async listBids(t){return this.orderbookService.listBids({chainName:this.chainName,...t})}async listCollectionBids(t){return this.orderbookService.listCollectionBids({chainName:this.chainName,...t})}async listTraitBids(t){return this.orderbookService.listTraitBids({chainName:this.chainName,...t})}async listTrades(t){return this.orderbookService.listTrades({chainName:this.chainName,...t})}async cancelOrders(t,r,s){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:r,orders:t,signature:s}})}async createListing({orderHash:t,orderComponents:r,orderSignature:s,makerFees:o}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a listing");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a listing");if(![2,3].includes(r.offer[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be listed");if(![0,1].includes(r.consideration[0].itemType))throw new Error("Only Native / ERC20 tokens can be used as currency items in a listing");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(Y),fees:o.map(a=>({type:C.type.MAKER_ECOSYSTEM,amount:a.amount,recipient_address:a.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:D(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:g,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(Y),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:o}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a bid");if(![2,3].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be bid against");return this.orderbookService.createBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(Y),fees:o.map(a=>({type:C.type.MAKER_ECOSYSTEM,amount:a.amount,recipient_address:a.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:D(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:g,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(J),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:o}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a collection bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a collection bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a collection bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");return this.orderbookService.createCollectionBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(le),fees:o.map(a=>({type:C.type.MAKER_ECOSYSTEM,amount:a.amount,recipient_address:a.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:D(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:g,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(J),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createTraitBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:o,traitCriteria:a}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a trait bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a trait bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a trait bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");if(!a?.length)throw new Error("At least one trait criterion is required for a trait bid");return this.orderbookService.createTraitBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(le),fees:o.map(i=>({type:C.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:D(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:g,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(J),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString(),trait_criteria:a.map(i=>({trait_type:i.traitType,values:i.values}))}})}};var X=class{constructor(t,r,s,o){this.chainName=r;this.seaportAddress=s;this.orderbookClient=new S({BASE:t,HEADERS:o?{"x-api-key":o}:void 0});}orderbookClient;create(){return new Z(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var ht="imtbl-zkevm-testnet",Et="imtbl-zkevm-mainnet";function Q(e,t){let r=new FetchRequest(e);return t&&r.setHeader("x-api-key",t),new JsonRpcProvider(r)}function ke(e){switch(e.baseConfig.environment){case Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:ht,provider:Q("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:Et,provider:Q("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}var ee=class{constructor(t,r){this.defaultSeaportContractAddress=t;this.provider=r;}create(t){let r=t??this.defaultSeaportContractAddress,s=this.provider;return s.getSigner=async function(a){a==null&&(a=0);let i=this.send("eth_accounts",[]);if(typeof a=="number"){let d=await i;if(a>=d.length)throw new Error("no such account");return new JsonRpcSigner(this,d[a])}return new JsonRpcSigner(this,a)},new Seaport(s,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}};var pe=class e{apiClient;seaport;orderbookConfig;constructor(t){let s={...ke(t),...t.overrides};if(t.overrides?.jsonRpcProviderUrl&&(s.provider=Q(t.overrides?.jsonRpcProviderUrl,t.baseConfig.rateLimitingKey)),!s)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=s;let{apiEndpoint:o,chainName:a}=this.orderbookConfig;if(!o)throw new Error("API endpoint must be provided");this.apiClient=new X(o,a,this.orderbookConfig.seaportContractAddress,t.baseConfig.rateLimitingKey).create();let i=new ee(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new K(i,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,t.baseConfig.rateLimitingKey);}static defaultOrderExpiry(){return new Date(Date.now()+1e3*60*60*24*365*2)}config(){return this.orderbookConfig}async getListing(t){let r=await this.apiClient.getListing(t);return {result:T(r.result)}}async getBid(t){let r=await this.apiClient.getBid(t);return {result:x(r.result)}}async getCollectionBid(t){let r=await this.apiClient.getCollectionBid(t);return {result:N(r.result)}}async getTraitBid(t){let r=await this.apiClient.getTraitBid(t);return {result:w(r.result)}}async getTrade(t){let r=await this.apiClient.getTrade(t);return {result:se(r.result)}}async listListings(t){let r=await this.apiClient.listListings(t);return {page:_(r.page),result:r.result.map(T)}}async listBids(t){let r=await this.apiClient.listBids(t);return {page:_(r.page),result:r.result.map(x)}}async listCollectionBids(t){let r=await this.apiClient.listCollectionBids(t);return {page:_(r.page),result:r.result.map(N)}}async listTraitBids(t){let r=await this.apiClient.listTraitBids(t);return {page:_(r.page),result:r.result.map(w)}}async listTrades(t){let r=await this.apiClient.listTrades(t);return {page:_(r.page),result:r.result.map(se)}}async prepareBulkListings({makerAddress:t,listingParams:r}){if(r.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(r.length===1){let i=await this.seaport.prepareSeaportOrder(t,r[0].sell,r[0].buy,r[0].sell.type==="ERC1155",r[0].orderStart||new Date,r[0].orderExpiry||e.defaultOrderExpiry());return {actions:i.actions,completeListings:async d=>{let p=await this.createListing({makerFees:r[0].makerFees,orderComponents:i.orderComponents,orderHash:i.orderHash,orderSignature:typeof d=="string"?d:d[0]});return {result:[{success:!0,orderHash:i.orderHash,order:p.result}]}}}}if(await this.orderbookConfig.provider.getCode(t)!=="0x"){track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:t,listingsCount:r.length});let i=await Promise.all(r.map(n=>this.seaport.prepareSeaportOrder(t,n.sell,n.buy,n.sell.type==="ERC1155",n.orderStart||new Date,n.orderExpiry||e.defaultOrderExpiry()))),d=[];return {actions:i.flatMap(n=>{let u=[];return n.actions.forEach(c=>{if(c.type==="TRANSACTION"){let l=n.orderComponents.offer[0].token;d.includes(l)||(d.push(l),u.push(c));}else u.push(c);}),u}),completeListings:async n=>{if(typeof n=="string")throw new Error("A signature per listing must be provided for smart contract wallets");return {result:(await Promise.all(i.map((l,m)=>{let O=n[m];return this.apiClient.createListing({makerFees:r[m].makerFees,orderComponents:l.orderComponents,orderHash:l.orderHash,orderSignature:O}).catch(()=>{})}))).map((l,m)=>({success:!!l,orderHash:i[m].orderHash,order:l?T(l.result):void 0}))}}}}track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:t,listingsCount:r.length});let{actions:o,preparedOrders:a}=await this.seaport.prepareBulkSeaportOrders(t,r.map(i=>({offerItem:i.sell,considerationItem:i.buy,allowPartialFills:i.sell.type==="ERC1155",orderStart:i.orderStart||new Date,orderExpiry:i.orderExpiry||e.defaultOrderExpiry()})));return {actions:o,completeListings:async i=>{let d=typeof i=="object";if(d&&i.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let p=a.map(l=>l.orderComponents),n=d?i[0]:i,u=Pe(n,p);return {result:(await Promise.all(p.map((l,m)=>{let O=u[m],E=a[m],Fe=r[m];return this.apiClient.createListing({orderComponents:l,orderHash:E.orderHash,orderSignature:O,makerFees:Fe.makerFees}).catch(()=>{})}))).map((l,m)=>({success:!!l,orderHash:a[m].orderHash,order:l?T(l.result):void 0}))}}}}async prepareListing({makerAddress:t,sell:r,buy:s,orderStart:o,orderExpiry:a}){return this.seaport.prepareSeaportOrder(t,r,s,r.type==="ERC1155",o||new Date,a||e.defaultOrderExpiry())}async createListing(t){let r=await this.apiClient.createListing(t);return {result:T(r.result)}}async prepareBid({makerAddress:t,sell:r,buy:s,orderStart:o,orderExpiry:a}){return this.seaport.prepareSeaportOrder(t,r,s,s.type==="ERC1155",o||new Date,a||e.defaultOrderExpiry())}async createBid(t){let r=await this.apiClient.createBid(t);return {result:x(r.result)}}async prepareCollectionBid({makerAddress:t,sell:r,buy:s,orderStart:o,orderExpiry:a}){return this.seaport.prepareSeaportOrder(t,r,s,!0,o||new Date,a||e.defaultOrderExpiry())}async createCollectionBid(t){let r=await this.apiClient.createCollectionBid(t);return {result:N(r.result)}}async prepareTraitBid({makerAddress:t,sell:r,buy:s,orderStart:o,orderExpiry:a}){return this.seaport.prepareSeaportOrder(t,r,s,!0,o||new Date,a||e.defaultOrderExpiry())}async createTraitBid(t){let r=await this.apiClient.createTraitBid(t);return {result:w(r.result)}}async fulfillOrder(t,r,s,o,a){let i={order_id:t,taker_address:r,fees:s.map(c=>({type:C.type.TAKER_ECOSYSTEM,amount:c.amount,recipient_address:c.recipientAddress}))},d=a?[{identifier:a,proof:[]}]:void 0;a&&(i.token_id=a);let p=await this.apiClient.fulfillmentData([i]);if(p.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment data: ${p.result.unfulfillable_orders[0].reason}`);if(p.result.fulfillable_orders?.length!==1)throw new Error("unexpected fulfillable order result length");let n=p.result.fulfillable_orders[0].extra_data,u=p.result.fulfillable_orders[0].order;if(u.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${u.status}`);return this.seaport.fulfillOrder(u,r,n,o,d)}async fulfillBulkOrders(t,r){let s=t.map(a=>{let i="listingId"in a;return {orderId:i?a.listingId:a.orderId,takerFees:a.takerFees,amountToFill:a.amountToFill,tokenId:i?void 0:a.tokenId}}),o=await this.apiClient.fulfillmentData(s.map(a=>({order_id:a.orderId,taker_address:r,fees:a.takerFees.map(i=>({type:C.type.TAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),token_id:a?.tokenId})));try{let a=o.result.fulfillable_orders.map(i=>{let d=s.find(n=>n.orderId===i.order.id&&n.tokenId===i.token_id);if(!d){let n=`Could not find order for order ${i.order.id}`;throw i.token_id&&(n+=` and token ID ${i.token_id}`),new Error(n)}let p=[];return d.tokenId&&p.push({identifier:d.tokenId,proof:[]}),{extraData:i.extra_data,order:i.order,unitsToFill:d.amountToFill,considerationCriteria:p}});return {...await this.seaport.fulfillBulkOrders(a,r),fulfillableOrders:o.result.fulfillable_orders.map(i=>k(i.order)),unfulfillableOrders:o.result.unfulfillable_orders.map(i=>({orderId:i.order_id,tokenId:i.token_id,reason:i.reason})),sufficientBalance:!0}}catch(a){if(String(a).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:o.result.fulfillable_orders.map(i=>k(i.order)),unfulfillableOrders:o.result.unfulfillable_orders.map(i=>({orderId:i.order_id,reason:i.reason})),sufficientBalance:!1};throw a}}async prepareOrderCancellations(t){let r=await this.orderbookConfig.provider.getNetwork(),s={name:"imtbl-order-book",chainId:Number(r.chainId),verifyingContract:this.orderbookConfig.seaportContractAddress},o={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},a={orders:t.map(i=>({id:i}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:s,types:o,value:a}}}}async cancelOrders(t,r,s){return this.apiClient.cancelOrders(t,r,s)}async cancelOrdersOnChain(t,r){let s=Promise.all(t.map(c=>this.apiClient.getListing(c).catch(l=>{if(l.status!==404)throw l}))),o=Promise.all(t.map(c=>this.apiClient.getBid(c).catch(l=>{if(l.status!==404)throw l}))),a=Promise.all(t.map(c=>this.apiClient.getCollectionBid(c).catch(l=>{if(l.status!==404)throw l}))),i=Promise.all(t.map(c=>this.apiClient.getTraitBid(c).catch(l=>{if(l.status!==404)throw l}))),d=[await Promise.all([s,o,a,i])].flat(2).filter(c=>c!==void 0).map(c=>c.result);if(d.length!==t.length){let c=t.filter(l=>!d.some(m=>m.id===l));throw new Error(`Orders ${c} not found`)}for(let c of d)if(c.account_address!==r.toLowerCase())throw new Error(`Only account ${c.account_address} can cancel order ${c.id}`);let p=d.map(c=>c.protocol_data.seaport_address);if(new Set(p).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(d,r)}}};var Ot={estimatedFulfillmentGasGwei:4e5};
10
10
 
11
- export { re as ActionType, Ye as FeeType, H as OrderStatusName, de as Orderbook, se as SignablePurpose, Ce as TransactionPurpose, ht as constants };
11
+ export { ie as ActionType, Ze as FeeType, V as OrderStatusName, pe as Orderbook, oe as SignablePurpose, ye as TransactionPurpose, Ot as constants };
@@ -1,8 +1,8 @@
1
- import { BidResult, CancelOrdersResult, CollectionBidResult, ListBidsResult, ListCollectionBidsResult, ListingResult, ListListingsResult, ListTradeResult, OrdersService, TradeResult } from '../openapi/sdk';
1
+ import { BidResult, CancelOrdersResult, CollectionBidResult, ListBidsResult, ListCollectionBidsResult, ListingResult, ListListingsResult, ListTradeResult, ListTraitBidsResult, OrdersService, TradeResult, TraitBidResult } from '../openapi/sdk';
2
2
  import { FulfillableOrder } from '../openapi/sdk/models/FulfillableOrder';
3
3
  import { FulfillmentDataRequest } from '../openapi/sdk/models/FulfillmentDataRequest';
4
4
  import { UnfulfillableOrder } from '../openapi/sdk/models/UnfulfillableOrder';
5
- import { CreateBidParams, CreateListingParams, ListBidsParams, ListCollectionBidsParams, ListListingsParams, ListTradesParams } from '../types';
5
+ import { CreateBidParams, CreateCollectionBidParams, CreateListingParams, CreateTraitBidParams, ListBidsParams, ListCollectionBidsParams, ListListingsParams, ListTraitBidsParams, ListTradesParams } from '../types';
6
6
  export declare class ImmutableApiClient {
7
7
  private readonly orderbookService;
8
8
  private readonly chainName;
@@ -17,13 +17,16 @@ export declare class ImmutableApiClient {
17
17
  getListing(listingId: string): Promise<ListingResult>;
18
18
  getBid(bidId: string): Promise<BidResult>;
19
19
  getCollectionBid(collectionBidId: string): Promise<CollectionBidResult>;
20
+ getTraitBid(traitBidId: string): Promise<TraitBidResult>;
20
21
  getTrade(tradeId: string): Promise<TradeResult>;
21
22
  listListings(listOrderParams: ListListingsParams): Promise<ListListingsResult>;
22
23
  listBids(listOrderParams: ListBidsParams): Promise<ListBidsResult>;
23
24
  listCollectionBids(listOrderParams: ListCollectionBidsParams): Promise<ListCollectionBidsResult>;
25
+ listTraitBids(listOrderParams: ListTraitBidsParams): Promise<ListTraitBidsResult>;
24
26
  listTrades(listTradesParams: ListTradesParams): Promise<ListTradeResult>;
25
27
  cancelOrders(orderIds: string[], accountAddress: string, signature: string): Promise<CancelOrdersResult>;
26
28
  createListing({ orderHash, orderComponents, orderSignature, makerFees, }: CreateListingParams): Promise<ListingResult>;
27
29
  createBid({ orderHash, orderComponents, orderSignature, makerFees, }: CreateBidParams): Promise<BidResult>;
28
- createCollectionBid({ orderHash, orderComponents, orderSignature, makerFees, }: CreateBidParams): Promise<CollectionBidResult>;
30
+ createCollectionBid({ orderHash, orderComponents, orderSignature, makerFees, }: CreateCollectionBidParams): Promise<CollectionBidResult>;
31
+ createTraitBid({ orderHash, orderComponents, orderSignature, makerFees, traitCriteria, }: CreateTraitBidParams): Promise<TraitBidResult>;
29
32
  }
@@ -1,10 +1,11 @@
1
- import { Bid, CollectionBid, Listing, Order, Page, Trade } from '../types';
1
+ import { Bid, CollectionBid, Listing, Order, Page, Trade, TraitBid } from '../types';
2
2
  import { Order as OpenApiOrder } from './sdk/models/Order';
3
3
  import { Page as OpenApiPage } from './sdk/models/Page';
4
4
  import { Trade as OpenApiTrade } from './sdk/models/Trade';
5
5
  export declare function mapListingFromOpenApiOrder(order: OpenApiOrder): Listing;
6
6
  export declare function mapBidFromOpenApiOrder(order: OpenApiOrder): Bid;
7
7
  export declare function mapCollectionBidFromOpenApiOrder(order: OpenApiOrder): CollectionBid;
8
+ export declare function mapTraitBidFromOpenApiOrder(order: OpenApiOrder): TraitBid;
8
9
  export declare function mapOrderFromOpenApiOrder(order: OpenApiOrder): Order;
9
10
  export declare function mapFromOpenApiTrade(trade: OpenApiTrade): Trade;
10
11
  export declare function mapFromOpenApiPage(page: OpenApiPage): Page;
@@ -0,0 +1 @@
1
+ export {};