@imtbl/orderbook 2.17.2-alpha.2 → 2.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.js +4 -4
- package/dist/node/index.cjs +10 -10
- package/dist/node/index.js +4 -4
- package/dist/types/api-client/api-client.d.ts +5 -2
- package/dist/types/openapi/mapper.d.ts +2 -1
- package/dist/types/openapi/sdk/index.d.ts +3 -0
- package/dist/types/openapi/sdk/models/CreateMetadataBidRequestBody.d.ts +41 -0
- package/dist/types/openapi/sdk/models/ListMetadataBidsResult.d.ts +6 -0
- package/dist/types/openapi/sdk/models/MetadataBidResult.d.ts +4 -0
- package/dist/types/openapi/sdk/models/Order.d.ts +6 -1
- package/dist/types/openapi/sdk/services/OrdersService.d.ts +75 -0
- package/dist/types/orderbook.d.ts +29 -1
- package/dist/types/test/helpers/order.d.ts +2 -1
- package/dist/types/test/metadata-bid.e2e.d.ts +1 -0
- package/dist/types/types.d.ts +23 -1
- package/package.json +3 -3
package/dist/node/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var metrics = require('@imtbl/metrics');
|
|
4
|
-
var
|
|
5
|
-
var
|
|
4
|
+
var ue = require('axios');
|
|
5
|
+
var me = 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 ce__default = /*#__PURE__*/_interopDefault(ce);
|
|
14
13
|
var ue__default = /*#__PURE__*/_interopDefault(ue);
|
|
14
|
+
var me__default = /*#__PURE__*/_interopDefault(me);
|
|
15
15
|
|
|
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};
|
|
16
|
+
var P=class{constructor(t){this.config=t;}};var _=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 M=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 i=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(d));},o=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(d));},a=d=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(d);};return Object.defineProperty(a,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(a,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(a,"isCancelled",{get:()=>this._isCancelled}),t(i,o,a)});}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 M("Request aborted"));}}get isCancelled(){return this._isCancelled}};var ae=e=>e!=null,V=e=>typeof e=="string",se=e=>V(e)&&e!=="",fe=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]),Me=e=>e instanceof me__default.default,He=e=>e>=200&&e<300,Ve=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},ze=e=>{let t=[],r=(i,o)=>{t.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(o))}`);},s=(i,o)=>{ae(o)&&(Array.isArray(o)?o.forEach(a=>{s(i,a);}):typeof o=="object"?Object.entries(o).forEach(([a,d])=>{s(`${i}[${a}]`,d);}):r(i,o));};return Object.entries(e).forEach(([i,o])=>{s(i,o);}),t.length>0?`?${t.join("&")}`:""},Ue=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(o,a)=>t.path?.hasOwnProperty(a)?r(String(t.path[a])):o),i=`${e.BASE}${s}`;return t.query?`${i}${ze(t.query)}`:i},$e=e=>{if(e.formData){let t=new me__default.default,r=(s,i)=>{V(i)||fe(i)?t.append(s,i):t.append(s,JSON.stringify(i));};return Object.entries(e.formData).filter(([s,i])=>ae(i)).forEach(([s,i])=>{Array.isArray(i)?i.forEach(o=>r(s,o)):r(s,i);}),t}},H=async(e,t)=>typeof t=="function"?t(e):t,Ge=async(e,t,r)=>{let s=await H(t,e.TOKEN),i=await H(t,e.USERNAME),o=await H(t,e.PASSWORD),a=await H(t,e.HEADERS),d=typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...a,...t.headers,...d}).filter(([n,c])=>ae(c)).reduce((n,[c,m])=>({...n,[c]:String(m)}),{});if(se(s)&&(p.Authorization=`Bearer ${s}`),se(i)&&se(o)){let n=Ve(`${i}:${o}`);p.Authorization=`Basic ${n}`;}return t.body&&(t.mediaType?p["Content-Type"]=t.mediaType:fe(t.body)?p["Content-Type"]=t.body.type||"application/octet-stream":V(t.body)?p["Content-Type"]="text/plain":Me(t.body)||(p["Content-Type"]="application/json")),p},je=e=>{if(e.body)return e.body},We=async(e,t,r,s,i,o,a)=>{let d=ue__default.default.CancelToken.source(),p={url:r,headers:o,data:s??i,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:d.token};a(()=>d.cancel("The user aborted a request."));try{return await ue__default.default.request(p)}catch(n){let c=n;if(c.response)return c.response;throw n}},Ke=(e,t)=>{if(t){let r=e.headers[t];if(V(r))return r}},Ye=e=>{if(e.status!==204)return e.data},Je=(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 _(e,t,s);if(!t.ok)throw new _(e,t,"Generic Error")},Ce=(e,t)=>new L(async(r,s,i)=>{try{let o=Ue(e,t),a=$e(t),d=je(t),p=await Ge(e,t,a);if(!i.isCancelled){let n=await We(e,t,o,d,a,p,i),c=Ye(n),m=Ke(n,t.responseHeader),l={url:o,ok:He(n.status),status:n.status,statusText:n.statusText,body:m??c};Je(t,l),r(l.body);}}catch(o){s(o);}});var z=class extends P{constructor(t){super(t);}request(t){return Ce(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:i,buyItemContractAddress:o,accountAddress:a,sellItemMetadataId:d,sellItemTokenId:p,fromUpdatedAt:n,pageSize:c,sortBy:m,sortDirection:l,pageCursor:u}){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:i,buy_item_contract_address:o,account_address:a,sell_item_metadata_id:d,sell_item_token_id:p,from_updated_at:n,page_size:c,sort_by:m,sort_direction:l,page_cursor:u},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:i,accountAddress:o,buyItemMetadataId:a,buyItemTokenId:d,fromUpdatedAt:p,pageSize:n,sortBy:c,sortDirection:m,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:i,account_address:o,buy_item_metadata_id:a,buy_item_token_id:d,from_updated_at:p,page_size:n,sort_by:c,sort_direction:m,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:i,accountAddress:o,fromUpdatedAt:a,pageSize:d,sortBy:p,sortDirection:n,pageCursor:c}){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:i,account_address:o,from_updated_at:a,page_size:d,sort_by:p,sort_direction:n,page_cursor:c},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:i,accountAddress:o,fromUpdatedAt:a,pageSize:d,sortBy:p,sortDirection:n,pageCursor:c}){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:i,account_address:o,from_updated_at:a,page_size:d,sort_by:p,sort_direction:n,page_cursor:c},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)"}})}listMetadataBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:i,accountAddress:o,metadataId:a,fromUpdatedAt:d,pageSize:p,sortBy:n,sortDirection:c,pageCursor:m}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/metadata-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:i,account_address:o,metadata_id:a,from_updated_at:d,page_size:p,sort_by:n,sort_direction:c,page_cursor:m},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createMetadataBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/metadata-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)"}})}getMetadataBid({chainName:t,metadataBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/metadata-bids/{metadata_bid_id}",path:{chain_name:t,metadata_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}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:i,pageSize:o,sortBy:a,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:i,page_size:o,sort_by:a,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 x=class{orders;request;constructor(t,r=z){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 Re;(t=>{(o=>(o.ON_CHAIN="ON_CHAIN",o.OFF_CHAIN="OFF_CHAIN",o.UNDERFUNDED="UNDERFUNDED"))(t.cancellation_type||={});})(Re||={});var ye;(t=>{(s=>s.FILLED="FILLED")(t.reason_code||={});})(ye||={});var C;(t=>{(a=>(a.ROYALTY="ROYALTY",a.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",a.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",a.PROTOCOL="PROTOCOL"))(t.type||={});})(C||={});var f;(t=>{(d=>(d.LISTING="LISTING",d.BID="BID",d.COLLECTION_BID="COLLECTION_BID",d.TRAIT_BID="TRAIT_BID",d.METADATA_BID="METADATA_BID"))(t.type||={});})(f||={});var U=(a=>(a.PENDING="PENDING",a.ACTIVE="ACTIVE",a.INACTIVE="INACTIVE",a.FILLED="FILLED",a.EXPIRED="EXPIRED",a.CANCELLED="CANCELLED",a))(U||{});var E;(t=>{(i=>(i.FULL_RESTRICTED="FULL_RESTRICTED",i.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(t.order_type||={});})(E||={});function R(e){throw new Error("Unreachable")}function I(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 N(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 Ze(e){return e?.length?e.map(t=>({traitType:t.trait_type,values:[...t.values]})):[]}function w(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 k(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:Ze(e.trait_criteria)}}function v(e){if(e.type!==f.type.METADATA_BID)throw new Error("Order type must be METADATA_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Metadata 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("Metadata 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,metadataId:e.metadata_id??""}}function D(e){switch(e.type){case f.type.LISTING:return I(e);case f.type.BID:return N(e);case f.type.COLLECTION_BID:return w(e);case f.type.TRAIT_BID:return k(e);case f.type.METADATA_BID:return v(e);default:return R(e.type)}}function ie(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 O(e){return {nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}var Xe=(i=>(i[i.MAKER_ECOSYSTEM=C.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",i[i.TAKER_ECOSYSTEM=C.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",i[i.PROTOCOL=C.type.PROTOCOL]="PROTOCOL",i[i.ROYALTY=C.type.ROYALTY]="ROYALTY",i))(Xe||{}),oe=(r=>(r.TRANSACTION="TRANSACTION",r.SIGNABLE="SIGNABLE",r))(oe||{}),he=(s=>(s.APPROVAL="APPROVAL",s.FULFILL_ORDER="FULFILL_ORDER",s.CANCEL="CANCEL",s))(he||{}),ne=(s=>(s.CREATE_LISTING="CREATE_ORDER",s.CREATE_ORDER="CREATE_ORDER",s.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",s))(ne||{});var de="ImmutableSeaport",y="1.5",$={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 Qe={integer:0,address:ethers.zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},le=e=>e===void 0?!1:e!=null&&(["string","number"].includes(typeof e)&&BigInt(e)===0n||Array.isArray(e)&&e.every(le)||typeof e=="object"&&Object.values(e).every(le)||typeof e=="boolean"&&e===!1);function et(e){let[,t]=e.match(/^bytes(\d+)$/)??[];return t?ethers.zeroPadValue("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),Qe[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,!le(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=et(t);if(r!==void 0)return r;let s=t.match(/^(.*)(\x5b(\d*)\x5d)$/);if(s){let o=s[1],a=parseInt(s[3]);if(a>0){let d=this.getDefaultValue(o);return Array(a).fill(d)}return []}let i=this.types[t];if(i)return i.reduce((o,{name:a,type:d})=>({...o,[a]:this.getDefaultValue(d)}),{});throw new Error(`unknown type: ${t}`)}};var at=(e,t)=>Array(e).fill(0).map((r,s)=>t(s)),pe=(e,t)=>at(Math.ceil(e.length/t),r=>e.slice(r*t,(r+1)*t)),ge=e=>ethers.toBeHex(e.toString("hex")),b=e=>Buffer.from(e.slice(2),"hex"),G=e=>b(ethers.keccak256(e)),it=e=>G(ethers.concat(e)),F=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),Te=(e,t=!0)=>{if(e.length===0)throw new Error("empty tree");let s=[e.map(i=>{let o=Buffer.isBuffer(i)?i:b(i);return t?G(o):o})];for(;s[s.length-1].length>1;)s.push(ot(s[s.length-1]));return s[s.length-1][0]},ot=e=>pe(e,2).map(it);var ct=(e,t)=>new merkletreejs.MerkleTree(e.map(b),G,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:b(t)}),ut=(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])]),j=class{constructor(t,r,s,i,o){this.types=t;this.rootType=r;this.leafType=s;this.elements=i;this.depth=o;let a=ethers.TypedDataEncoder.from(t);this.encoder=a,this.leafHasher=d=>a.hashStruct(s,d),this.defaultNode=A.from(t,s),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=ct(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:t}=this;return F([...t],this.completedSize,this.defaultNode)}getCompleteLeaves(){let t=this.elements.map(this.leafHasher);return F([...t],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(t){let s=this.getCompleteLeaves()[t],i=this.tree.getHexProof(s,t),o=this.tree.getHexRoot();return {leaf:s,proof:i,root:o}}getEncodedProofAndSignature(t,r){let{proof:s}=this.getProof(t);return ut(t,s,r)}getDataToSign(){let t=this.getCompleteElements();for(;t.length>2;)t=pe(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=ge(Te(r,!1)),i=ethers.keccak256(ethers.toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(ethers.keccak256(ethers.concat([i,s]))!==t)throw new Error("expected derived bulk order hash to match");return t}};function mt(e){return {...$,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}function ft(e){return Math.max(Math.ceil(Math.log2(e)),1)}function _e(e,t=0,r=ft(e.length+t)){let s=mt(r),i=A.from(s,"OrderComponents"),o=[...e];return t>0&&(o=[...F([],t,i),...e]),new j(s,"BulkOrder","OrderComponents",o,r)}function Be(e){if([0,1,2,3].includes(Number(e)))return Number(e);throw new Error(`Unknown order type ${e}`)}function W(e){if([0,1,2,3,4,5].includes(Number(e)))return Number(e);throw new Error(`Unknown item type ${e}`)}function Pe(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:W(s.itemType)})),consideration:r.consideration.map(s=>({...s,itemType:W(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(i=>({...i,itemType:W(i.itemType)})),consideration:s.consideration.map(i=>({...i,itemType:W(i.itemType)}))})),types:t.types,value:t.message}}function Se(e,t){let r=_e(t);return t.map((s,i)=>r.getEncodedProofAndSignature(i,e))}function Rt(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 yt(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 Y(e){let t=e.sell.map(Rt),r=e.buy.map(a=>yt(a,e.account_address)),s=function(a){switch(a){case f.type.LISTING:return r[0];case f.type.BID:case f.type.COLLECTION_BID:case f.type.TRAIT_BID:case f.type.METADATA_BID:return t[0];default:return R()}}(e.type),i=function(a){switch(a){case E.order_type.FULL_RESTRICTED:return 2;case E.order_type.PARTIAL_RESTRICTED:return 3;default:return R()}}(e.protocol_data.order_type),o=e.fees.map(a=>({amount:a.amount,itemType:s.itemType,recipient:a.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:i.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:o}}function g(e,t,r){return async()=>{let s=await e.buildTransaction(),i={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 i.gasLimit=BigInt(await e.estimateGas()),i.gasLimit+=i.gasLimit/BigInt(5),i}}function Ne(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 we(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 J=class e{constructor(t,r,s,i,o){this.seaportLibFactory=t;this.provider=r;this.seaportContractAddress=s;this.zoneContractAddress=i;this.rateLimitingKey=o;}async prepareBulkSeaportOrders(t,r){let{actions:s}=await this.createSeaportOrders(t,r),i=s.filter(l=>l.type==="approval"),o=await this.provider.getNetwork(),a=i.map(l=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(l.transactionMethods,o.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:c,value:m}=Le(p);return a.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(c,m)}),{actions:a,preparedOrders:n.map(l=>({orderComponents:l,orderHash:this.getSeaportLib().getOrderHash(l)}))}}async prepareSeaportOrder(t,r,s,i,o,a){let{actions:d}=await this.createSeaportOrder(t,r,s,i,o,a),p=[],n=d.find(u=>u.type==="approval");n&&p.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(n.transactionMethods,(await this.provider.getNetwork()).chainId,t)});let c=d.find(u=>u.type==="create");if(!c)throw new Error("No create order action found");let m=await c.getMessageToSign(),l=Pe(m);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,i,o){let{orderComponents:a,tips:d}=Y(t),p=this.getSeaportLib(t),n=(await this.provider.getNetwork()).chainId,c={order:{parameters:a,signature:t.signature},unitsToFill:i,extraData:s,tips:d};o&&(c.considerationCriteria=o);let{actions:m}=await p.fulfillOrders({accountAddress:r,fulfillOrderDetails:[c]}),l=[],u=m.filter(T=>T.type==="approval");u.length>0&&u.forEach(T=>{l.push({type:"TRANSACTION",buildTransaction:g(T.transactionMethods,n,r),purpose:"APPROVAL"});});let h=m.find(T=>T.type==="exchange");if(!h)throw new Error("No exchange action found");return l.push({type:"TRANSACTION",buildTransaction:g(h.transactionMethods,n,r),purpose:"FULFILL_ORDER"}),{actions:l,expiration:e.getExpirationISOTimeFromExtraData(s),order:D(t)}}async fulfillBulkOrders(t,r){let s=t.map(n=>{let{orderComponents:c,tips:m}=Y(n.order),l={order:{parameters:c,signature:n.order.signature},unitsToFill:n.unitsToFill,extraData:n.extraData,tips:m};return n.considerationCriteria&&n.considerationCriteria.length>0&&(l.considerationCriteria=n.considerationCriteria),l}),{actions:i}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:s,accountAddress:r}),o=[],a=i.filter(n=>n.type==="approval"),d=(await this.provider.getNetwork()).chainId;a.length>0&&a.forEach(n=>{o.push({type:"TRANSACTION",buildTransaction:g(n.transactionMethods,d,r),purpose:"APPROVAL"});});let p=i.find(n=>n.type==="exchange");if(!p)throw new Error("No exchange action found");return o.push({type:"TRANSACTION",buildTransaction:g(p.transactionMethods,(await this.provider.getNetwork()).chainId,r),purpose:"FULFILL_ORDER"}),{actions:o,expiration:s.map(n=>e.getExpirationISOTimeFromExtraData(n.extraData)).reduce((n,c)=>new Date(n)<new Date(c)?n:c)}}async cancelOrders(t,r){let s=t.map(a=>Y(a).orderComponents),o=await this.getSeaportLib(t[0]).cancelOrders(s,r);return {type:"TRANSACTION",buildTransaction:g(o,(await this.provider.getNetwork()).chainId,r),purpose:"CANCEL"}}createSeaportOrders(t,r){return this.getSeaportLib().createBulkOrders(r.map(i=>{let{offerItem:o,considerationItem:a,allowPartialFills:d,orderStart:p,orderExpiry:n}=i;return {allowPartialFills:d,offer:[Ne(o)],consideration:[we(a,t)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(n.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),t)}createSeaportOrder(t,r,s,i,o,a){return this.getSeaportLib().createOrder({allowPartialFills:i,offer:[Ne(r)],consideration:[we(s,t)],startTime:(o.getTime()/1e3).toFixed(0),endTime:(a.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:de,version:y,chainId:s,verifyingContract:this.seaportContractAddress},types:t,value:r}}async getTypedDataFromOrderComponents(t){let{chainId:r}=await this.provider.getNetwork();return {domain:{name:de,version:y,chainId:r,verifyingContract:this.seaportContractAddress},types:$,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 Z(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 q(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 X(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 B(e){switch(e){case 2:return E.order_type.FULL_RESTRICTED;case 3:return E.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${e}`);default:return R()}}var Q=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 getMetadataBid(t){return this.orderbookService.getMetadataBid({chainName:this.chainName,metadataBidId:t})}async listMetadataBids(t){return this.orderbookService.listMetadataBids({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:i}){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(Z),fees:i.map(o=>({type:C.type.MAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:B(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:y,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(Z),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:i}){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(Z),fees:i.map(o=>({type:C.type.MAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:B(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:y,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(q),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:i}){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(X),fees:i.map(o=>({type:C.type.MAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:B(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:y,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(q),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createMetadataBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:i,metadataId:o}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a metadata bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a metadata bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a metadata bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");if(!o)throw new Error("A metadata_id is required for a metadata bid");return this.orderbookService.createMetadataBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(X),fees:i.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:B(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:y,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(q),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString(),metadata_id:o}})}async createTraitBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:i,traitCriteria:o}){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(!o?.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(X),fees:i.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:B(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:y,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(q),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString(),trait_criteria:o.map(a=>({trait_type:a.traitType,values:a.values}))}})}};var ee=class{constructor(t,r,s,i){this.chainName=r;this.seaportAddress=s;this.orderbookClient=new x({BASE:t,HEADERS:i?{"x-api-key":i}:void 0});}orderbookClient;create(){return new Q(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var gt="imtbl-zkevm-testnet",Tt="imtbl-zkevm-mainnet";function te(e,t){let r=new ethers.FetchRequest(e);return t&&r.setHeader("x-api-key",t),new ethers.JsonRpcProvider(r)}function ve(e){switch(e.baseConfig.environment){case config.Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:gt,provider:te("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case config.Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:Tt,provider:te("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}var re=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(o){o==null&&(o=0);let a=this.send("eth_accounts",[]);if(typeof o=="number"){let d=await a;if(o>=d.length)throw new Error("no such account");return new ethers.JsonRpcSigner(this,d[o])}return new ethers.JsonRpcSigner(this,o)},new seaportJs.Seaport(s,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}};var ce=class e{apiClient;seaport;orderbookConfig;constructor(t){let s={...ve(t),...t.overrides};if(t.overrides?.jsonRpcProviderUrl&&(s.provider=te(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:i,chainName:o}=this.orderbookConfig;if(!i)throw new Error("API endpoint must be provided");this.apiClient=new ee(i,o,this.orderbookConfig.seaportContractAddress,t.baseConfig.rateLimitingKey).create();let a=new re(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new J(a,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:I(r.result)}}async getBid(t){let r=await this.apiClient.getBid(t);return {result:N(r.result)}}async getCollectionBid(t){let r=await this.apiClient.getCollectionBid(t);return {result:w(r.result)}}async getTraitBid(t){let r=await this.apiClient.getTraitBid(t);return {result:k(r.result)}}async getMetadataBid(t){let r=await this.apiClient.getMetadataBid(t);return {result:v(r.result)}}async getTrade(t){let r=await this.apiClient.getTrade(t);return {result:ie(r.result)}}async listListings(t){let r=await this.apiClient.listListings(t);return {page:O(r.page),result:r.result.map(I)}}async listBids(t){let r=await this.apiClient.listBids(t);return {page:O(r.page),result:r.result.map(N)}}async listCollectionBids(t){let r=await this.apiClient.listCollectionBids(t);return {page:O(r.page),result:r.result.map(w)}}async listTraitBids(t){let r=await this.apiClient.listTraitBids(t);return {page:O(r.page),result:r.result.map(k)}}async listMetadataBids(t){let r=await this.apiClient.listMetadataBids(t);return {page:O(r.page),result:r.result.map(v)}}async listTrades(t){let r=await this.apiClient.listTrades(t);return {page:O(r.page),result:r.result.map(ie)}}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 a=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:a.actions,completeListings:async d=>{let p=await this.createListing({makerFees:r[0].makerFees,orderComponents:a.orderComponents,orderHash:a.orderHash,orderSignature:typeof d=="string"?d:d[0]});return {result:[{success:!0,orderHash:a.orderHash,order:p.result}]}}}}if(await this.orderbookConfig.provider.getCode(t)!=="0x"){metrics.track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:t,listingsCount:r.length});let a=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:a.flatMap(n=>{let c=[];return n.actions.forEach(m=>{if(m.type==="TRANSACTION"){let l=n.orderComponents.offer[0].token;d.includes(l)||(d.push(l),c.push(m));}else c.push(m);}),c}),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(a.map((l,u)=>{let h=n[u];return this.apiClient.createListing({makerFees:r[u].makerFees,orderComponents:l.orderComponents,orderHash:l.orderHash,orderSignature:h}).catch(()=>{})}))).map((l,u)=>({success:!!l,orderHash:a[u].orderHash,order:l?I(l.result):void 0}))}}}}metrics.track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:t,listingsCount:r.length});let{actions:i,preparedOrders:o}=await this.seaport.prepareBulkSeaportOrders(t,r.map(a=>({offerItem:a.sell,considerationItem:a.buy,allowPartialFills:a.sell.type==="ERC1155",orderStart:a.orderStart||new Date,orderExpiry:a.orderExpiry||e.defaultOrderExpiry()})));return {actions:i,completeListings:async a=>{let d=typeof a=="object";if(d&&a.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let p=o.map(l=>l.orderComponents),n=d?a[0]:a,c=Se(n,p);return {result:(await Promise.all(p.map((l,u)=>{let h=c[u],T=o[u],qe=r[u];return this.apiClient.createListing({orderComponents:l,orderHash:T.orderHash,orderSignature:h,makerFees:qe.makerFees}).catch(()=>{})}))).map((l,u)=>({success:!!l,orderHash:o[u].orderHash,order:l?I(l.result):void 0}))}}}}async prepareListing({makerAddress:t,sell:r,buy:s,orderStart:i,orderExpiry:o}){return this.seaport.prepareSeaportOrder(t,r,s,r.type==="ERC1155",i||new Date,o||e.defaultOrderExpiry())}async createListing(t){let r=await this.apiClient.createListing(t);return {result:I(r.result)}}async prepareBid({makerAddress:t,sell:r,buy:s,orderStart:i,orderExpiry:o}){return this.seaport.prepareSeaportOrder(t,r,s,s.type==="ERC1155",i||new Date,o||e.defaultOrderExpiry())}async createBid(t){let r=await this.apiClient.createBid(t);return {result:N(r.result)}}async prepareCollectionBid({makerAddress:t,sell:r,buy:s,orderStart:i,orderExpiry:o}){return this.seaport.prepareSeaportOrder(t,r,s,!0,i||new Date,o||e.defaultOrderExpiry())}async createCollectionBid(t){let r=await this.apiClient.createCollectionBid(t);return {result:w(r.result)}}async prepareTraitBid({makerAddress:t,sell:r,buy:s,orderStart:i,orderExpiry:o}){return this.seaport.prepareSeaportOrder(t,r,s,!0,i||new Date,o||e.defaultOrderExpiry())}async createTraitBid(t){let r=await this.apiClient.createTraitBid(t);return {result:k(r.result)}}async prepareMetadataBid({makerAddress:t,sell:r,buy:s,orderStart:i,orderExpiry:o}){return this.seaport.prepareSeaportOrder(t,r,s,!0,i||new Date,o||e.defaultOrderExpiry())}async createMetadataBid(t){let r=await this.apiClient.createMetadataBid(t);return {result:v(r.result)}}async fulfillOrder(t,r,s,i,o){let a={order_id:t,taker_address:r,fees:s.map(m=>({type:C.type.TAKER_ECOSYSTEM,amount:m.amount,recipient_address:m.recipientAddress}))},d=o?[{identifier:o,proof:[]}]:void 0;o&&(a.token_id=o);let p=await this.apiClient.fulfillmentData([a]);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,c=p.result.fulfillable_orders[0].order;if(c.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${c.status}`);return this.seaport.fulfillOrder(c,r,n,i,d)}async fulfillBulkOrders(t,r){let s=t.map(o=>{let a="listingId"in o;return {orderId:a?o.listingId:o.orderId,takerFees:o.takerFees,amountToFill:o.amountToFill,tokenId:a?void 0:o.tokenId}}),i=await this.apiClient.fulfillmentData(s.map(o=>({order_id:o.orderId,taker_address:r,fees:o.takerFees.map(a=>({type:C.type.TAKER_ECOSYSTEM,amount:a.amount,recipient_address:a.recipientAddress})),token_id:o?.tokenId})));try{let o=i.result.fulfillable_orders.map(a=>{let d=s.find(n=>n.orderId===a.order.id&&n.tokenId===a.token_id);if(!d){let n=`Could not find order for order ${a.order.id}`;throw a.token_id&&(n+=` and token ID ${a.token_id}`),new Error(n)}let p=[];return d.tokenId&&p.push({identifier:d.tokenId,proof:[]}),{extraData:a.extra_data,order:a.order,unitsToFill:d.amountToFill,considerationCriteria:p}});return {...await this.seaport.fulfillBulkOrders(o,r),fulfillableOrders:i.result.fulfillable_orders.map(a=>D(a.order)),unfulfillableOrders:i.result.unfulfillable_orders.map(a=>({orderId:a.order_id,tokenId:a.token_id,reason:a.reason})),sufficientBalance:!0}}catch(o){if(String(o).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:i.result.fulfillable_orders.map(a=>D(a.order)),unfulfillableOrders:i.result.unfulfillable_orders.map(a=>({orderId:a.order_id,reason:a.reason})),sufficientBalance:!1};throw o}}async prepareOrderCancellations(t){let r=await this.orderbookConfig.provider.getNetwork(),s={name:"imtbl-order-book",chainId:Number(r.chainId),verifyingContract:this.orderbookConfig.seaportContractAddress},i={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},o={orders:t.map(a=>({id:a}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:s,types:i,value:o}}}}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}))),i=Promise.all(t.map(l=>this.apiClient.getBid(l).catch(u=>{if(u.status!==404)throw u}))),o=Promise.all(t.map(l=>this.apiClient.getCollectionBid(l).catch(u=>{if(u.status!==404)throw u}))),a=Promise.all(t.map(l=>this.apiClient.getTraitBid(l).catch(u=>{if(u.status!==404)throw u}))),d=Promise.all(t.map(l=>this.apiClient.getMetadataBid(l).catch(u=>{if(u.status!==404)throw u}))),p=[await Promise.all([s,i,o,a,d])].flat(2).filter(l=>l!==void 0).map(l=>l.result);if(p.length!==t.length){let l=t.filter(u=>!p.some(h=>h.id===u));throw new Error(`Orders ${l} not found`)}for(let l of p)if(l.account_address!==r.toLowerCase())throw new Error(`Only account ${l.account_address} can cancel order ${l.id}`);let n=p.map(l=>l.protocol_data.seaport_address);if(new Set(n).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(p,r)}}};var Ot={estimatedFulfillmentGasGwei:4e5};
|
|
17
17
|
|
|
18
|
-
exports.ActionType =
|
|
19
|
-
exports.FeeType =
|
|
20
|
-
exports.OrderStatusName =
|
|
21
|
-
exports.Orderbook =
|
|
22
|
-
exports.SignablePurpose =
|
|
23
|
-
exports.TransactionPurpose =
|
|
18
|
+
exports.ActionType = oe;
|
|
19
|
+
exports.FeeType = Xe;
|
|
20
|
+
exports.OrderStatusName = U;
|
|
21
|
+
exports.Orderbook = ce;
|
|
22
|
+
exports.SignablePurpose = ne;
|
|
23
|
+
exports.TransactionPurpose = he;
|
|
24
24
|
exports.constants = Ot;
|
package/dist/node/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { track } from '@imtbl/metrics';
|
|
2
|
-
import
|
|
3
|
-
import
|
|
2
|
+
import ue from 'axios';
|
|
3
|
+
import me 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 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};
|
|
9
|
+
var P=class{constructor(t){this.config=t;}};var _=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 M=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 i=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(d));},o=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(d));},a=d=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(d);};return Object.defineProperty(a,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(a,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(a,"isCancelled",{get:()=>this._isCancelled}),t(i,o,a)});}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 M("Request aborted"));}}get isCancelled(){return this._isCancelled}};var ae=e=>e!=null,V=e=>typeof e=="string",se=e=>V(e)&&e!=="",fe=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]),Me=e=>e instanceof me,He=e=>e>=200&&e<300,Ve=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},ze=e=>{let t=[],r=(i,o)=>{t.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(o))}`);},s=(i,o)=>{ae(o)&&(Array.isArray(o)?o.forEach(a=>{s(i,a);}):typeof o=="object"?Object.entries(o).forEach(([a,d])=>{s(`${i}[${a}]`,d);}):r(i,o));};return Object.entries(e).forEach(([i,o])=>{s(i,o);}),t.length>0?`?${t.join("&")}`:""},Ue=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(o,a)=>t.path?.hasOwnProperty(a)?r(String(t.path[a])):o),i=`${e.BASE}${s}`;return t.query?`${i}${ze(t.query)}`:i},$e=e=>{if(e.formData){let t=new me,r=(s,i)=>{V(i)||fe(i)?t.append(s,i):t.append(s,JSON.stringify(i));};return Object.entries(e.formData).filter(([s,i])=>ae(i)).forEach(([s,i])=>{Array.isArray(i)?i.forEach(o=>r(s,o)):r(s,i);}),t}},H=async(e,t)=>typeof t=="function"?t(e):t,Ge=async(e,t,r)=>{let s=await H(t,e.TOKEN),i=await H(t,e.USERNAME),o=await H(t,e.PASSWORD),a=await H(t,e.HEADERS),d=typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...a,...t.headers,...d}).filter(([n,c])=>ae(c)).reduce((n,[c,m])=>({...n,[c]:String(m)}),{});if(se(s)&&(p.Authorization=`Bearer ${s}`),se(i)&&se(o)){let n=Ve(`${i}:${o}`);p.Authorization=`Basic ${n}`;}return t.body&&(t.mediaType?p["Content-Type"]=t.mediaType:fe(t.body)?p["Content-Type"]=t.body.type||"application/octet-stream":V(t.body)?p["Content-Type"]="text/plain":Me(t.body)||(p["Content-Type"]="application/json")),p},je=e=>{if(e.body)return e.body},We=async(e,t,r,s,i,o,a)=>{let d=ue.CancelToken.source(),p={url:r,headers:o,data:s??i,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:d.token};a(()=>d.cancel("The user aborted a request."));try{return await ue.request(p)}catch(n){let c=n;if(c.response)return c.response;throw n}},Ke=(e,t)=>{if(t){let r=e.headers[t];if(V(r))return r}},Ye=e=>{if(e.status!==204)return e.data},Je=(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 _(e,t,s);if(!t.ok)throw new _(e,t,"Generic Error")},Ce=(e,t)=>new L(async(r,s,i)=>{try{let o=Ue(e,t),a=$e(t),d=je(t),p=await Ge(e,t,a);if(!i.isCancelled){let n=await We(e,t,o,d,a,p,i),c=Ye(n),m=Ke(n,t.responseHeader),l={url:o,ok:He(n.status),status:n.status,statusText:n.statusText,body:m??c};Je(t,l),r(l.body);}}catch(o){s(o);}});var z=class extends P{constructor(t){super(t);}request(t){return Ce(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:i,buyItemContractAddress:o,accountAddress:a,sellItemMetadataId:d,sellItemTokenId:p,fromUpdatedAt:n,pageSize:c,sortBy:m,sortDirection:l,pageCursor:u}){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:i,buy_item_contract_address:o,account_address:a,sell_item_metadata_id:d,sell_item_token_id:p,from_updated_at:n,page_size:c,sort_by:m,sort_direction:l,page_cursor:u},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:i,accountAddress:o,buyItemMetadataId:a,buyItemTokenId:d,fromUpdatedAt:p,pageSize:n,sortBy:c,sortDirection:m,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:i,account_address:o,buy_item_metadata_id:a,buy_item_token_id:d,from_updated_at:p,page_size:n,sort_by:c,sort_direction:m,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:i,accountAddress:o,fromUpdatedAt:a,pageSize:d,sortBy:p,sortDirection:n,pageCursor:c}){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:i,account_address:o,from_updated_at:a,page_size:d,sort_by:p,sort_direction:n,page_cursor:c},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:i,accountAddress:o,fromUpdatedAt:a,pageSize:d,sortBy:p,sortDirection:n,pageCursor:c}){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:i,account_address:o,from_updated_at:a,page_size:d,sort_by:p,sort_direction:n,page_cursor:c},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)"}})}listMetadataBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:i,accountAddress:o,metadataId:a,fromUpdatedAt:d,pageSize:p,sortBy:n,sortDirection:c,pageCursor:m}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/metadata-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:i,account_address:o,metadata_id:a,from_updated_at:d,page_size:p,sort_by:n,sort_direction:c,page_cursor:m},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createMetadataBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/metadata-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)"}})}getMetadataBid({chainName:t,metadataBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/metadata-bids/{metadata_bid_id}",path:{chain_name:t,metadata_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}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:i,pageSize:o,sortBy:a,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:i,page_size:o,sort_by:a,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 x=class{orders;request;constructor(t,r=z){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 Re;(t=>{(o=>(o.ON_CHAIN="ON_CHAIN",o.OFF_CHAIN="OFF_CHAIN",o.UNDERFUNDED="UNDERFUNDED"))(t.cancellation_type||={});})(Re||={});var ye;(t=>{(s=>s.FILLED="FILLED")(t.reason_code||={});})(ye||={});var C;(t=>{(a=>(a.ROYALTY="ROYALTY",a.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",a.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",a.PROTOCOL="PROTOCOL"))(t.type||={});})(C||={});var f;(t=>{(d=>(d.LISTING="LISTING",d.BID="BID",d.COLLECTION_BID="COLLECTION_BID",d.TRAIT_BID="TRAIT_BID",d.METADATA_BID="METADATA_BID"))(t.type||={});})(f||={});var U=(a=>(a.PENDING="PENDING",a.ACTIVE="ACTIVE",a.INACTIVE="INACTIVE",a.FILLED="FILLED",a.EXPIRED="EXPIRED",a.CANCELLED="CANCELLED",a))(U||{});var E;(t=>{(i=>(i.FULL_RESTRICTED="FULL_RESTRICTED",i.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(t.order_type||={});})(E||={});function R(e){throw new Error("Unreachable")}function I(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 N(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 Ze(e){return e?.length?e.map(t=>({traitType:t.trait_type,values:[...t.values]})):[]}function w(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 k(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:Ze(e.trait_criteria)}}function v(e){if(e.type!==f.type.METADATA_BID)throw new Error("Order type must be METADATA_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Metadata 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("Metadata 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,metadataId:e.metadata_id??""}}function D(e){switch(e.type){case f.type.LISTING:return I(e);case f.type.BID:return N(e);case f.type.COLLECTION_BID:return w(e);case f.type.TRAIT_BID:return k(e);case f.type.METADATA_BID:return v(e);default:return R(e.type)}}function ie(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 O(e){return {nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}var Xe=(i=>(i[i.MAKER_ECOSYSTEM=C.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",i[i.TAKER_ECOSYSTEM=C.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",i[i.PROTOCOL=C.type.PROTOCOL]="PROTOCOL",i[i.ROYALTY=C.type.ROYALTY]="ROYALTY",i))(Xe||{}),oe=(r=>(r.TRANSACTION="TRANSACTION",r.SIGNABLE="SIGNABLE",r))(oe||{}),he=(s=>(s.APPROVAL="APPROVAL",s.FULFILL_ORDER="FULFILL_ORDER",s.CANCEL="CANCEL",s))(he||{}),ne=(s=>(s.CREATE_LISTING="CREATE_ORDER",s.CREATE_ORDER="CREATE_ORDER",s.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",s))(ne||{});var de="ImmutableSeaport",y="1.5",$={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 Qe={integer:0,address:zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},le=e=>e===void 0?!1:e!=null&&(["string","number"].includes(typeof e)&&BigInt(e)===0n||Array.isArray(e)&&e.every(le)||typeof e=="object"&&Object.values(e).every(le)||typeof e=="boolean"&&e===!1);function et(e){let[,t]=e.match(/^bytes(\d+)$/)??[];return t?zeroPadValue("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),Qe[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,!le(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=et(t);if(r!==void 0)return r;let s=t.match(/^(.*)(\x5b(\d*)\x5d)$/);if(s){let o=s[1],a=parseInt(s[3]);if(a>0){let d=this.getDefaultValue(o);return Array(a).fill(d)}return []}let i=this.types[t];if(i)return i.reduce((o,{name:a,type:d})=>({...o,[a]:this.getDefaultValue(d)}),{});throw new Error(`unknown type: ${t}`)}};var at=(e,t)=>Array(e).fill(0).map((r,s)=>t(s)),pe=(e,t)=>at(Math.ceil(e.length/t),r=>e.slice(r*t,(r+1)*t)),ge=e=>toBeHex(e.toString("hex")),b=e=>Buffer.from(e.slice(2),"hex"),G=e=>b(keccak256(e)),it=e=>G(concat(e)),F=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),Te=(e,t=!0)=>{if(e.length===0)throw new Error("empty tree");let s=[e.map(i=>{let o=Buffer.isBuffer(i)?i:b(i);return t?G(o):o})];for(;s[s.length-1].length>1;)s.push(ot(s[s.length-1]));return s[s.length-1][0]},ot=e=>pe(e,2).map(it);var ct=(e,t)=>new MerkleTree(e.map(b),G,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:b(t)}),ut=(e,t,r=`0x${"ff".repeat(64)}`)=>concat([r,`0x${e.toString(16).padStart(6,"0")}`,AbiCoder.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]),j=class{constructor(t,r,s,i,o){this.types=t;this.rootType=r;this.leafType=s;this.elements=i;this.depth=o;let a=TypedDataEncoder.from(t);this.encoder=a,this.leafHasher=d=>a.hashStruct(s,d),this.defaultNode=A.from(t,s),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=ct(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:t}=this;return F([...t],this.completedSize,this.defaultNode)}getCompleteLeaves(){let t=this.elements.map(this.leafHasher);return F([...t],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(t){let s=this.getCompleteLeaves()[t],i=this.tree.getHexProof(s,t),o=this.tree.getHexRoot();return {leaf:s,proof:i,root:o}}getEncodedProofAndSignature(t,r){let{proof:s}=this.getProof(t);return ut(t,s,r)}getDataToSign(){let t=this.getCompleteElements();for(;t.length>2;)t=pe(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=ge(Te(r,!1)),i=keccak256(toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(keccak256(concat([i,s]))!==t)throw new Error("expected derived bulk order hash to match");return t}};function mt(e){return {...$,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}function ft(e){return Math.max(Math.ceil(Math.log2(e)),1)}function _e(e,t=0,r=ft(e.length+t)){let s=mt(r),i=A.from(s,"OrderComponents"),o=[...e];return t>0&&(o=[...F([],t,i),...e]),new j(s,"BulkOrder","OrderComponents",o,r)}function Be(e){if([0,1,2,3].includes(Number(e)))return Number(e);throw new Error(`Unknown order type ${e}`)}function W(e){if([0,1,2,3,4,5].includes(Number(e)))return Number(e);throw new Error(`Unknown item type ${e}`)}function Pe(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:W(s.itemType)})),consideration:r.consideration.map(s=>({...s,itemType:W(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(i=>({...i,itemType:W(i.itemType)})),consideration:s.consideration.map(i=>({...i,itemType:W(i.itemType)}))})),types:t.types,value:t.message}}function Se(e,t){let r=_e(t);return t.map((s,i)=>r.getEncodedProofAndSignature(i,e))}function Rt(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 yt(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 Y(e){let t=e.sell.map(Rt),r=e.buy.map(a=>yt(a,e.account_address)),s=function(a){switch(a){case f.type.LISTING:return r[0];case f.type.BID:case f.type.COLLECTION_BID:case f.type.TRAIT_BID:case f.type.METADATA_BID:return t[0];default:return R()}}(e.type),i=function(a){switch(a){case E.order_type.FULL_RESTRICTED:return 2;case E.order_type.PARTIAL_RESTRICTED:return 3;default:return R()}}(e.protocol_data.order_type),o=e.fees.map(a=>({amount:a.amount,itemType:s.itemType,recipient:a.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:i.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:o}}function g(e,t,r){return async()=>{let s=await e.buildTransaction(),i={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 i.gasLimit=BigInt(await e.estimateGas()),i.gasLimit+=i.gasLimit/BigInt(5),i}}function Ne(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 we(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 J=class e{constructor(t,r,s,i,o){this.seaportLibFactory=t;this.provider=r;this.seaportContractAddress=s;this.zoneContractAddress=i;this.rateLimitingKey=o;}async prepareBulkSeaportOrders(t,r){let{actions:s}=await this.createSeaportOrders(t,r),i=s.filter(l=>l.type==="approval"),o=await this.provider.getNetwork(),a=i.map(l=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(l.transactionMethods,o.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:c,value:m}=Le(p);return a.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(c,m)}),{actions:a,preparedOrders:n.map(l=>({orderComponents:l,orderHash:this.getSeaportLib().getOrderHash(l)}))}}async prepareSeaportOrder(t,r,s,i,o,a){let{actions:d}=await this.createSeaportOrder(t,r,s,i,o,a),p=[],n=d.find(u=>u.type==="approval");n&&p.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(n.transactionMethods,(await this.provider.getNetwork()).chainId,t)});let c=d.find(u=>u.type==="create");if(!c)throw new Error("No create order action found");let m=await c.getMessageToSign(),l=Pe(m);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,i,o){let{orderComponents:a,tips:d}=Y(t),p=this.getSeaportLib(t),n=(await this.provider.getNetwork()).chainId,c={order:{parameters:a,signature:t.signature},unitsToFill:i,extraData:s,tips:d};o&&(c.considerationCriteria=o);let{actions:m}=await p.fulfillOrders({accountAddress:r,fulfillOrderDetails:[c]}),l=[],u=m.filter(T=>T.type==="approval");u.length>0&&u.forEach(T=>{l.push({type:"TRANSACTION",buildTransaction:g(T.transactionMethods,n,r),purpose:"APPROVAL"});});let h=m.find(T=>T.type==="exchange");if(!h)throw new Error("No exchange action found");return l.push({type:"TRANSACTION",buildTransaction:g(h.transactionMethods,n,r),purpose:"FULFILL_ORDER"}),{actions:l,expiration:e.getExpirationISOTimeFromExtraData(s),order:D(t)}}async fulfillBulkOrders(t,r){let s=t.map(n=>{let{orderComponents:c,tips:m}=Y(n.order),l={order:{parameters:c,signature:n.order.signature},unitsToFill:n.unitsToFill,extraData:n.extraData,tips:m};return n.considerationCriteria&&n.considerationCriteria.length>0&&(l.considerationCriteria=n.considerationCriteria),l}),{actions:i}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:s,accountAddress:r}),o=[],a=i.filter(n=>n.type==="approval"),d=(await this.provider.getNetwork()).chainId;a.length>0&&a.forEach(n=>{o.push({type:"TRANSACTION",buildTransaction:g(n.transactionMethods,d,r),purpose:"APPROVAL"});});let p=i.find(n=>n.type==="exchange");if(!p)throw new Error("No exchange action found");return o.push({type:"TRANSACTION",buildTransaction:g(p.transactionMethods,(await this.provider.getNetwork()).chainId,r),purpose:"FULFILL_ORDER"}),{actions:o,expiration:s.map(n=>e.getExpirationISOTimeFromExtraData(n.extraData)).reduce((n,c)=>new Date(n)<new Date(c)?n:c)}}async cancelOrders(t,r){let s=t.map(a=>Y(a).orderComponents),o=await this.getSeaportLib(t[0]).cancelOrders(s,r);return {type:"TRANSACTION",buildTransaction:g(o,(await this.provider.getNetwork()).chainId,r),purpose:"CANCEL"}}createSeaportOrders(t,r){return this.getSeaportLib().createBulkOrders(r.map(i=>{let{offerItem:o,considerationItem:a,allowPartialFills:d,orderStart:p,orderExpiry:n}=i;return {allowPartialFills:d,offer:[Ne(o)],consideration:[we(a,t)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(n.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),t)}createSeaportOrder(t,r,s,i,o,a){return this.getSeaportLib().createOrder({allowPartialFills:i,offer:[Ne(r)],consideration:[we(s,t)],startTime:(o.getTime()/1e3).toFixed(0),endTime:(a.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:de,version:y,chainId:s,verifyingContract:this.seaportContractAddress},types:t,value:r}}async getTypedDataFromOrderComponents(t){let{chainId:r}=await this.provider.getNetwork();return {domain:{name:de,version:y,chainId:r,verifyingContract:this.seaportContractAddress},types:$,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 Z(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 q(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 X(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 B(e){switch(e){case 2:return E.order_type.FULL_RESTRICTED;case 3:return E.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${e}`);default:return R()}}var Q=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 getMetadataBid(t){return this.orderbookService.getMetadataBid({chainName:this.chainName,metadataBidId:t})}async listMetadataBids(t){return this.orderbookService.listMetadataBids({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:i}){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(Z),fees:i.map(o=>({type:C.type.MAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:B(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:y,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(Z),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:i}){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(Z),fees:i.map(o=>({type:C.type.MAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:B(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:y,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(q),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:i}){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(X),fees:i.map(o=>({type:C.type.MAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:B(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:y,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(q),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createMetadataBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:i,metadataId:o}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a metadata bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a metadata bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a metadata bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");if(!o)throw new Error("A metadata_id is required for a metadata bid");return this.orderbookService.createMetadataBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(X),fees:i.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:B(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:y,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(q),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString(),metadata_id:o}})}async createTraitBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:i,traitCriteria:o}){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(!o?.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(X),fees:i.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:B(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:y,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(q),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString(),trait_criteria:o.map(a=>({trait_type:a.traitType,values:a.values}))}})}};var ee=class{constructor(t,r,s,i){this.chainName=r;this.seaportAddress=s;this.orderbookClient=new x({BASE:t,HEADERS:i?{"x-api-key":i}:void 0});}orderbookClient;create(){return new Q(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var gt="imtbl-zkevm-testnet",Tt="imtbl-zkevm-mainnet";function te(e,t){let r=new FetchRequest(e);return t&&r.setHeader("x-api-key",t),new JsonRpcProvider(r)}function ve(e){switch(e.baseConfig.environment){case Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:gt,provider:te("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:Tt,provider:te("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}var re=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(o){o==null&&(o=0);let a=this.send("eth_accounts",[]);if(typeof o=="number"){let d=await a;if(o>=d.length)throw new Error("no such account");return new JsonRpcSigner(this,d[o])}return new JsonRpcSigner(this,o)},new Seaport(s,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}};var ce=class e{apiClient;seaport;orderbookConfig;constructor(t){let s={...ve(t),...t.overrides};if(t.overrides?.jsonRpcProviderUrl&&(s.provider=te(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:i,chainName:o}=this.orderbookConfig;if(!i)throw new Error("API endpoint must be provided");this.apiClient=new ee(i,o,this.orderbookConfig.seaportContractAddress,t.baseConfig.rateLimitingKey).create();let a=new re(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new J(a,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:I(r.result)}}async getBid(t){let r=await this.apiClient.getBid(t);return {result:N(r.result)}}async getCollectionBid(t){let r=await this.apiClient.getCollectionBid(t);return {result:w(r.result)}}async getTraitBid(t){let r=await this.apiClient.getTraitBid(t);return {result:k(r.result)}}async getMetadataBid(t){let r=await this.apiClient.getMetadataBid(t);return {result:v(r.result)}}async getTrade(t){let r=await this.apiClient.getTrade(t);return {result:ie(r.result)}}async listListings(t){let r=await this.apiClient.listListings(t);return {page:O(r.page),result:r.result.map(I)}}async listBids(t){let r=await this.apiClient.listBids(t);return {page:O(r.page),result:r.result.map(N)}}async listCollectionBids(t){let r=await this.apiClient.listCollectionBids(t);return {page:O(r.page),result:r.result.map(w)}}async listTraitBids(t){let r=await this.apiClient.listTraitBids(t);return {page:O(r.page),result:r.result.map(k)}}async listMetadataBids(t){let r=await this.apiClient.listMetadataBids(t);return {page:O(r.page),result:r.result.map(v)}}async listTrades(t){let r=await this.apiClient.listTrades(t);return {page:O(r.page),result:r.result.map(ie)}}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 a=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:a.actions,completeListings:async d=>{let p=await this.createListing({makerFees:r[0].makerFees,orderComponents:a.orderComponents,orderHash:a.orderHash,orderSignature:typeof d=="string"?d:d[0]});return {result:[{success:!0,orderHash:a.orderHash,order:p.result}]}}}}if(await this.orderbookConfig.provider.getCode(t)!=="0x"){track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:t,listingsCount:r.length});let a=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:a.flatMap(n=>{let c=[];return n.actions.forEach(m=>{if(m.type==="TRANSACTION"){let l=n.orderComponents.offer[0].token;d.includes(l)||(d.push(l),c.push(m));}else c.push(m);}),c}),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(a.map((l,u)=>{let h=n[u];return this.apiClient.createListing({makerFees:r[u].makerFees,orderComponents:l.orderComponents,orderHash:l.orderHash,orderSignature:h}).catch(()=>{})}))).map((l,u)=>({success:!!l,orderHash:a[u].orderHash,order:l?I(l.result):void 0}))}}}}track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:t,listingsCount:r.length});let{actions:i,preparedOrders:o}=await this.seaport.prepareBulkSeaportOrders(t,r.map(a=>({offerItem:a.sell,considerationItem:a.buy,allowPartialFills:a.sell.type==="ERC1155",orderStart:a.orderStart||new Date,orderExpiry:a.orderExpiry||e.defaultOrderExpiry()})));return {actions:i,completeListings:async a=>{let d=typeof a=="object";if(d&&a.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let p=o.map(l=>l.orderComponents),n=d?a[0]:a,c=Se(n,p);return {result:(await Promise.all(p.map((l,u)=>{let h=c[u],T=o[u],qe=r[u];return this.apiClient.createListing({orderComponents:l,orderHash:T.orderHash,orderSignature:h,makerFees:qe.makerFees}).catch(()=>{})}))).map((l,u)=>({success:!!l,orderHash:o[u].orderHash,order:l?I(l.result):void 0}))}}}}async prepareListing({makerAddress:t,sell:r,buy:s,orderStart:i,orderExpiry:o}){return this.seaport.prepareSeaportOrder(t,r,s,r.type==="ERC1155",i||new Date,o||e.defaultOrderExpiry())}async createListing(t){let r=await this.apiClient.createListing(t);return {result:I(r.result)}}async prepareBid({makerAddress:t,sell:r,buy:s,orderStart:i,orderExpiry:o}){return this.seaport.prepareSeaportOrder(t,r,s,s.type==="ERC1155",i||new Date,o||e.defaultOrderExpiry())}async createBid(t){let r=await this.apiClient.createBid(t);return {result:N(r.result)}}async prepareCollectionBid({makerAddress:t,sell:r,buy:s,orderStart:i,orderExpiry:o}){return this.seaport.prepareSeaportOrder(t,r,s,!0,i||new Date,o||e.defaultOrderExpiry())}async createCollectionBid(t){let r=await this.apiClient.createCollectionBid(t);return {result:w(r.result)}}async prepareTraitBid({makerAddress:t,sell:r,buy:s,orderStart:i,orderExpiry:o}){return this.seaport.prepareSeaportOrder(t,r,s,!0,i||new Date,o||e.defaultOrderExpiry())}async createTraitBid(t){let r=await this.apiClient.createTraitBid(t);return {result:k(r.result)}}async prepareMetadataBid({makerAddress:t,sell:r,buy:s,orderStart:i,orderExpiry:o}){return this.seaport.prepareSeaportOrder(t,r,s,!0,i||new Date,o||e.defaultOrderExpiry())}async createMetadataBid(t){let r=await this.apiClient.createMetadataBid(t);return {result:v(r.result)}}async fulfillOrder(t,r,s,i,o){let a={order_id:t,taker_address:r,fees:s.map(m=>({type:C.type.TAKER_ECOSYSTEM,amount:m.amount,recipient_address:m.recipientAddress}))},d=o?[{identifier:o,proof:[]}]:void 0;o&&(a.token_id=o);let p=await this.apiClient.fulfillmentData([a]);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,c=p.result.fulfillable_orders[0].order;if(c.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${c.status}`);return this.seaport.fulfillOrder(c,r,n,i,d)}async fulfillBulkOrders(t,r){let s=t.map(o=>{let a="listingId"in o;return {orderId:a?o.listingId:o.orderId,takerFees:o.takerFees,amountToFill:o.amountToFill,tokenId:a?void 0:o.tokenId}}),i=await this.apiClient.fulfillmentData(s.map(o=>({order_id:o.orderId,taker_address:r,fees:o.takerFees.map(a=>({type:C.type.TAKER_ECOSYSTEM,amount:a.amount,recipient_address:a.recipientAddress})),token_id:o?.tokenId})));try{let o=i.result.fulfillable_orders.map(a=>{let d=s.find(n=>n.orderId===a.order.id&&n.tokenId===a.token_id);if(!d){let n=`Could not find order for order ${a.order.id}`;throw a.token_id&&(n+=` and token ID ${a.token_id}`),new Error(n)}let p=[];return d.tokenId&&p.push({identifier:d.tokenId,proof:[]}),{extraData:a.extra_data,order:a.order,unitsToFill:d.amountToFill,considerationCriteria:p}});return {...await this.seaport.fulfillBulkOrders(o,r),fulfillableOrders:i.result.fulfillable_orders.map(a=>D(a.order)),unfulfillableOrders:i.result.unfulfillable_orders.map(a=>({orderId:a.order_id,tokenId:a.token_id,reason:a.reason})),sufficientBalance:!0}}catch(o){if(String(o).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:i.result.fulfillable_orders.map(a=>D(a.order)),unfulfillableOrders:i.result.unfulfillable_orders.map(a=>({orderId:a.order_id,reason:a.reason})),sufficientBalance:!1};throw o}}async prepareOrderCancellations(t){let r=await this.orderbookConfig.provider.getNetwork(),s={name:"imtbl-order-book",chainId:Number(r.chainId),verifyingContract:this.orderbookConfig.seaportContractAddress},i={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},o={orders:t.map(a=>({id:a}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:s,types:i,value:o}}}}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}))),i=Promise.all(t.map(l=>this.apiClient.getBid(l).catch(u=>{if(u.status!==404)throw u}))),o=Promise.all(t.map(l=>this.apiClient.getCollectionBid(l).catch(u=>{if(u.status!==404)throw u}))),a=Promise.all(t.map(l=>this.apiClient.getTraitBid(l).catch(u=>{if(u.status!==404)throw u}))),d=Promise.all(t.map(l=>this.apiClient.getMetadataBid(l).catch(u=>{if(u.status!==404)throw u}))),p=[await Promise.all([s,i,o,a,d])].flat(2).filter(l=>l!==void 0).map(l=>l.result);if(p.length!==t.length){let l=t.filter(u=>!p.some(h=>h.id===u));throw new Error(`Orders ${l} not found`)}for(let l of p)if(l.account_address!==r.toLowerCase())throw new Error(`Only account ${l.account_address} can cancel order ${l.id}`);let n=p.map(l=>l.protocol_data.seaport_address);if(new Set(n).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(p,r)}}};var Ot={estimatedFulfillmentGasGwei:4e5};
|
|
10
10
|
|
|
11
|
-
export {
|
|
11
|
+
export { oe as ActionType, Xe as FeeType, U as OrderStatusName, ce as Orderbook, ne as SignablePurpose, he as TransactionPurpose, Ot as constants };
|