@imtbl/sdk 1.43.5 → 1.43.6
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/blockchain_data-b707cdfe.js +1 -0
- package/dist/blockchain_data.js +1 -1
- package/dist/browser/checkout/sdk.js +4 -4
- package/dist/{checkout-835624fb.js → checkout-2b3fb1c2.js} +2 -2
- package/dist/{checkout.d-ae9ca847.d.ts → checkout.d-7613e722.d.ts} +5 -0
- package/dist/checkout.d.ts +1 -1
- package/dist/checkout.js +1 -1
- package/dist/{config-e6decb95.js → config-85c79b7b.js} +1 -1
- package/dist/config.js +1 -1
- package/dist/{index-cfadae12.js → index-1465defe.js} +1 -1
- package/dist/{index-974c422d.js → index-3379fae3.js} +1 -1
- package/dist/{index-7d2761cb.js → index-79a47cb5.js} +1 -1
- package/dist/{index-3c4d20df.js → index-8891a569.js} +1 -1
- package/dist/{index-d7b7aff9.js → index-c6873334.js} +1 -1
- package/dist/{index-1ff17202.js → index-db991a0e.js} +1 -1
- package/dist/index.browser.js +4 -4
- package/dist/index.browser.js.map +1 -1
- package/dist/index.cjs +12 -7
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{minting_backend-10ddbfd1.js → minting_backend-e41ac518.js} +1 -1
- package/dist/minting_backend.js +1 -1
- package/dist/{orderbook-10fe79b7.js → orderbook-0f158b43.js} +1 -1
- package/dist/orderbook.js +1 -1
- package/dist/{passport-e96a6719.js → passport-5ce49992.js} +1 -1
- package/dist/passport.js +1 -1
- package/dist/webhook-acd3b92c.js +1 -0
- package/dist/webhook.js +1 -1
- package/dist/{x-7dcaea97.js → x-95ef888b.js} +1 -1
- package/dist/x.js +1 -1
- package/package.json +1 -1
- package/dist/blockchain_data-08e66ad1.js +0 -1
- package/dist/webhook-8b165b7a.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"sns-validator";import{E as e}from"./index-
|
|
1
|
+
import t from"sns-validator";import{E as e}from"./index-1465defe.js";const a=new t,i={[e.PRODUCTION]:"arn:aws:sns:us-east-2:362750628221:",[e.SANDBOX]:"arn:aws:sns:us-east-2:783421985614:"},r=async(t,e,r)=>{const d=await new Promise(((r,d)=>{a.validate(t,((t,a)=>{if(t)return d(t);if(!a.TopicArn.startsWith(i[e]))throw new Error("Invalid topic arn");return"SubscriptionConfirmation"===a?.Type&&fetch(a.SubscribeURL).then((()=>{r(a)})).catch((t=>{d(t)})),r(a)}))}));if("Notification"===d.Type){const t=JSON.parse(d.Message);switch(t.event_name){case"imtbl_zkevm_mint_request_updated":r?.zkevmMintRequestUpdated&&await(r?.zkevmMintRequestUpdated(t));break;case"imtbl_zkevm_activity_mint":r?.zkEvmActivityMint&&await(r?.zkEvmActivityMint(t));break;case"imtbl_zkevm_activity_burn":r?.zkEvmActivityBurn&&await(r?.zkEvmActivityBurn(t));break;case"imtbl_zkevm_activity_transfer":r?.zkEvmActivityTransfer&&await(r?.zkEvmActivityTransfer(t));break;case"imtbl_zkevm_activity_sale":r?.zkEvmActivitySale&&await(r?.zkEvmActivitySale(t));break;case"imtbl_zkevm_activity_deposit":r?.zkEvmActivityDeposit&&await(r?.zkEvmActivityDeposit(t));break;case"imtbl_zkevm_activity_withdrawal":r?.zkEvmActivityWithdrawal&&await(r?.zkEvmActivityWithdrawal(t));break;case"imtbl_zkevm_collection_updated":r?.zkEvmCollectionUpdated&&await(r?.zkEvmCollectionUpdated(t));break;case"imtbl_zkevm_nft_updated":r?.zkEvmNftUpdated&&await(r?.zkEvmNftUpdated(t));break;case"imtbl_zkevm_metadata_updated":r?.zkEvmMetadataUpdated&&await(r?.zkEvmMetadataUpdated(t));break;case"imtbl_zkevm_token_updated":r?.zkEvmTokenUpdated&&await(r?.zkEvmTokenUpdated(t));break;case"imtbl_zkevm_order_updated":r?.zkEvmOrderUpdated&&await(r?.zkEvmOrderUpdated(t));break;case"imtbl_zkevm_trade_created":r?.zkEvmTradeCreated&&await(r?.zkEvmTradeCreated(t));break;case"imtbl_x_nft_created":r?.xNftCreated&&await(r?.xNftCreated(t));break;case"imtbl_x_nft_updated":r?.xNftUpdated&&await(r?.xNftUpdated(t));break;case"imtbl_x_order_accepted":r?.xOrderAccepted&&await(r?.xOrderAccepted(t));break;case"imtbl_x_order_filled":r?.xOrderFilled&&await(r?.xOrderFilled(t));break;case"imtbl_x_order_cancelled":r?.xOrderCancelled&&await(r?.xOrderCancelled(t));break;case"imtbl_x_transfer_created":r?.xTransferCreated&&await(r?.xTransferCreated(t))}return r?.all&&await(r?.all(t)),t}return null};export{r as h};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"axios";import t from"form-data";import{providers as r,BigNumber as s,constants as a}from"ethers";import{ethers as n,FetchRequest as o,JsonRpcProvider as i,JsonRpcSigner as d,keccak256 as c,toUtf8Bytes as u,concat as l,TypedDataEncoder as p,zeroPadValue as h,toBeHex as m,AbiCoder as f}from"ethers-v6";import{MerkleTree as y}from"merkletreejs";import{E}from"./index-cfadae12.js";import{Seaport as C}from"@opensea/seaport-js";class _{config;constructor(e){this.config=e}}class g extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}}class T extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}}class A{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(e){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise(((t,r)=>{this._resolve=t,this._reject=r;const s=e=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(e)};return Object.defineProperty(s,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(s,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(s,"isCancelled",{get:()=>this._isCancelled}),e((e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(e))}),(e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(e))}),s)}))}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(const e of this._cancelHandlers)e()}catch(e){return void console.warn("Cancellation threw an error",e)}this._cancelHandlers.length=0,this._reject?.(new T("Request aborted"))}}get isCancelled(){return this._isCancelled}}const R=e=>null!=e,I=e=>"string"==typeof e,O=e=>I(e)&&""!==e,S=e=>"object"==typeof e&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.arrayBuffer&&"function"==typeof e.constructor&&"string"==typeof e.constructor.name&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),b=e=>{const t=[],r=(e,s)=>{R(s)&&(Array.isArray(s)?s.forEach((t=>{r(e,t)})):"object"==typeof s?Object.entries(s).forEach((([t,s])=>{r(`${e}[${t}]`,s)})):((e,r)=>{t.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(r))}`)})(e,s))};return Object.entries(e).forEach((([e,t])=>{r(e,t)})),t.length>0?`?${t.join("&")}`:""},w=async(e,t)=>"function"==typeof t?t(e):t,N=async(e,r,s)=>{const a=await w(r,e.TOKEN),n=await w(r,e.USERNAME),o=await w(r,e.PASSWORD),i=await w(r,e.HEADERS),d="function"==typeof s?.getHeaders&&s?.getHeaders()||{},c=Object.entries({Accept:"application/json",...i,...r.headers,...d}).filter((([e,t])=>R(t))).reduce(((e,[t,r])=>({...e,[t]:String(r)})),{});if(O(a)&&(c.Authorization=`Bearer ${a}`),O(n)&&O(o)){const e=(e=>{try{return btoa(e)}catch(t){return Buffer.from(e).toString("base64")}})(`${n}:${o}`);c.Authorization=`Basic ${e}`}return r.body&&(r.mediaType?c["Content-Type"]=r.mediaType:S(r.body)?c["Content-Type"]=r.body.type||"application/octet-stream":I(r.body)?c["Content-Type"]="text/plain":r.body instanceof t||(c["Content-Type"]="application/json")),c},L=(r,s)=>new A((async(a,n,o)=>{try{const n=((e,t)=>{const r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,((e,s)=>t.path?.hasOwnProperty(s)?r(String(t.path[s])):e)),a=`${e.BASE}${s}`;return t.query?`${a}${b(t.query)}`:a})(r,s),d=(e=>{if(e.formData){const r=new t,s=(e,t)=>{I(t)||S(t)?r.append(e,t):r.append(e,JSON.stringify(t))};return Object.entries(e.formData).filter((([e,t])=>R(t))).forEach((([e,t])=>{Array.isArray(t)?t.forEach((t=>s(e,t))):s(e,t)})),r}})(s),c=(e=>{if(e.body)return e.body})(s),u=await N(r,s,d);if(!o.isCancelled){const t=await(async(t,r,s,a,n,o,i)=>{const d=e.CancelToken.source(),c={url:s,headers:o,data:a??n,method:r.method,withCredentials:t.WITH_CREDENTIALS,cancelToken:d.token};i((()=>d.cancel("The user aborted a request.")));try{return await e.request(c)}catch(e){const t=e;if(t.response)return t.response;throw e}})(r,s,n,c,d,u,o),l=(e=>{if(204!==e.status)return e.data})(t),p=((e,t)=>{if(t){const r=e.headers[t];if(I(r))return r}})(t,s.responseHeader),h={url:n,ok:(i=t.status,i>=200&&i<300),status:t.status,statusText:t.statusText,body:p??l};((e,t)=>{const r={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(r)throw new g(e,t,r);if(!t.ok)throw new g(e,t,"Generic Error")})(s,h),a(h.body)}}catch(e){n(e)}var i}));class v extends _{constructor(e){super(e)}request(e){return L(this.config,e)}}class k{httpRequest;constructor(e){this.httpRequest=e}cancelOrders({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:e},body:t,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:e,status:t,sellItemContractAddress:r,buyItemType:s,buyItemContractAddress:a,accountAddress:n,sellItemMetadataId:o,sellItemTokenId:i,fromUpdatedAt:d,pageSize:c,sortBy:u,sortDirection:l,pageCursor:p}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:e},query:{status:t,sell_item_contract_address:r,buy_item_type:s,buy_item_contract_address:a,account_address:n,sell_item_metadata_id:o,sell_item_token_id:i,from_updated_at:d,page_size:c,sort_by:u,sort_direction:l,page_cursor:p},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:e},body:t,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getListing({chainName:e,listingId:t}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:e,listing_id:t},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:e},body:t,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:e,accountAddress:t,sellItemContractAddress:r,fromIndexedAt:s,pageSize:a,sortBy:n,sortDirection:o,pageCursor:i}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:e},query:{account_address:t,sell_item_contract_address:r,from_indexed_at:s,page_size:a,sort_by:n,sort_direction:o,page_cursor:i},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:e,tradeId:t}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:e,trade_id:t},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}}class D{orders;request;constructor(e,t=v){this.request=new t({BASE:e?.BASE??"https://api.immutable.com",VERSION:e?.VERSION??"1.0.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.orders=new k(this.request)}}var x,F,P,B,H,q,V,M,j,z;function $(e){const t=e.buy.map((e=>{if("ERC20"===e.type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.amount};if("NATIVE"===e.type)return{type:"NATIVE",amount:e.amount};throw new Error("Buy items must be either ERC20 or NATIVE")})),r=e.sell.map((e=>{if("ERC721"===e.type)return{type:"ERC721",contractAddress:e.contract_address,tokenId:e.token_id};if("ERC1155"===e.type)return{type:"ERC1155",contractAddress:e.contract_address,tokenId:e.token_id,amount:e.amount};throw new Error("Sell items must ERC721 or ERC1155")}));return{id:e.id,type:e.type,accountAddress:e.account_address,buy:t,sell:r,fees:e.fees.map((e=>({amount:e.amount,recipientAddress:e.recipient_address,type:e.type}))),fillStatus:e.fill_status,chain:e.chain,createdAt:e.created_at,endAt:e.end_at,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},salt:e.salt,signature:e.signature,startAt:e.start_at,status:e.status,updatedAt:e.updated_at}}function G(e){const t=e.buy.map((e=>{if("ERC20"===e.type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.amount};if("NATIVE"===e.type)return{type:"NATIVE",amount:e.amount};throw new Error("Buy items must be either ERC20 or NATIVE")})),r=e.sell.map((e=>{if("ERC721"===e.type)return{type:"ERC721",contractAddress:e.contract_address,tokenId:e.token_id};if("ERC1155"===e.type)return{type:"ERC1155",contractAddress:e.contract_address,tokenId:e.token_id,amount:e.amount};throw new Error("Sell items must ERC721")}));return{id:e.id,orderId:e.order_id,buy:t,sell:r,buyerFees:e.buyer_fees.map((e=>({amount:e.amount,recipientAddress:e.recipient_address,type:e.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 U(e){return{nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}!function(e){var t;(t=e.cancellation_type||(e.cancellation_type={})).ON_CHAIN="ON_CHAIN",t.OFF_CHAIN="OFF_CHAIN",t.UNDERFUNDED="UNDERFUNDED"}(x||(x={})),function(e){(e.reason_code||(e.reason_code={})).FILLED="FILLED"}(F||(F={})),function(e){var t;(t=e.type||(e.type={})).ROYALTY="ROYALTY",t.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",t.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",t.PROTOCOL="PROTOCOL"}(P||(P={})),function(e){(e.type||(e.type={})).LISTING="LISTING"}(B||(B={})),function(e){e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.FILLED="FILLED",e.EXPIRED="EXPIRED",e.CANCELLED="CANCELLED"}(H||(H={})),function(e){var t;(t=e.order_type||(e.order_type={})).FULL_RESTRICTED="FULL_RESTRICTED",t.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"}(q||(q={})),function(e){e.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",e.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",e.PROTOCOL="PROTOCOL",e.ROYALTY="ROYALTY"}(V||(V={})),function(e){e.APPROVAL="APPROVAL",e.FULFILL_ORDER="FULFILL_ORDER",e.CANCEL="CANCEL"}(M||(M={})),function(e){e.CREATE_LISTING="CREATE_LISTING",e.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION"}(j||(j={})),function(e){e.TRANSACTION="TRANSACTION",e.SIGNABLE="SIGNABLE"}(z||(z={}));const K="ImmutableSeaport",Y="1.5",W={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 Z,J,X,Q;!function(e){e[e.FULL_OPEN=0]="FULL_OPEN",e[e.PARTIAL_OPEN=1]="PARTIAL_OPEN",e[e.FULL_RESTRICTED=2]="FULL_RESTRICTED",e[e.PARTIAL_RESTRICTED=3]="PARTIAL_RESTRICTED"}(Z||(Z={})),function(e){e[e.NATIVE=0]="NATIVE",e[e.ERC20=1]="ERC20",e[e.ERC721=2]="ERC721",e[e.ERC1155=3]="ERC1155",e[e.ERC721_WITH_CRITERIA=4]="ERC721_WITH_CRITERIA",e[e.ERC1155_WITH_CRITERIA=5]="ERC1155_WITH_CRITERIA"}(J||(J={})),function(e){e[e.OFFER=0]="OFFER",e[e.CONSIDERATION=1]="CONSIDERATION"}(X||(X={})),function(e){e[e.ETH_TO_ERC721=0]="ETH_TO_ERC721",e[e.ETH_TO_ERC1155=1]="ETH_TO_ERC1155",e[e.ERC20_TO_ERC721=2]="ERC20_TO_ERC721",e[e.ERC20_TO_ERC1155=3]="ERC20_TO_ERC1155",e[e.ERC721_TO_ERC20=4]="ERC721_TO_ERC20",e[e.ERC1155_TO_ERC20=5]="ERC1155_TO_ERC20"}(Q||(Q={}));const ee={integer:0,address:n.zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},te=e=>void 0!==e&&(null!=e&&(["string","number"].includes(typeof e)&&0n===BigInt(e)||Array.isArray(e)&&e.every(te)||"object"==typeof e&&Object.values(e).every(te)||"boolean"==typeof e&&!1===e));class re{types;defaultValues={};constructor(e){this.types=e;for(const t in e){const e=this.getDefaultValue(t);if(this.defaultValues[t]=e,!te(e))throw new Error(`Got non-empty value for type ${t} in default generator: ${e}`)}}static from(e,t){const{defaultValues:r}=new re(e);return t?r[t]:r}getDefaultValue(e){if(this.defaultValues[e])return this.defaultValues[e];const t=function(e){const[,t]=e.match(/^bytes(\d+)$/)??[];return t?h("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),ee[e])}(e);if(void 0!==t)return t;const r=e.match(/^(.*)(\x5b(\d*)\x5d)$/);if(r){const e=r[1],t=parseInt(r[3]);if(t>0){const r=this.getDefaultValue(e);return Array(t).fill(r)}return[]}const s=this.types[e];if(s)return s.reduce(((e,{name:t,type:r})=>({...e,[t]:this.getDefaultValue(r)})),{});throw new Error(`unknown type: ${e}`)}}const se=(e,t)=>{return r=Math.ceil(e.length/t),s=r=>e.slice(r*t,(r+1)*t),Array(r).fill(0).map(((e,t)=>s(t)));var r,s},ae=e=>Buffer.from(e.slice(2),"hex"),ne=e=>ae(c(e)),oe=e=>ne(l(e)),ie=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),de=e=>se(e,2).map(oe);class ce{types;rootType;leafType;elements;depth;tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){const{elements:e}=this;return ie([...e],this.completedSize,this.defaultNode)}getCompleteLeaves(){const e=this.elements.map(this.leafHasher);return ie([...e],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(e){const t=this.getCompleteLeaves()[e];return{leaf:t,proof:this.tree.getHexProof(t,e),root:this.tree.getHexRoot()}}getEncodedProofAndSignature(e,t){const{proof:r}=this.getProof(e);return((e,t,r=`0x${"ff".repeat(64)}`)=>l([r,`0x${e.toString(16).padStart(6,"0")}`,f.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]))(e,r,t)}getDataToSign(){let e=this.getCompleteElements();for(;e.length>2;)e=se(e,2);return e}add(e){this.elements.push(e)}getBulkOrderHash(){const e=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),t=this.getCompleteLeaves().map(ae),r=(s=((e,t=!0)=>{if(0===e.length)throw new Error("empty tree");const r=[e.map((e=>{const r=Buffer.isBuffer(e)?e:ae(e);return t?ne(r):r}))];for(;r[r.length-1].length>1;)r.push(de(r[r.length-1]));return r[r.length-1][0]})(t,!1),m(s.toString("hex")));var s;const a=c(u(this.encoder.types.BulkOrder[0].type));if(c(l([a,r]))!==e)throw new Error("expected derived bulk order hash to match");return e}constructor(e,t,r,s,a){this.types=e,this.rootType=t,this.leafType=r,this.elements=s,this.depth=a;const n=p.from(e);var o,i;this.encoder=n,this.leafHasher=e=>n.hashStruct(r,e),this.defaultNode=re.from(e,r),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=(o=this.getCompleteLeaves(),i=this.defaultLeaf,new y(o.map(ae),ne,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:ae(i)}))}}function ue(e,t=0,r=function(e){return Math.max(Math.ceil(Math.log2(e)),1)}(e.length+t)){const s=function(e){return{...W,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}(r),a=re.from(s,"OrderComponents");let n=[...e];t>0&&(n=[...ie([],t,a),...e]);return new ce(s,"BulkOrder","OrderComponents",n,r)}function le(e,t,r){return async()=>{const a=await e.buildTransaction(),n={to:a.to,from:r,type:a.type,maxFeePerGas:a.maxFeePerGas?s.from(a.maxFeePerGas):void 0,maxPriorityFeePerGas:a.maxPriorityFeePerGas?s.from(a.maxPriorityFeePerGas):void 0,value:a.value?s.from(a.value):void 0,data:a.data,nonce:a.nonce,chainId:t};return n.gasLimit=s.from(await e.estimateGas()),n.gasLimit=n.gasLimit.add(n.gasLimit.div(5)),n}}function pe(e){const t=e.buy.map((t=>{switch(t.type){case"NATIVE":return{startAmount:t.amount,endAmount:t.amount,itemType:J.NATIVE,recipient:e.account_address,token:a.AddressZero,identifierOrCriteria:"0"};case"ERC20":return{startAmount:t.amount,endAmount:t.amount,itemType:J.ERC20,recipient:e.account_address,token:t.contract_address||a.AddressZero,identifierOrCriteria:"0"};default:return{startAmount:"1",endAmount:"1",itemType:J.ERC721,recipient:e.account_address,token:t.contract_address||a.AddressZero,identifierOrCriteria:"0"}}})),r=e.fees.map((t=>({amount:t.amount,itemType:"ERC20"===e.buy[0].type?J.ERC20:J.NATIVE,recipient:t.recipient_address,token:"ERC20"===e.buy[0].type?e.buy[0].contract_address:a.AddressZero,identifierOrCriteria:"0"})));return{orderComponents:{conduitKey:a.HashZero,consideration:[...t],offer:e.sell.map((t=>{let r;return"ERC1155"===t.type?(r=t,{startAmount:r.amount,endAmount:r.amount,itemType:J.ERC1155,recipient:e.account_address,token:r.contract_address,identifierOrCriteria:r.token_id}):(r=t,{startAmount:"1",endAmount:"1",itemType:J.ERC721,recipient:e.account_address,token:r.contract_address,identifierOrCriteria:r.token_id})})),counter:e.protocol_data.counter,endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),salt:e.salt,offerer:e.account_address,zone:e.protocol_data.zone_address,totalOriginalConsiderationItems:t.length,orderType:"ERC1155"===e.sell[0].type?Z.PARTIAL_RESTRICTED:Z.FULL_RESTRICTED,zoneHash:a.HashZero},tips:r}}function he(e,t){if("ERC1155"===e.sell[0].type&&!t){const{numerator:t,denominator:r}=e.fill_status,s=BigInt(e.sell[0].amount);if("0"===t||"0"===r)return s.toString();return((BigInt(r)-BigInt(t))*BigInt(s)/BigInt(r)).toString()}return t}class me{seaportLibFactory;provider;seaportContractAddress;zoneContractAddress;rateLimitingKey;constructor(e,t,r,s,a){this.seaportLibFactory=e,this.provider=t,this.seaportContractAddress=r,this.zoneContractAddress=s,this.rateLimitingKey=a}async prepareBulkSeaportOrders(e,t){const{actions:r}=await this.createSeaportOrders(e,t),a=r.filter((e=>"approval"===e.type)),n=await this.provider.getNetwork(),o=a.map((t=>({type:z.TRANSACTION,purpose:M.APPROVAL,buildTransaction:le(t.transactionMethods,n.chainId,e)}))),i=r.find((e=>"createBulk"===e.type));if(!i)throw new Error("No create bulk order action found");const d=await i.getMessageToSign(),{components:c,types:u,value:l}=function(e){const t=JSON.parse(e),r=t.message.tree.flat(1/0).filter((e=>"0x0000000000000000000000000000000000000000"!==e.offerer));for(const e of r)e.salt=s.from(e.salt).toHexString();return{components:r,types:t.types,value:t.message}}(d);return o.push({type:z.SIGNABLE,purpose:j.CREATE_LISTING,message:await this.getTypedDataFromBulkOrderComponents(u,l)}),{actions:o,preparedListings:c.map((e=>({orderComponents:e,orderHash:this.getSeaportLib().getOrderHash(e)})))}}async prepareSeaportOrder(e,t,r,a,n){const{actions:o}=await this.createSeaportOrder(e,t,r,a,n),i=[],d=o.find((e=>"approval"===e.type));d&&i.push({type:z.TRANSACTION,purpose:M.APPROVAL,buildTransaction:le(d.transactionMethods,(await this.provider.getNetwork()).chainId,e)});const c=o.find((e=>"create"===e.type));if(!c)throw new Error("No create order action found");const u=function(e){const t=JSON.parse(e).message;return t.salt=s.from(t.salt).toHexString(),t}(await c.getMessageToSign());return i.push({type:z.SIGNABLE,purpose:j.CREATE_LISTING,message:await this.getTypedDataFromOrderComponents(u)}),{actions:i,orderComponents:u,orderHash:this.getSeaportLib().getOrderHash(u)}}async fulfillOrder(e,t,r,s){const{orderComponents:a,tips:n}=pe(e),o=this.getSeaportLib(e),{actions:i}=await o.fulfillOrders({accountAddress:t,fulfillOrderDetails:[{order:{parameters:a,signature:e.signature},unitsToFill:he(e,s),extraData:r,tips:n}]}),d=[],c=i.find((e=>"approval"===e.type));c&&d.push({type:z.TRANSACTION,buildTransaction:le(c.transactionMethods,(await this.provider.getNetwork()).chainId,t),purpose:M.APPROVAL});const u=i.find((e=>"exchange"===e.type));if(!u)throw new Error("No exchange action found");return d.push({type:z.TRANSACTION,buildTransaction:le(u.transactionMethods,(await this.provider.getNetwork()).chainId,t),purpose:M.FULFILL_ORDER}),{actions:d,expiration:me.getExpirationISOTimeFromExtraData(r),order:$(e)}}async fulfillBulkOrders(e,t){const r=e.map((e=>{const{orderComponents:t,tips:r}=pe(e.order);return{order:{parameters:t,signature:e.order.signature},unitsToFill:he(e.order,e.unitsToFill),extraData:e.extraData,tips:r}})),{actions:s}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:r,accountAddress:t}),a=[],n=s.find((e=>"approval"===e.type));n&&a.push({type:z.TRANSACTION,buildTransaction:le(n.transactionMethods,(await this.provider.getNetwork()).chainId,t),purpose:M.APPROVAL});const o=s.find((e=>"exchange"===e.type));if(!o)throw new Error("No exchange action found");return a.push({type:z.TRANSACTION,buildTransaction:le(o.transactionMethods,(await this.provider.getNetwork()).chainId,t),purpose:M.FULFILL_ORDER}),{actions:a,expiration:r.map((e=>me.getExpirationISOTimeFromExtraData(e.extraData))).reduce(((e,t)=>new Date(e)<new Date(t)?e:t))}}async cancelOrders(e,t){const r=e.map((e=>pe(e).orderComponents)),s=this.getSeaportLib(e[0]),a=await s.cancelOrders(r,t);return{type:z.TRANSACTION,buildTransaction:le(a,(await this.provider.getNetwork()).chainId,t),purpose:M.CANCEL}}createSeaportOrders(e,t){return this.getSeaportLib().createBulkOrders(t.map((t=>{const{listingItem:r,considerationItem:s,orderStart:a,orderExpiry:n}=t,o="ERC721"===r.type?{itemType:J.ERC721,token:r.contractAddress,identifier:r.tokenId}:{itemType:J.ERC1155,token:r.contractAddress,identifier:r.tokenId,amount:r.amount};return{allowPartialFills:"ERC1155"===r.type,offer:[o],consideration:[{token:"ERC20"===s.type?s.contractAddress:void 0,amount:s.amount,recipient:e}],startTime:(a.getTime()/1e3).toFixed(0),endTime:(n.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}})),e)}createSeaportOrder(e,t,r,s,a){const n=this.getSeaportLib(),o="ERC721"===t.type?{itemType:J.ERC721,token:t.contractAddress,identifier:t.tokenId}:{itemType:J.ERC1155,token:t.contractAddress,identifier:t.tokenId,amount:t.amount};return n.createOrder({allowPartialFills:"ERC1155"===t.type,offer:[o],consideration:[{token:"ERC20"===r.type?r.contractAddress:void 0,amount:r.amount,recipient:e}],startTime:(s.getTime()/1e3).toFixed(0),endTime:(a.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},e)}async getTypedDataFromBulkOrderComponents(e,t){delete e.EIP712Domain;const{chainId:r}=await this.provider.getNetwork();return{domain:{name:K,version:Y,chainId:r,verifyingContract:this.seaportContractAddress},types:e,value:t}}async getTypedDataFromOrderComponents(e){const{chainId:t}=await this.provider.getNetwork();return{domain:{name:K,version:Y,chainId:t,verifyingContract:this.seaportContractAddress},types:W,value:e}}getSeaportLib(e){const t=e?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(t,this.rateLimitingKey)}static getExpirationISOTimeFromExtraData(e){const t=e.slice(44,60),r=parseInt(t,16);return new Date(1e3*r).toISOString()}}class fe{orderbookService;chainName;seaportAddress;constructor(e,t,r){this.orderbookService=e,this.chainName=t,this.seaportAddress=r}async fulfillmentData(e){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:e})}async getListing(e){return this.orderbookService.getListing({chainName:this.chainName,listingId:e})}async getTrade(e){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:e})}async listListings(e){return this.orderbookService.listListings({chainName:this.chainName,...e})}async listTrades(e){return this.orderbookService.listTrades({chainName:this.chainName,...e})}async cancelOrders(e,t,r){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:t,orders:e,signature:r}})}async createListing({orderHash:e,orderComponents:t,orderSignature:r,makerFees:s}){if(1!==t.offer.length)throw new Error("Only one item can be listed at a time");if(Number(t.offer[0].itemType)!==J.ERC721&&Number(t.offer[0].itemType)!==J.ERC1155)throw new Error("Only ERC721 / ERC1155 tokens can be listed");const a=[...t.consideration.map((e=>e.itemType))];if(!(1===new Set(a).size))throw new Error("All consideration items must be of the same type");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{account_address:t.offerer,buy:[{type:Number(t.consideration[0].itemType)===J.NATIVE?"NATIVE":"ERC20",amount:t.consideration[0].startAmount,contract_address:t.consideration[0].token}],fees:s.map((e=>({amount:e.amount,type:V.MAKER_ECOSYSTEM,recipient_address:e.recipientAddress}))),end_at:new Date(parseInt(`${t.endTime.toString()}000`,10)).toISOString(),order_hash:e,protocol_data:{order_type:Number(t.offer[0].itemType)===J.ERC1155?q.order_type.PARTIAL_RESTRICTED:q.order_type.FULL_RESTRICTED,zone_address:t.zone,seaport_address:this.seaportAddress,seaport_version:Y,counter:t.counter.toString()},salt:t.salt,sell:Number(t.offer[0].itemType)===J.ERC1155?[{contract_address:t.offer[0].token,token_id:t.offer[0].identifierOrCriteria,type:"ERC1155",amount:t.offer[0].startAmount}]:[{contract_address:t.offer[0].token,token_id:t.offer[0].identifierOrCriteria,type:"ERC721"}],signature:r,start_at:new Date(parseInt(`${t.startTime.toString()}000`,10)).toISOString()}})}}class ye{chainName;seaportAddress;orderbookClient;constructor(e,t,r,s){this.chainName=t,this.seaportAddress=r,this.orderbookClient=new D({BASE:e,HEADERS:s?{"x-api-key":s}:void 0})}create(){return new fe(this.orderbookClient.orders,this.chainName,this.seaportAddress)}}function Ee(e,t){return new r.JsonRpcProvider({url:e,headers:t?{"x-api-key":t}:void 0})}class Ce{defaultSeaportContractAddress;provider;constructor(e,t){this.defaultSeaportContractAddress=e,this.provider=t}create(e,t){const r=e??this.defaultSeaportContractAddress;return new C(function(e,t){const r=new o(e.connection.url);t&&r.setHeader("x-api-key",t);const s=new i(r);return s.getSigner=async function(e){null==e&&(e=0);const t=this.send("eth_accounts",[]);if("number"==typeof e){const r=await t;if(e>=r.length)throw new Error("no such account");return new d(this,r[e])}return new d(this,e)},s}(this.provider,t),{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}}class _e{apiClient;seaport;orderbookConfig;constructor(e){const t=function(e){switch(e.baseConfig.environment){case E.SANDBOX:return{seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:"imtbl-zkevm-testnet",provider:Ee("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case E.PRODUCTION:return{seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:"imtbl-zkevm-mainnet",provider:Ee("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}(e),r={...t,...e.overrides};if(e.overrides?.jsonRpcProviderUrl&&(r.provider=Ee(e.overrides?.jsonRpcProviderUrl,e.baseConfig.rateLimitingKey)),!r)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=r;const{apiEndpoint:s,chainName:a}=this.orderbookConfig;if(!s)throw new Error("API endpoint must be provided");this.apiClient=new ye(s,a,this.orderbookConfig.seaportContractAddress,e.baseConfig.rateLimitingKey).create();const n=new Ce(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new me(n,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,e.baseConfig.rateLimitingKey)}config(){return this.orderbookConfig}async getListing(e){return{result:$((await this.apiClient.getListing(e)).result)}}async getTrade(e){return{result:G((await this.apiClient.getTrade(e)).result)}}async listListings(e){const t=await this.apiClient.listListings(e);return{page:U(t.page),result:t.result.map($)}}async listTrades(e){const t=await this.apiClient.listTrades(e);return{page:U(t.page),result:t.result.map(G)}}async prepareBulkListings({makerAddress:e,listingParams:t}){if(t.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(1===t.length){const r=await this.seaport.prepareSeaportOrder(e,t[0].sell,t[0].buy,new Date,t[0].orderExpiry||new Date(Date.now()+63072e6));return{actions:r.actions,completeListings:async e=>{const s=await this.createListing({makerFees:t[0].makerFees,orderComponents:r.orderComponents,orderHash:r.orderHash,orderSignature:e});return{result:[{success:!0,orderHash:r.orderHash,order:s.result}]}}}}const{actions:r,preparedListings:s}=await this.seaport.prepareBulkSeaportOrders(e,t.map((e=>({listingItem:e.sell,considerationItem:e.buy,orderStart:new Date,orderExpiry:e.orderExpiry||new Date(Date.now()+63072e6)}))));return{actions:r,completeListings:async e=>{const r=s.map((e=>e.orderComponents)),a=function(e,t){const r=ue(t);return t.map(((t,s)=>r.getEncodedProofAndSignature(s,e)))}(e,r);return{result:(await Promise.all(r.map(((e,r)=>{const n=a[r],o=s[r],i=t[r];return this.apiClient.createListing({orderComponents:e,orderHash:o.orderHash,orderSignature:n,makerFees:i.makerFees}).catch((()=>{}))})))).map(((e,t)=>({success:!!e,orderHash:s[t].orderHash,order:e?$(e.result):void 0})))}}}}async prepareListing({makerAddress:e,sell:t,buy:r,orderExpiry:s}){return this.seaport.prepareSeaportOrder(e,t,r,new Date,s||new Date(Date.now()+63072e6))}async createListing(e){return{result:$((await this.apiClient.createListing({...e})).result)}}async fulfillOrder(e,t,r,s){const a=await this.apiClient.fulfillmentData([{order_id:e,taker_address:t,fees:r.map((e=>({amount:e.amount,type:V.TAKER_ECOSYSTEM,recipient_address:e.recipientAddress})))}]);if(a.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment date: ${a.result.unfulfillable_orders[0].reason}`);if(1!==a.result.fulfillable_orders?.length)throw new Error("unexpected fulfillable order result length");const n=a.result.fulfillable_orders[0].extra_data,o=a.result.fulfillable_orders[0].order;if(o.status.name!==H.ACTIVE)throw new Error(`Cannot fulfil order that is not active. Current status: ${o.status}`);return this.seaport.fulfillOrder(o,t,n,s)}async fulfillBulkOrders(e,t){const r=await this.apiClient.fulfillmentData(e.map((e=>({order_id:e.listingId,taker_address:t,fees:e.takerFees.map((e=>({amount:e.amount,type:V.TAKER_ECOSYSTEM,recipient_address:e.recipientAddress})))}))));try{const s=r.result.fulfillable_orders.map((t=>{const r=e.find((e=>e.listingId===t.order.id));if(!r)throw new Error(`Could not find listing for order ${t.order.id}`);return{extraData:t.extra_data,order:t.order,unitsToFill:r.amountToFill}}));return{...await this.seaport.fulfillBulkOrders(s,t),fulfillableOrders:r.result.fulfillable_orders.map((e=>$(e.order))),unfulfillableOrders:r.result.unfulfillable_orders.map((e=>({orderId:e.order_id,reason:e.reason}))),sufficientBalance:!0}}catch(e){if(String(e).includes("The fulfiller does not have the balances needed to fulfill."))return{fulfillableOrders:r.result.fulfillable_orders.map((e=>$(e.order))),unfulfillableOrders:r.result.unfulfillable_orders.map((e=>({orderId:e.order_id,reason:e.reason}))),sufficientBalance:!1};throw e}}async prepareOrderCancellations(e){const t={name:"imtbl-order-book",chainId:(await this.orderbookConfig.provider.getNetwork()).chainId,verifyingContract:this.orderbookConfig.seaportContractAddress},r={orders:e.map((e=>({id:e})))};return{signableAction:{purpose:j.OFF_CHAIN_CANCELLATION,type:z.SIGNABLE,message:{domain:t,types:{CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},value:r}}}}async cancelOrders(e,t,r){return this.apiClient.cancelOrders(e,t,r)}async cancelOrdersOnChain(e,t){const r=await Promise.all(e.map((e=>this.apiClient.getListing(e))));for(const e of r){if(e.result.status.name!==H.ACTIVE&&e.result.status.name!==H.INACTIVE&&e.result.status.name!==H.PENDING)throw new Error(`Cannot cancel order with status ${e.result.status}`);if(e.result.account_address!==t.toLowerCase())throw new Error(`Only account ${e.result.account_address} can cancel order ${e.result.id}`)}const s=r.map((e=>e.result)),a=s.map((e=>e.protocol_data.seaport_address));if(1!==new Set(...[a]).size)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return{cancellationAction:await this.seaport.cancelOrders(s,t)}}}const ge={estimatedFulfillmentGasGwei:4e5};export{z as A,V as F,H as O,j as S,M as T,_e as a,ge as c};
|
|
1
|
+
import e from"axios";import t from"form-data";import{providers as r,BigNumber as s,constants as a}from"ethers";import{ethers as n,FetchRequest as o,JsonRpcProvider as i,JsonRpcSigner as d,keccak256 as c,toUtf8Bytes as u,concat as l,TypedDataEncoder as p,zeroPadValue as h,toBeHex as m,AbiCoder as f}from"ethers-v6";import{MerkleTree as y}from"merkletreejs";import{E}from"./index-1465defe.js";import{Seaport as C}from"@opensea/seaport-js";class _{config;constructor(e){this.config=e}}class g extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}}class T extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}}class A{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(e){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise(((t,r)=>{this._resolve=t,this._reject=r;const s=e=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(e)};return Object.defineProperty(s,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(s,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(s,"isCancelled",{get:()=>this._isCancelled}),e((e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(e))}),(e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(e))}),s)}))}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(const e of this._cancelHandlers)e()}catch(e){return void console.warn("Cancellation threw an error",e)}this._cancelHandlers.length=0,this._reject?.(new T("Request aborted"))}}get isCancelled(){return this._isCancelled}}const R=e=>null!=e,I=e=>"string"==typeof e,O=e=>I(e)&&""!==e,S=e=>"object"==typeof e&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.arrayBuffer&&"function"==typeof e.constructor&&"string"==typeof e.constructor.name&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),b=e=>{const t=[],r=(e,s)=>{R(s)&&(Array.isArray(s)?s.forEach((t=>{r(e,t)})):"object"==typeof s?Object.entries(s).forEach((([t,s])=>{r(`${e}[${t}]`,s)})):((e,r)=>{t.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(r))}`)})(e,s))};return Object.entries(e).forEach((([e,t])=>{r(e,t)})),t.length>0?`?${t.join("&")}`:""},w=async(e,t)=>"function"==typeof t?t(e):t,N=async(e,r,s)=>{const a=await w(r,e.TOKEN),n=await w(r,e.USERNAME),o=await w(r,e.PASSWORD),i=await w(r,e.HEADERS),d="function"==typeof s?.getHeaders&&s?.getHeaders()||{},c=Object.entries({Accept:"application/json",...i,...r.headers,...d}).filter((([e,t])=>R(t))).reduce(((e,[t,r])=>({...e,[t]:String(r)})),{});if(O(a)&&(c.Authorization=`Bearer ${a}`),O(n)&&O(o)){const e=(e=>{try{return btoa(e)}catch(t){return Buffer.from(e).toString("base64")}})(`${n}:${o}`);c.Authorization=`Basic ${e}`}return r.body&&(r.mediaType?c["Content-Type"]=r.mediaType:S(r.body)?c["Content-Type"]=r.body.type||"application/octet-stream":I(r.body)?c["Content-Type"]="text/plain":r.body instanceof t||(c["Content-Type"]="application/json")),c},L=(r,s)=>new A((async(a,n,o)=>{try{const n=((e,t)=>{const r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,((e,s)=>t.path?.hasOwnProperty(s)?r(String(t.path[s])):e)),a=`${e.BASE}${s}`;return t.query?`${a}${b(t.query)}`:a})(r,s),d=(e=>{if(e.formData){const r=new t,s=(e,t)=>{I(t)||S(t)?r.append(e,t):r.append(e,JSON.stringify(t))};return Object.entries(e.formData).filter((([e,t])=>R(t))).forEach((([e,t])=>{Array.isArray(t)?t.forEach((t=>s(e,t))):s(e,t)})),r}})(s),c=(e=>{if(e.body)return e.body})(s),u=await N(r,s,d);if(!o.isCancelled){const t=await(async(t,r,s,a,n,o,i)=>{const d=e.CancelToken.source(),c={url:s,headers:o,data:a??n,method:r.method,withCredentials:t.WITH_CREDENTIALS,cancelToken:d.token};i((()=>d.cancel("The user aborted a request.")));try{return await e.request(c)}catch(e){const t=e;if(t.response)return t.response;throw e}})(r,s,n,c,d,u,o),l=(e=>{if(204!==e.status)return e.data})(t),p=((e,t)=>{if(t){const r=e.headers[t];if(I(r))return r}})(t,s.responseHeader),h={url:n,ok:(i=t.status,i>=200&&i<300),status:t.status,statusText:t.statusText,body:p??l};((e,t)=>{const r={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(r)throw new g(e,t,r);if(!t.ok)throw new g(e,t,"Generic Error")})(s,h),a(h.body)}}catch(e){n(e)}var i}));class v extends _{constructor(e){super(e)}request(e){return L(this.config,e)}}class k{httpRequest;constructor(e){this.httpRequest=e}cancelOrders({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:e},body:t,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:e,status:t,sellItemContractAddress:r,buyItemType:s,buyItemContractAddress:a,accountAddress:n,sellItemMetadataId:o,sellItemTokenId:i,fromUpdatedAt:d,pageSize:c,sortBy:u,sortDirection:l,pageCursor:p}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:e},query:{status:t,sell_item_contract_address:r,buy_item_type:s,buy_item_contract_address:a,account_address:n,sell_item_metadata_id:o,sell_item_token_id:i,from_updated_at:d,page_size:c,sort_by:u,sort_direction:l,page_cursor:p},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:e},body:t,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getListing({chainName:e,listingId:t}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:e,listing_id:t},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:e},body:t,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:e,accountAddress:t,sellItemContractAddress:r,fromIndexedAt:s,pageSize:a,sortBy:n,sortDirection:o,pageCursor:i}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:e},query:{account_address:t,sell_item_contract_address:r,from_indexed_at:s,page_size:a,sort_by:n,sort_direction:o,page_cursor:i},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:e,tradeId:t}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:e,trade_id:t},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}}class D{orders;request;constructor(e,t=v){this.request=new t({BASE:e?.BASE??"https://api.immutable.com",VERSION:e?.VERSION??"1.0.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.orders=new k(this.request)}}var x,F,P,B,H,q,V,M,j,z;function $(e){const t=e.buy.map((e=>{if("ERC20"===e.type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.amount};if("NATIVE"===e.type)return{type:"NATIVE",amount:e.amount};throw new Error("Buy items must be either ERC20 or NATIVE")})),r=e.sell.map((e=>{if("ERC721"===e.type)return{type:"ERC721",contractAddress:e.contract_address,tokenId:e.token_id};if("ERC1155"===e.type)return{type:"ERC1155",contractAddress:e.contract_address,tokenId:e.token_id,amount:e.amount};throw new Error("Sell items must ERC721 or ERC1155")}));return{id:e.id,type:e.type,accountAddress:e.account_address,buy:t,sell:r,fees:e.fees.map((e=>({amount:e.amount,recipientAddress:e.recipient_address,type:e.type}))),fillStatus:e.fill_status,chain:e.chain,createdAt:e.created_at,endAt:e.end_at,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},salt:e.salt,signature:e.signature,startAt:e.start_at,status:e.status,updatedAt:e.updated_at}}function G(e){const t=e.buy.map((e=>{if("ERC20"===e.type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.amount};if("NATIVE"===e.type)return{type:"NATIVE",amount:e.amount};throw new Error("Buy items must be either ERC20 or NATIVE")})),r=e.sell.map((e=>{if("ERC721"===e.type)return{type:"ERC721",contractAddress:e.contract_address,tokenId:e.token_id};if("ERC1155"===e.type)return{type:"ERC1155",contractAddress:e.contract_address,tokenId:e.token_id,amount:e.amount};throw new Error("Sell items must ERC721")}));return{id:e.id,orderId:e.order_id,buy:t,sell:r,buyerFees:e.buyer_fees.map((e=>({amount:e.amount,recipientAddress:e.recipient_address,type:e.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 U(e){return{nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}!function(e){var t;(t=e.cancellation_type||(e.cancellation_type={})).ON_CHAIN="ON_CHAIN",t.OFF_CHAIN="OFF_CHAIN",t.UNDERFUNDED="UNDERFUNDED"}(x||(x={})),function(e){(e.reason_code||(e.reason_code={})).FILLED="FILLED"}(F||(F={})),function(e){var t;(t=e.type||(e.type={})).ROYALTY="ROYALTY",t.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",t.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",t.PROTOCOL="PROTOCOL"}(P||(P={})),function(e){(e.type||(e.type={})).LISTING="LISTING"}(B||(B={})),function(e){e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.FILLED="FILLED",e.EXPIRED="EXPIRED",e.CANCELLED="CANCELLED"}(H||(H={})),function(e){var t;(t=e.order_type||(e.order_type={})).FULL_RESTRICTED="FULL_RESTRICTED",t.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"}(q||(q={})),function(e){e.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",e.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",e.PROTOCOL="PROTOCOL",e.ROYALTY="ROYALTY"}(V||(V={})),function(e){e.APPROVAL="APPROVAL",e.FULFILL_ORDER="FULFILL_ORDER",e.CANCEL="CANCEL"}(M||(M={})),function(e){e.CREATE_LISTING="CREATE_LISTING",e.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION"}(j||(j={})),function(e){e.TRANSACTION="TRANSACTION",e.SIGNABLE="SIGNABLE"}(z||(z={}));const K="ImmutableSeaport",Y="1.5",W={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 Z,J,X,Q;!function(e){e[e.FULL_OPEN=0]="FULL_OPEN",e[e.PARTIAL_OPEN=1]="PARTIAL_OPEN",e[e.FULL_RESTRICTED=2]="FULL_RESTRICTED",e[e.PARTIAL_RESTRICTED=3]="PARTIAL_RESTRICTED"}(Z||(Z={})),function(e){e[e.NATIVE=0]="NATIVE",e[e.ERC20=1]="ERC20",e[e.ERC721=2]="ERC721",e[e.ERC1155=3]="ERC1155",e[e.ERC721_WITH_CRITERIA=4]="ERC721_WITH_CRITERIA",e[e.ERC1155_WITH_CRITERIA=5]="ERC1155_WITH_CRITERIA"}(J||(J={})),function(e){e[e.OFFER=0]="OFFER",e[e.CONSIDERATION=1]="CONSIDERATION"}(X||(X={})),function(e){e[e.ETH_TO_ERC721=0]="ETH_TO_ERC721",e[e.ETH_TO_ERC1155=1]="ETH_TO_ERC1155",e[e.ERC20_TO_ERC721=2]="ERC20_TO_ERC721",e[e.ERC20_TO_ERC1155=3]="ERC20_TO_ERC1155",e[e.ERC721_TO_ERC20=4]="ERC721_TO_ERC20",e[e.ERC1155_TO_ERC20=5]="ERC1155_TO_ERC20"}(Q||(Q={}));const ee={integer:0,address:n.zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},te=e=>void 0!==e&&(null!=e&&(["string","number"].includes(typeof e)&&0n===BigInt(e)||Array.isArray(e)&&e.every(te)||"object"==typeof e&&Object.values(e).every(te)||"boolean"==typeof e&&!1===e));class re{types;defaultValues={};constructor(e){this.types=e;for(const t in e){const e=this.getDefaultValue(t);if(this.defaultValues[t]=e,!te(e))throw new Error(`Got non-empty value for type ${t} in default generator: ${e}`)}}static from(e,t){const{defaultValues:r}=new re(e);return t?r[t]:r}getDefaultValue(e){if(this.defaultValues[e])return this.defaultValues[e];const t=function(e){const[,t]=e.match(/^bytes(\d+)$/)??[];return t?h("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),ee[e])}(e);if(void 0!==t)return t;const r=e.match(/^(.*)(\x5b(\d*)\x5d)$/);if(r){const e=r[1],t=parseInt(r[3]);if(t>0){const r=this.getDefaultValue(e);return Array(t).fill(r)}return[]}const s=this.types[e];if(s)return s.reduce(((e,{name:t,type:r})=>({...e,[t]:this.getDefaultValue(r)})),{});throw new Error(`unknown type: ${e}`)}}const se=(e,t)=>{return r=Math.ceil(e.length/t),s=r=>e.slice(r*t,(r+1)*t),Array(r).fill(0).map(((e,t)=>s(t)));var r,s},ae=e=>Buffer.from(e.slice(2),"hex"),ne=e=>ae(c(e)),oe=e=>ne(l(e)),ie=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),de=e=>se(e,2).map(oe);class ce{types;rootType;leafType;elements;depth;tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){const{elements:e}=this;return ie([...e],this.completedSize,this.defaultNode)}getCompleteLeaves(){const e=this.elements.map(this.leafHasher);return ie([...e],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(e){const t=this.getCompleteLeaves()[e];return{leaf:t,proof:this.tree.getHexProof(t,e),root:this.tree.getHexRoot()}}getEncodedProofAndSignature(e,t){const{proof:r}=this.getProof(e);return((e,t,r=`0x${"ff".repeat(64)}`)=>l([r,`0x${e.toString(16).padStart(6,"0")}`,f.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]))(e,r,t)}getDataToSign(){let e=this.getCompleteElements();for(;e.length>2;)e=se(e,2);return e}add(e){this.elements.push(e)}getBulkOrderHash(){const e=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),t=this.getCompleteLeaves().map(ae),r=(s=((e,t=!0)=>{if(0===e.length)throw new Error("empty tree");const r=[e.map((e=>{const r=Buffer.isBuffer(e)?e:ae(e);return t?ne(r):r}))];for(;r[r.length-1].length>1;)r.push(de(r[r.length-1]));return r[r.length-1][0]})(t,!1),m(s.toString("hex")));var s;const a=c(u(this.encoder.types.BulkOrder[0].type));if(c(l([a,r]))!==e)throw new Error("expected derived bulk order hash to match");return e}constructor(e,t,r,s,a){this.types=e,this.rootType=t,this.leafType=r,this.elements=s,this.depth=a;const n=p.from(e);var o,i;this.encoder=n,this.leafHasher=e=>n.hashStruct(r,e),this.defaultNode=re.from(e,r),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=(o=this.getCompleteLeaves(),i=this.defaultLeaf,new y(o.map(ae),ne,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:ae(i)}))}}function ue(e,t=0,r=function(e){return Math.max(Math.ceil(Math.log2(e)),1)}(e.length+t)){const s=function(e){return{...W,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}(r),a=re.from(s,"OrderComponents");let n=[...e];t>0&&(n=[...ie([],t,a),...e]);return new ce(s,"BulkOrder","OrderComponents",n,r)}function le(e,t,r){return async()=>{const a=await e.buildTransaction(),n={to:a.to,from:r,type:a.type,maxFeePerGas:a.maxFeePerGas?s.from(a.maxFeePerGas):void 0,maxPriorityFeePerGas:a.maxPriorityFeePerGas?s.from(a.maxPriorityFeePerGas):void 0,value:a.value?s.from(a.value):void 0,data:a.data,nonce:a.nonce,chainId:t};return n.gasLimit=s.from(await e.estimateGas()),n.gasLimit=n.gasLimit.add(n.gasLimit.div(5)),n}}function pe(e){const t=e.buy.map((t=>{switch(t.type){case"NATIVE":return{startAmount:t.amount,endAmount:t.amount,itemType:J.NATIVE,recipient:e.account_address,token:a.AddressZero,identifierOrCriteria:"0"};case"ERC20":return{startAmount:t.amount,endAmount:t.amount,itemType:J.ERC20,recipient:e.account_address,token:t.contract_address||a.AddressZero,identifierOrCriteria:"0"};default:return{startAmount:"1",endAmount:"1",itemType:J.ERC721,recipient:e.account_address,token:t.contract_address||a.AddressZero,identifierOrCriteria:"0"}}})),r=e.fees.map((t=>({amount:t.amount,itemType:"ERC20"===e.buy[0].type?J.ERC20:J.NATIVE,recipient:t.recipient_address,token:"ERC20"===e.buy[0].type?e.buy[0].contract_address:a.AddressZero,identifierOrCriteria:"0"})));return{orderComponents:{conduitKey:a.HashZero,consideration:[...t],offer:e.sell.map((t=>{let r;return"ERC1155"===t.type?(r=t,{startAmount:r.amount,endAmount:r.amount,itemType:J.ERC1155,recipient:e.account_address,token:r.contract_address,identifierOrCriteria:r.token_id}):(r=t,{startAmount:"1",endAmount:"1",itemType:J.ERC721,recipient:e.account_address,token:r.contract_address,identifierOrCriteria:r.token_id})})),counter:e.protocol_data.counter,endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),salt:e.salt,offerer:e.account_address,zone:e.protocol_data.zone_address,totalOriginalConsiderationItems:t.length,orderType:"ERC1155"===e.sell[0].type?Z.PARTIAL_RESTRICTED:Z.FULL_RESTRICTED,zoneHash:a.HashZero},tips:r}}function he(e,t){if("ERC1155"===e.sell[0].type&&!t){const{numerator:t,denominator:r}=e.fill_status,s=BigInt(e.sell[0].amount);if("0"===t||"0"===r)return s.toString();return((BigInt(r)-BigInt(t))*BigInt(s)/BigInt(r)).toString()}return t}class me{seaportLibFactory;provider;seaportContractAddress;zoneContractAddress;rateLimitingKey;constructor(e,t,r,s,a){this.seaportLibFactory=e,this.provider=t,this.seaportContractAddress=r,this.zoneContractAddress=s,this.rateLimitingKey=a}async prepareBulkSeaportOrders(e,t){const{actions:r}=await this.createSeaportOrders(e,t),a=r.filter((e=>"approval"===e.type)),n=await this.provider.getNetwork(),o=a.map((t=>({type:z.TRANSACTION,purpose:M.APPROVAL,buildTransaction:le(t.transactionMethods,n.chainId,e)}))),i=r.find((e=>"createBulk"===e.type));if(!i)throw new Error("No create bulk order action found");const d=await i.getMessageToSign(),{components:c,types:u,value:l}=function(e){const t=JSON.parse(e),r=t.message.tree.flat(1/0).filter((e=>"0x0000000000000000000000000000000000000000"!==e.offerer));for(const e of r)e.salt=s.from(e.salt).toHexString();return{components:r,types:t.types,value:t.message}}(d);return o.push({type:z.SIGNABLE,purpose:j.CREATE_LISTING,message:await this.getTypedDataFromBulkOrderComponents(u,l)}),{actions:o,preparedListings:c.map((e=>({orderComponents:e,orderHash:this.getSeaportLib().getOrderHash(e)})))}}async prepareSeaportOrder(e,t,r,a,n){const{actions:o}=await this.createSeaportOrder(e,t,r,a,n),i=[],d=o.find((e=>"approval"===e.type));d&&i.push({type:z.TRANSACTION,purpose:M.APPROVAL,buildTransaction:le(d.transactionMethods,(await this.provider.getNetwork()).chainId,e)});const c=o.find((e=>"create"===e.type));if(!c)throw new Error("No create order action found");const u=function(e){const t=JSON.parse(e).message;return t.salt=s.from(t.salt).toHexString(),t}(await c.getMessageToSign());return i.push({type:z.SIGNABLE,purpose:j.CREATE_LISTING,message:await this.getTypedDataFromOrderComponents(u)}),{actions:i,orderComponents:u,orderHash:this.getSeaportLib().getOrderHash(u)}}async fulfillOrder(e,t,r,s){const{orderComponents:a,tips:n}=pe(e),o=this.getSeaportLib(e),{actions:i}=await o.fulfillOrders({accountAddress:t,fulfillOrderDetails:[{order:{parameters:a,signature:e.signature},unitsToFill:he(e,s),extraData:r,tips:n}]}),d=[],c=i.find((e=>"approval"===e.type));c&&d.push({type:z.TRANSACTION,buildTransaction:le(c.transactionMethods,(await this.provider.getNetwork()).chainId,t),purpose:M.APPROVAL});const u=i.find((e=>"exchange"===e.type));if(!u)throw new Error("No exchange action found");return d.push({type:z.TRANSACTION,buildTransaction:le(u.transactionMethods,(await this.provider.getNetwork()).chainId,t),purpose:M.FULFILL_ORDER}),{actions:d,expiration:me.getExpirationISOTimeFromExtraData(r),order:$(e)}}async fulfillBulkOrders(e,t){const r=e.map((e=>{const{orderComponents:t,tips:r}=pe(e.order);return{order:{parameters:t,signature:e.order.signature},unitsToFill:he(e.order,e.unitsToFill),extraData:e.extraData,tips:r}})),{actions:s}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:r,accountAddress:t}),a=[],n=s.find((e=>"approval"===e.type));n&&a.push({type:z.TRANSACTION,buildTransaction:le(n.transactionMethods,(await this.provider.getNetwork()).chainId,t),purpose:M.APPROVAL});const o=s.find((e=>"exchange"===e.type));if(!o)throw new Error("No exchange action found");return a.push({type:z.TRANSACTION,buildTransaction:le(o.transactionMethods,(await this.provider.getNetwork()).chainId,t),purpose:M.FULFILL_ORDER}),{actions:a,expiration:r.map((e=>me.getExpirationISOTimeFromExtraData(e.extraData))).reduce(((e,t)=>new Date(e)<new Date(t)?e:t))}}async cancelOrders(e,t){const r=e.map((e=>pe(e).orderComponents)),s=this.getSeaportLib(e[0]),a=await s.cancelOrders(r,t);return{type:z.TRANSACTION,buildTransaction:le(a,(await this.provider.getNetwork()).chainId,t),purpose:M.CANCEL}}createSeaportOrders(e,t){return this.getSeaportLib().createBulkOrders(t.map((t=>{const{listingItem:r,considerationItem:s,orderStart:a,orderExpiry:n}=t,o="ERC721"===r.type?{itemType:J.ERC721,token:r.contractAddress,identifier:r.tokenId}:{itemType:J.ERC1155,token:r.contractAddress,identifier:r.tokenId,amount:r.amount};return{allowPartialFills:"ERC1155"===r.type,offer:[o],consideration:[{token:"ERC20"===s.type?s.contractAddress:void 0,amount:s.amount,recipient:e}],startTime:(a.getTime()/1e3).toFixed(0),endTime:(n.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}})),e)}createSeaportOrder(e,t,r,s,a){const n=this.getSeaportLib(),o="ERC721"===t.type?{itemType:J.ERC721,token:t.contractAddress,identifier:t.tokenId}:{itemType:J.ERC1155,token:t.contractAddress,identifier:t.tokenId,amount:t.amount};return n.createOrder({allowPartialFills:"ERC1155"===t.type,offer:[o],consideration:[{token:"ERC20"===r.type?r.contractAddress:void 0,amount:r.amount,recipient:e}],startTime:(s.getTime()/1e3).toFixed(0),endTime:(a.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},e)}async getTypedDataFromBulkOrderComponents(e,t){delete e.EIP712Domain;const{chainId:r}=await this.provider.getNetwork();return{domain:{name:K,version:Y,chainId:r,verifyingContract:this.seaportContractAddress},types:e,value:t}}async getTypedDataFromOrderComponents(e){const{chainId:t}=await this.provider.getNetwork();return{domain:{name:K,version:Y,chainId:t,verifyingContract:this.seaportContractAddress},types:W,value:e}}getSeaportLib(e){const t=e?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(t,this.rateLimitingKey)}static getExpirationISOTimeFromExtraData(e){const t=e.slice(44,60),r=parseInt(t,16);return new Date(1e3*r).toISOString()}}class fe{orderbookService;chainName;seaportAddress;constructor(e,t,r){this.orderbookService=e,this.chainName=t,this.seaportAddress=r}async fulfillmentData(e){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:e})}async getListing(e){return this.orderbookService.getListing({chainName:this.chainName,listingId:e})}async getTrade(e){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:e})}async listListings(e){return this.orderbookService.listListings({chainName:this.chainName,...e})}async listTrades(e){return this.orderbookService.listTrades({chainName:this.chainName,...e})}async cancelOrders(e,t,r){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:t,orders:e,signature:r}})}async createListing({orderHash:e,orderComponents:t,orderSignature:r,makerFees:s}){if(1!==t.offer.length)throw new Error("Only one item can be listed at a time");if(Number(t.offer[0].itemType)!==J.ERC721&&Number(t.offer[0].itemType)!==J.ERC1155)throw new Error("Only ERC721 / ERC1155 tokens can be listed");const a=[...t.consideration.map((e=>e.itemType))];if(!(1===new Set(a).size))throw new Error("All consideration items must be of the same type");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{account_address:t.offerer,buy:[{type:Number(t.consideration[0].itemType)===J.NATIVE?"NATIVE":"ERC20",amount:t.consideration[0].startAmount,contract_address:t.consideration[0].token}],fees:s.map((e=>({amount:e.amount,type:V.MAKER_ECOSYSTEM,recipient_address:e.recipientAddress}))),end_at:new Date(parseInt(`${t.endTime.toString()}000`,10)).toISOString(),order_hash:e,protocol_data:{order_type:Number(t.offer[0].itemType)===J.ERC1155?q.order_type.PARTIAL_RESTRICTED:q.order_type.FULL_RESTRICTED,zone_address:t.zone,seaport_address:this.seaportAddress,seaport_version:Y,counter:t.counter.toString()},salt:t.salt,sell:Number(t.offer[0].itemType)===J.ERC1155?[{contract_address:t.offer[0].token,token_id:t.offer[0].identifierOrCriteria,type:"ERC1155",amount:t.offer[0].startAmount}]:[{contract_address:t.offer[0].token,token_id:t.offer[0].identifierOrCriteria,type:"ERC721"}],signature:r,start_at:new Date(parseInt(`${t.startTime.toString()}000`,10)).toISOString()}})}}class ye{chainName;seaportAddress;orderbookClient;constructor(e,t,r,s){this.chainName=t,this.seaportAddress=r,this.orderbookClient=new D({BASE:e,HEADERS:s?{"x-api-key":s}:void 0})}create(){return new fe(this.orderbookClient.orders,this.chainName,this.seaportAddress)}}function Ee(e,t){return new r.JsonRpcProvider({url:e,headers:t?{"x-api-key":t}:void 0})}class Ce{defaultSeaportContractAddress;provider;constructor(e,t){this.defaultSeaportContractAddress=e,this.provider=t}create(e,t){const r=e??this.defaultSeaportContractAddress;return new C(function(e,t){const r=new o(e.connection.url);t&&r.setHeader("x-api-key",t);const s=new i(r);return s.getSigner=async function(e){null==e&&(e=0);const t=this.send("eth_accounts",[]);if("number"==typeof e){const r=await t;if(e>=r.length)throw new Error("no such account");return new d(this,r[e])}return new d(this,e)},s}(this.provider,t),{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}}class _e{apiClient;seaport;orderbookConfig;constructor(e){const t=function(e){switch(e.baseConfig.environment){case E.SANDBOX:return{seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:"imtbl-zkevm-testnet",provider:Ee("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case E.PRODUCTION:return{seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:"imtbl-zkevm-mainnet",provider:Ee("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}(e),r={...t,...e.overrides};if(e.overrides?.jsonRpcProviderUrl&&(r.provider=Ee(e.overrides?.jsonRpcProviderUrl,e.baseConfig.rateLimitingKey)),!r)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=r;const{apiEndpoint:s,chainName:a}=this.orderbookConfig;if(!s)throw new Error("API endpoint must be provided");this.apiClient=new ye(s,a,this.orderbookConfig.seaportContractAddress,e.baseConfig.rateLimitingKey).create();const n=new Ce(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new me(n,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,e.baseConfig.rateLimitingKey)}config(){return this.orderbookConfig}async getListing(e){return{result:$((await this.apiClient.getListing(e)).result)}}async getTrade(e){return{result:G((await this.apiClient.getTrade(e)).result)}}async listListings(e){const t=await this.apiClient.listListings(e);return{page:U(t.page),result:t.result.map($)}}async listTrades(e){const t=await this.apiClient.listTrades(e);return{page:U(t.page),result:t.result.map(G)}}async prepareBulkListings({makerAddress:e,listingParams:t}){if(t.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(1===t.length){const r=await this.seaport.prepareSeaportOrder(e,t[0].sell,t[0].buy,new Date,t[0].orderExpiry||new Date(Date.now()+63072e6));return{actions:r.actions,completeListings:async e=>{const s=await this.createListing({makerFees:t[0].makerFees,orderComponents:r.orderComponents,orderHash:r.orderHash,orderSignature:e});return{result:[{success:!0,orderHash:r.orderHash,order:s.result}]}}}}const{actions:r,preparedListings:s}=await this.seaport.prepareBulkSeaportOrders(e,t.map((e=>({listingItem:e.sell,considerationItem:e.buy,orderStart:new Date,orderExpiry:e.orderExpiry||new Date(Date.now()+63072e6)}))));return{actions:r,completeListings:async e=>{const r=s.map((e=>e.orderComponents)),a=function(e,t){const r=ue(t);return t.map(((t,s)=>r.getEncodedProofAndSignature(s,e)))}(e,r);return{result:(await Promise.all(r.map(((e,r)=>{const n=a[r],o=s[r],i=t[r];return this.apiClient.createListing({orderComponents:e,orderHash:o.orderHash,orderSignature:n,makerFees:i.makerFees}).catch((()=>{}))})))).map(((e,t)=>({success:!!e,orderHash:s[t].orderHash,order:e?$(e.result):void 0})))}}}}async prepareListing({makerAddress:e,sell:t,buy:r,orderExpiry:s}){return this.seaport.prepareSeaportOrder(e,t,r,new Date,s||new Date(Date.now()+63072e6))}async createListing(e){return{result:$((await this.apiClient.createListing({...e})).result)}}async fulfillOrder(e,t,r,s){const a=await this.apiClient.fulfillmentData([{order_id:e,taker_address:t,fees:r.map((e=>({amount:e.amount,type:V.TAKER_ECOSYSTEM,recipient_address:e.recipientAddress})))}]);if(a.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment date: ${a.result.unfulfillable_orders[0].reason}`);if(1!==a.result.fulfillable_orders?.length)throw new Error("unexpected fulfillable order result length");const n=a.result.fulfillable_orders[0].extra_data,o=a.result.fulfillable_orders[0].order;if(o.status.name!==H.ACTIVE)throw new Error(`Cannot fulfil order that is not active. Current status: ${o.status}`);return this.seaport.fulfillOrder(o,t,n,s)}async fulfillBulkOrders(e,t){const r=await this.apiClient.fulfillmentData(e.map((e=>({order_id:e.listingId,taker_address:t,fees:e.takerFees.map((e=>({amount:e.amount,type:V.TAKER_ECOSYSTEM,recipient_address:e.recipientAddress})))}))));try{const s=r.result.fulfillable_orders.map((t=>{const r=e.find((e=>e.listingId===t.order.id));if(!r)throw new Error(`Could not find listing for order ${t.order.id}`);return{extraData:t.extra_data,order:t.order,unitsToFill:r.amountToFill}}));return{...await this.seaport.fulfillBulkOrders(s,t),fulfillableOrders:r.result.fulfillable_orders.map((e=>$(e.order))),unfulfillableOrders:r.result.unfulfillable_orders.map((e=>({orderId:e.order_id,reason:e.reason}))),sufficientBalance:!0}}catch(e){if(String(e).includes("The fulfiller does not have the balances needed to fulfill."))return{fulfillableOrders:r.result.fulfillable_orders.map((e=>$(e.order))),unfulfillableOrders:r.result.unfulfillable_orders.map((e=>({orderId:e.order_id,reason:e.reason}))),sufficientBalance:!1};throw e}}async prepareOrderCancellations(e){const t={name:"imtbl-order-book",chainId:(await this.orderbookConfig.provider.getNetwork()).chainId,verifyingContract:this.orderbookConfig.seaportContractAddress},r={orders:e.map((e=>({id:e})))};return{signableAction:{purpose:j.OFF_CHAIN_CANCELLATION,type:z.SIGNABLE,message:{domain:t,types:{CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},value:r}}}}async cancelOrders(e,t,r){return this.apiClient.cancelOrders(e,t,r)}async cancelOrdersOnChain(e,t){const r=await Promise.all(e.map((e=>this.apiClient.getListing(e))));for(const e of r){if(e.result.status.name!==H.ACTIVE&&e.result.status.name!==H.INACTIVE&&e.result.status.name!==H.PENDING)throw new Error(`Cannot cancel order with status ${e.result.status}`);if(e.result.account_address!==t.toLowerCase())throw new Error(`Only account ${e.result.account_address} can cancel order ${e.result.id}`)}const s=r.map((e=>e.result)),a=s.map((e=>e.protocol_data.seaport_address));if(1!==new Set(...[a]).size)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return{cancellationAction:await this.seaport.cancelOrders(s,t)}}}const ge={estimatedFulfillmentGasGwei:4e5};export{z as A,V as F,H as O,j as S,M as T,_e as a,ge as c};
|