@imtbl/orderbook 2.0.0-alpha.4 → 2.0.0-alpha.5

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.
@@ -6,6 +6,6 @@ import { MerkleTree } from 'merkletreejs';
6
6
  import { Environment } from '@imtbl/config';
7
7
  import { Seaport } from '@opensea/seaport-js';
8
8
 
9
- var te={},tt=!1;function Kt(){if(tt)return te;tt=!0,te.byteLength=h,te.toByteArray=f,te.fromByteArray=g;for(var r=[],n=[],l=typeof Uint8Array<"u"?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=0,c=a.length;u<c;++u)r[u]=a[u],n[a.charCodeAt(u)]=u;n[45]=62,n[95]=63;function o(C){var I=C.length;if(I%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var _=C.indexOf("=");_===-1&&(_=I);var L=_===I?0:4-_%4;return [_,L]}function h(C){var I=o(C),_=I[0],L=I[1];return (_+L)*3/4-L}function E(C,I,_){return (I+_)*3/4-_}function f(C){var I,_=o(C),L=_[0],k=_[1],x=new l(E(C,L,k)),D=0,q=k>0?L-4:L,N;for(N=0;N<q;N+=4)I=n[C.charCodeAt(N)]<<18|n[C.charCodeAt(N+1)]<<12|n[C.charCodeAt(N+2)]<<6|n[C.charCodeAt(N+3)],x[D++]=I>>16&255,x[D++]=I>>8&255,x[D++]=I&255;return k===2&&(I=n[C.charCodeAt(N)]<<2|n[C.charCodeAt(N+1)]>>4,x[D++]=I&255),k===1&&(I=n[C.charCodeAt(N)]<<10|n[C.charCodeAt(N+1)]<<4|n[C.charCodeAt(N+2)]>>2,x[D++]=I>>8&255,x[D++]=I&255),x}function y(C){return r[C>>18&63]+r[C>>12&63]+r[C>>6&63]+r[C&63]}function R(C,I,_){for(var L,k=[],x=I;x<_;x+=3)L=(C[x]<<16&16711680)+(C[x+1]<<8&65280)+(C[x+2]&255),k.push(y(L));return k.join("")}function g(C){for(var I,_=C.length,L=_%3,k=[],x=16383,D=0,q=_-L;D<q;D+=x)k.push(R(C,D,D+x>q?q:D+x));return L===1?(I=C[_-1],k.push(r[I>>2]+r[I<<4&63]+"==")):L===2&&(I=(C[_-2]<<8)+C[_-1],k.push(r[I>>10]+r[I>>4&63]+r[I<<2&63]+"=")),k.join("")}return te}var de={},rt=!1;function Jt(){if(rt)return de;rt=!0;return de.read=function(r,n,l,a,u){var c,o,h=u*8-a-1,E=(1<<h)-1,f=E>>1,y=-7,R=l?u-1:0,g=l?-1:1,C=r[n+R];for(R+=g,c=C&(1<<-y)-1,C>>=-y,y+=h;y>0;c=c*256+r[n+R],R+=g,y-=8);for(o=c&(1<<-y)-1,c>>=-y,y+=a;y>0;o=o*256+r[n+R],R+=g,y-=8);if(c===0)c=1-f;else {if(c===E)return o?NaN:(C?-1:1)*(1/0);o=o+Math.pow(2,a),c=c-f;}return (C?-1:1)*o*Math.pow(2,c-a)},de.write=function(r,n,l,a,u,c){var o,h,E,f=c*8-u-1,y=(1<<f)-1,R=y>>1,g=u===23?Math.pow(2,-24)-Math.pow(2,-77):0,C=a?0:c-1,I=a?1:-1,_=n<0||n===0&&1/n<0?1:0;for(n=Math.abs(n),isNaN(n)||n===1/0?(h=isNaN(n)?1:0,o=y):(o=Math.floor(Math.log(n)/Math.LN2),n*(E=Math.pow(2,-o))<1&&(o--,E*=2),o+R>=1?n+=g/E:n+=g*Math.pow(2,1-R),n*E>=2&&(o++,E/=2),o+R>=y?(h=0,o=y):o+R>=1?(h=(n*E-1)*Math.pow(2,u),o=o+R):(h=n*Math.pow(2,R-1)*Math.pow(2,u),o=0));u>=8;r[l+C]=h&255,C+=I,h/=256,u-=8);for(o=o<<u|h,f+=u;f>0;r[l+C]=o&255,C+=I,o/=256,f-=8);r[l+C-I]|=_*128;},de}var G={},nt=!1;function Xt(){if(nt)return G;nt=!0;let r=Kt(),n=Jt(),l=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;G.Buffer=o,G.SlowBuffer=k,G.INSPECT_MAX_BYTES=50;let a=2147483647;G.kMaxLength=a,o.TYPED_ARRAY_SUPPORT=u(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function u(){try{let i=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(i,e),i.foo()===42}catch{return !1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function c(i){if(i>a)throw new RangeError('The value "'+i+'" is invalid for option "size"');let e=new Uint8Array(i);return Object.setPrototypeOf(e,o.prototype),e}function o(i,e,t){if(typeof i=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return y(i)}return h(i,e,t)}o.poolSize=8192;function h(i,e,t){if(typeof i=="string")return R(i,e);if(ArrayBuffer.isView(i))return C(i);if(i==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof i);if(M(i,ArrayBuffer)||i&&M(i.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(M(i,SharedArrayBuffer)||i&&M(i.buffer,SharedArrayBuffer)))return I(i,e,t);if(typeof i=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let s=i.valueOf&&i.valueOf();if(s!=null&&s!==i)return o.from(s,e,t);let p=_(i);if(p)return p;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof i[Symbol.toPrimitive]=="function")return o.from(i[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof i)}o.from=function(i,e,t){return h(i,e,t)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function E(i){if(typeof i!="number")throw new TypeError('"size" argument must be of type number');if(i<0)throw new RangeError('The value "'+i+'" is invalid for option "size"')}function f(i,e,t){return E(i),i<=0?c(i):e!==void 0?typeof t=="string"?c(i).fill(e,t):c(i).fill(e):c(i)}o.alloc=function(i,e,t){return f(i,e,t)};function y(i){return E(i),c(i<0?0:L(i)|0)}o.allocUnsafe=function(i){return y(i)},o.allocUnsafeSlow=function(i){return y(i)};function R(i,e){if((typeof e!="string"||e==="")&&(e="utf8"),!o.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=x(i,e)|0,s=c(t),p=s.write(i,e);return p!==t&&(s=s.slice(0,p)),s}function g(i){let e=i.length<0?0:L(i.length)|0,t=c(e);for(let s=0;s<e;s+=1)t[s]=i[s]&255;return t}function C(i){if(M(i,Uint8Array)){let e=new Uint8Array(i);return I(e.buffer,e.byteOffset,e.byteLength)}return g(i)}function I(i,e,t){if(e<0||i.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(i.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');let s;return e===void 0&&t===void 0?s=new Uint8Array(i):t===void 0?s=new Uint8Array(i,e):s=new Uint8Array(i,e,t),Object.setPrototypeOf(s,o.prototype),s}function _(i){if(o.isBuffer(i)){let e=L(i.length)|0,t=c(e);return t.length===0||i.copy(t,0,0,e),t}if(i.length!==void 0)return typeof i.length!="number"||Ne(i.length)?c(0):g(i);if(i.type==="Buffer"&&Array.isArray(i.data))return g(i.data)}function L(i){if(i>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return i|0}function k(i){return +i!=i&&(i=0),o.alloc(+i)}o.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==o.prototype},o.compare=function(e,t){if(M(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),M(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let s=e.length,p=t.length;for(let d=0,m=Math.min(s,p);d<m;++d)if(e[d]!==t[d]){s=e[d],p=t[d];break}return s<p?-1:p<s?1:0},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return !0;default:return !1}},o.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return o.alloc(0);let s;if(t===void 0)for(t=0,s=0;s<e.length;++s)t+=e[s].length;let p=o.allocUnsafe(t),d=0;for(s=0;s<e.length;++s){let m=e[s];if(M(m,Uint8Array))d+m.length>p.length?(o.isBuffer(m)||(m=o.from(m)),m.copy(p,d)):Uint8Array.prototype.set.call(p,m,d);else if(o.isBuffer(m))m.copy(p,d);else throw new TypeError('"list" argument must be an Array of Buffers');d+=m.length;}return p};function x(i,e){if(o.isBuffer(i))return i.length;if(ArrayBuffer.isView(i)||M(i,ArrayBuffer))return i.byteLength;if(typeof i!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof i);let t=i.length,s=arguments.length>2&&arguments[2]===!0;if(!s&&t===0)return 0;let p=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return Pe(i).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return et(i).length;default:if(p)return s?-1:Pe(i).length;e=(""+e).toLowerCase(),p=!0;}}o.byteLength=x;function D(i,e,t){let s=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return "";for(i||(i="utf8");;)switch(i){case"hex":return Ht(this,e,t);case"utf8":case"utf-8":return Ge(this,e,t);case"ascii":return Ut(this,e,t);case"latin1":case"binary":return qt(this,e,t);case"base64":return Ft(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Mt(this,e,t);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(i+"").toLowerCase(),s=!0;}}o.prototype._isBuffer=!0;function q(i,e,t){let s=i[e];i[e]=i[t],i[t]=s;}o.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)q(this,t,t+1);return this},o.prototype.swap32=function(){let e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)q(this,t,t+3),q(this,t+1,t+2);return this},o.prototype.swap64=function(){let e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)q(this,t,t+7),q(this,t+1,t+6),q(this,t+2,t+5),q(this,t+3,t+4);return this},o.prototype.toString=function(){let e=this.length;return e===0?"":arguments.length===0?Ge(this,0,e):D.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:o.compare(this,e)===0},o.prototype.inspect=function(){let e="",t=G.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},l&&(o.prototype[l]=o.prototype.inspect),o.prototype.compare=function(e,t,s,p,d){if(M(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),s===void 0&&(s=e?e.length:0),p===void 0&&(p=0),d===void 0&&(d=this.length),t<0||s>e.length||p<0||d>this.length)throw new RangeError("out of range index");if(p>=d&&t>=s)return 0;if(p>=d)return -1;if(t>=s)return 1;if(t>>>=0,s>>>=0,p>>>=0,d>>>=0,this===e)return 0;let m=d-p,A=s-t,b=Math.min(m,A),w=this.slice(p,d),S=e.slice(t,s);for(let B=0;B<b;++B)if(w[B]!==S[B]){m=w[B],A=S[B];break}return m<A?-1:A<m?1:0};function N(i,e,t,s,p){if(i.length===0)return -1;if(typeof t=="string"?(s=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,Ne(t)&&(t=p?0:i.length-1),t<0&&(t=i.length+t),t>=i.length){if(p)return -1;t=i.length-1;}else if(t<0)if(p)t=0;else return -1;if(typeof e=="string"&&(e=o.from(e,s)),o.isBuffer(e))return e.length===0?-1:ze(i,e,t,s,p);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?p?Uint8Array.prototype.indexOf.call(i,e,t):Uint8Array.prototype.lastIndexOf.call(i,e,t):ze(i,[e],t,s,p);throw new TypeError("val must be string, number or Buffer")}function ze(i,e,t,s,p){let d=1,m=i.length,A=e.length;if(s!==void 0&&(s=String(s).toLowerCase(),s==="ucs2"||s==="ucs-2"||s==="utf16le"||s==="utf-16le")){if(i.length<2||e.length<2)return -1;d=2,m/=2,A/=2,t/=2;}function b(S,B){return d===1?S[B]:S.readUInt16BE(B*d)}let w;if(p){let S=-1;for(w=t;w<m;w++)if(b(i,w)===b(e,S===-1?0:w-S)){if(S===-1&&(S=w),w-S+1===A)return S*d}else S!==-1&&(w-=w-S),S=-1;}else for(t+A>m&&(t=m-A),w=t;w>=0;w--){let S=!0;for(let B=0;B<A;B++)if(b(i,w+B)!==b(e,B)){S=!1;break}if(S)return w}return -1}o.prototype.includes=function(e,t,s){return this.indexOf(e,t,s)!==-1},o.prototype.indexOf=function(e,t,s){return N(this,e,t,s,!0)},o.prototype.lastIndexOf=function(e,t,s){return N(this,e,t,s,!1)};function xt(i,e,t,s){t=Number(t)||0;let p=i.length-t;s?(s=Number(s),s>p&&(s=p)):s=p;let d=e.length;s>d/2&&(s=d/2);let m;for(m=0;m<s;++m){let A=parseInt(e.substr(m*2,2),16);if(Ne(A))return m;i[t+m]=A;}return m}function Pt(i,e,t,s){return ue(Pe(e,i.length-t),i,t,s)}function Nt(i,e,t,s){return ue(Gt(e),i,t,s)}function kt(i,e,t,s){return ue(et(e),i,t,s)}function Dt(i,e,t,s){return ue(jt(e,i.length-t),i,t,s)}o.prototype.write=function(e,t,s,p){if(t===void 0)p="utf8",s=this.length,t=0;else if(s===void 0&&typeof t=="string")p=t,s=this.length,t=0;else if(isFinite(t))t=t>>>0,isFinite(s)?(s=s>>>0,p===void 0&&(p="utf8")):(p=s,s=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let d=this.length-t;if((s===void 0||s>d)&&(s=d),e.length>0&&(s<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");p||(p="utf8");let m=!1;for(;;)switch(p){case"hex":return xt(this,e,t,s);case"utf8":case"utf-8":return Pt(this,e,t,s);case"ascii":case"latin1":case"binary":return Nt(this,e,t,s);case"base64":return kt(this,e,t,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Dt(this,e,t,s);default:if(m)throw new TypeError("Unknown encoding: "+p);p=(""+p).toLowerCase(),m=!0;}},o.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ft(i,e,t){return e===0&&t===i.length?r.fromByteArray(i):r.fromByteArray(i.slice(e,t))}function Ge(i,e,t){t=Math.min(i.length,t);let s=[],p=e;for(;p<t;){let d=i[p],m=null,A=d>239?4:d>223?3:d>191?2:1;if(p+A<=t){let b,w,S,B;switch(A){case 1:d<128&&(m=d);break;case 2:b=i[p+1],(b&192)===128&&(B=(d&31)<<6|b&63,B>127&&(m=B));break;case 3:b=i[p+1],w=i[p+2],(b&192)===128&&(w&192)===128&&(B=(d&15)<<12|(b&63)<<6|w&63,B>2047&&(B<55296||B>57343)&&(m=B));break;case 4:b=i[p+1],w=i[p+2],S=i[p+3],(b&192)===128&&(w&192)===128&&(S&192)===128&&(B=(d&15)<<18|(b&63)<<12|(w&63)<<6|S&63,B>65535&&B<1114112&&(m=B));}}m===null?(m=65533,A=1):m>65535&&(m-=65536,s.push(m>>>10&1023|55296),m=56320|m&1023),s.push(m),p+=A;}return vt(s)}let je=4096;function vt(i){let e=i.length;if(e<=je)return String.fromCharCode.apply(String,i);let t="",s=0;for(;s<e;)t+=String.fromCharCode.apply(String,i.slice(s,s+=je));return t}function Ut(i,e,t){let s="";t=Math.min(i.length,t);for(let p=e;p<t;++p)s+=String.fromCharCode(i[p]&127);return s}function qt(i,e,t){let s="";t=Math.min(i.length,t);for(let p=e;p<t;++p)s+=String.fromCharCode(i[p]);return s}function Ht(i,e,t){let s=i.length;(!e||e<0)&&(e=0),(!t||t<0||t>s)&&(t=s);let p="";for(let d=e;d<t;++d)p+=Wt[i[d]];return p}function Mt(i,e,t){let s=i.slice(e,t),p="";for(let d=0;d<s.length-1;d+=2)p+=String.fromCharCode(s[d]+s[d+1]*256);return p}o.prototype.slice=function(e,t){let s=this.length;e=~~e,t=t===void 0?s:~~t,e<0?(e+=s,e<0&&(e=0)):e>s&&(e=s),t<0?(t+=s,t<0&&(t=0)):t>s&&(t=s),t<e&&(t=e);let p=this.subarray(e,t);return Object.setPrototypeOf(p,o.prototype),p};function P(i,e,t){if(i%1!==0||i<0)throw new RangeError("offset is not uint");if(i+e>t)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(e,t,s){e=e>>>0,t=t>>>0,s||P(e,t,this.length);let p=this[e],d=1,m=0;for(;++m<t&&(d*=256);)p+=this[e+m]*d;return p},o.prototype.readUintBE=o.prototype.readUIntBE=function(e,t,s){e=e>>>0,t=t>>>0,s||P(e,t,this.length);let p=this[e+--t],d=1;for(;t>0&&(d*=256);)p+=this[e+--t]*d;return p},o.prototype.readUint8=o.prototype.readUInt8=function(e,t){return e=e>>>0,t||P(e,1,this.length),this[e]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||P(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||P(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||P(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readBigUInt64LE=$(function(e){e=e>>>0,J(e,"offset");let t=this[e],s=this[e+7];(t===void 0||s===void 0)&&ee(e,this.length-8);let p=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,d=this[++e]+this[++e]*2**8+this[++e]*2**16+s*2**24;return BigInt(p)+(BigInt(d)<<BigInt(32))}),o.prototype.readBigUInt64BE=$(function(e){e=e>>>0,J(e,"offset");let t=this[e],s=this[e+7];(t===void 0||s===void 0)&&ee(e,this.length-8);let p=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],d=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+s;return (BigInt(p)<<BigInt(32))+BigInt(d)}),o.prototype.readIntLE=function(e,t,s){e=e>>>0,t=t>>>0,s||P(e,t,this.length);let p=this[e],d=1,m=0;for(;++m<t&&(d*=256);)p+=this[e+m]*d;return d*=128,p>=d&&(p-=Math.pow(2,8*t)),p},o.prototype.readIntBE=function(e,t,s){e=e>>>0,t=t>>>0,s||P(e,t,this.length);let p=t,d=1,m=this[e+--p];for(;p>0&&(d*=256);)m+=this[e+--p]*d;return d*=128,m>=d&&(m-=Math.pow(2,8*t)),m},o.prototype.readInt8=function(e,t){return e=e>>>0,t||P(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},o.prototype.readInt16LE=function(e,t){e=e>>>0,t||P(e,2,this.length);let s=this[e]|this[e+1]<<8;return s&32768?s|4294901760:s},o.prototype.readInt16BE=function(e,t){e=e>>>0,t||P(e,2,this.length);let s=this[e+1]|this[e]<<8;return s&32768?s|4294901760:s},o.prototype.readInt32LE=function(e,t){return e=e>>>0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e=e>>>0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readBigInt64LE=$(function(e){e=e>>>0,J(e,"offset");let t=this[e],s=this[e+7];(t===void 0||s===void 0)&&ee(e,this.length-8);let p=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(s<<24);return (BigInt(p)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)}),o.prototype.readBigInt64BE=$(function(e){e=e>>>0,J(e,"offset");let t=this[e],s=this[e+7];(t===void 0||s===void 0)&&ee(e,this.length-8);let p=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return (BigInt(p)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+s)}),o.prototype.readFloatLE=function(e,t){return e=e>>>0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e=e>>>0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||P(e,8,this.length),n.read(this,e,!1,52,8)};function F(i,e,t,s,p,d){if(!o.isBuffer(i))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>p||e<d)throw new RangeError('"value" argument is out of bounds');if(t+s>i.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(e,t,s,p){if(e=+e,t=t>>>0,s=s>>>0,!p){let A=Math.pow(2,8*s)-1;F(this,e,t,s,A,0);}let d=1,m=0;for(this[t]=e&255;++m<s&&(d*=256);)this[t+m]=e/d&255;return t+s},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(e,t,s,p){if(e=+e,t=t>>>0,s=s>>>0,!p){let A=Math.pow(2,8*s)-1;F(this,e,t,s,A,0);}let d=s-1,m=1;for(this[t+d]=e&255;--d>=0&&(m*=256);)this[t+d]=e/m&255;return t+s},o.prototype.writeUint8=o.prototype.writeUInt8=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,1,255,0),this[t]=e&255,t+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function We(i,e,t,s,p){Qe(e,s,p,i,t,7);let d=Number(e&BigInt(4294967295));i[t++]=d,d=d>>8,i[t++]=d,d=d>>8,i[t++]=d,d=d>>8,i[t++]=d;let m=Number(e>>BigInt(32)&BigInt(4294967295));return i[t++]=m,m=m>>8,i[t++]=m,m=m>>8,i[t++]=m,m=m>>8,i[t++]=m,t}function Ye(i,e,t,s,p){Qe(e,s,p,i,t,7);let d=Number(e&BigInt(4294967295));i[t+7]=d,d=d>>8,i[t+6]=d,d=d>>8,i[t+5]=d,d=d>>8,i[t+4]=d;let m=Number(e>>BigInt(32)&BigInt(4294967295));return i[t+3]=m,m=m>>8,i[t+2]=m,m=m>>8,i[t+1]=m,m=m>>8,i[t]=m,t+8}o.prototype.writeBigUInt64LE=$(function(e,t=0){return We(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=$(function(e,t=0){return Ye(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(e,t,s,p){if(e=+e,t=t>>>0,!p){let b=Math.pow(2,8*s-1);F(this,e,t,s,b-1,-b);}let d=0,m=1,A=0;for(this[t]=e&255;++d<s&&(m*=256);)e<0&&A===0&&this[t+d-1]!==0&&(A=1),this[t+d]=(e/m>>0)-A&255;return t+s},o.prototype.writeIntBE=function(e,t,s,p){if(e=+e,t=t>>>0,!p){let b=Math.pow(2,8*s-1);F(this,e,t,s,b-1,-b);}let d=s-1,m=1,A=0;for(this[t+d]=e&255;--d>=0&&(m*=256);)e<0&&A===0&&this[t+d+1]!==0&&(A=1),this[t+d]=(e/m>>0)-A&255;return t+s},o.prototype.writeInt8=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},o.prototype.writeInt16LE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},o.prototype.writeInt32LE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},o.prototype.writeBigInt64LE=$(function(e,t=0){return We(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=$(function(e,t=0){return Ye(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Ke(i,e,t,s,p,d){if(t+s>i.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function Je(i,e,t,s,p){return e=+e,t=t>>>0,p||Ke(i,e,t,4),n.write(i,e,t,s,23,4),t+4}o.prototype.writeFloatLE=function(e,t,s){return Je(this,e,t,!0,s)},o.prototype.writeFloatBE=function(e,t,s){return Je(this,e,t,!1,s)};function Xe(i,e,t,s,p){return e=+e,t=t>>>0,p||Ke(i,e,t,8),n.write(i,e,t,s,52,8),t+8}o.prototype.writeDoubleLE=function(e,t,s){return Xe(this,e,t,!0,s)},o.prototype.writeDoubleBE=function(e,t,s){return Xe(this,e,t,!1,s)},o.prototype.copy=function(e,t,s,p){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(s||(s=0),!p&&p!==0&&(p=this.length),t>=e.length&&(t=e.length),t||(t=0),p>0&&p<s&&(p=s),p===s||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(s<0||s>=this.length)throw new RangeError("Index out of range");if(p<0)throw new RangeError("sourceEnd out of bounds");p>this.length&&(p=this.length),e.length-t<p-s&&(p=e.length-t+s);let d=p-s;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(t,s,p):Uint8Array.prototype.set.call(e,this.subarray(s,p),t),d},o.prototype.fill=function(e,t,s,p){if(typeof e=="string"){if(typeof t=="string"?(p=t,t=0,s=this.length):typeof s=="string"&&(p=s,s=this.length),p!==void 0&&typeof p!="string")throw new TypeError("encoding must be a string");if(typeof p=="string"&&!o.isEncoding(p))throw new TypeError("Unknown encoding: "+p);if(e.length===1){let m=e.charCodeAt(0);(p==="utf8"&&m<128||p==="latin1")&&(e=m);}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(t<0||this.length<t||this.length<s)throw new RangeError("Out of range index");if(s<=t)return this;t=t>>>0,s=s===void 0?this.length:s>>>0,e||(e=0);let d;if(typeof e=="number")for(d=t;d<s;++d)this[d]=e;else {let m=o.isBuffer(e)?e:o.from(e,p),A=m.length;if(A===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(d=0;d<s-t;++d)this[d+t]=m[d%A];}return this};let K={};function xe(i,e,t){K[i]=class extends t{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${i}]`,this.stack,delete this.name;}get code(){return i}set code(p){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:p,writable:!0});}toString(){return `${this.name} [${i}]: ${this.message}`}};}xe("ERR_BUFFER_OUT_OF_BOUNDS",function(i){return i?`${i} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),xe("ERR_INVALID_ARG_TYPE",function(i,e){return `The "${i}" argument must be of type number. Received type ${typeof e}`},TypeError),xe("ERR_OUT_OF_RANGE",function(i,e,t){let s=`The value of "${i}" is out of range.`,p=t;return Number.isInteger(t)&&Math.abs(t)>2**32?p=Ze(String(t)):typeof t=="bigint"&&(p=String(t),(t>BigInt(2)**BigInt(32)||t<-(BigInt(2)**BigInt(32)))&&(p=Ze(p)),p+="n"),s+=` It must be ${e}. Received ${p}`,s},RangeError);function Ze(i){let e="",t=i.length,s=i[0]==="-"?1:0;for(;t>=s+4;t-=3)e=`_${i.slice(t-3,t)}${e}`;return `${i.slice(0,t)}${e}`}function $t(i,e,t){J(e,"offset"),(i[e]===void 0||i[e+t]===void 0)&&ee(e,i.length-(t+1));}function Qe(i,e,t,s,p,d){if(i>t||i<e){let m=typeof e=="bigint"?"n":"",A;throw e===0||e===BigInt(0)?A=`>= 0${m} and < 2${m} ** ${(d+1)*8}${m}`:A=`>= -(2${m} ** ${(d+1)*8-1}${m}) and < 2 ** ${(d+1)*8-1}${m}`,new K.ERR_OUT_OF_RANGE("value",A,i)}$t(s,p,d);}function J(i,e){if(typeof i!="number")throw new K.ERR_INVALID_ARG_TYPE(e,"number",i)}function ee(i,e,t){throw Math.floor(i)!==i?(J(i,t),new K.ERR_OUT_OF_RANGE("offset","an integer",i)):e<0?new K.ERR_BUFFER_OUT_OF_BOUNDS:new K.ERR_OUT_OF_RANGE("offset",`>= ${0} and <= ${e}`,i)}let Vt=/[^+/0-9A-Za-z-_]/g;function zt(i){if(i=i.split("=")[0],i=i.trim().replace(Vt,""),i.length<2)return "";for(;i.length%4!==0;)i=i+"=";return i}function Pe(i,e){e=e||1/0;let t,s=i.length,p=null,d=[];for(let m=0;m<s;++m){if(t=i.charCodeAt(m),t>55295&&t<57344){if(!p){if(t>56319){(e-=3)>-1&&d.push(239,191,189);continue}else if(m+1===s){(e-=3)>-1&&d.push(239,191,189);continue}p=t;continue}if(t<56320){(e-=3)>-1&&d.push(239,191,189),p=t;continue}t=(p-55296<<10|t-56320)+65536;}else p&&(e-=3)>-1&&d.push(239,191,189);if(p=null,t<128){if((e-=1)<0)break;d.push(t);}else if(t<2048){if((e-=2)<0)break;d.push(t>>6|192,t&63|128);}else if(t<65536){if((e-=3)<0)break;d.push(t>>12|224,t>>6&63|128,t&63|128);}else if(t<1114112){if((e-=4)<0)break;d.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128);}else throw new Error("Invalid code point")}return d}function Gt(i){let e=[];for(let t=0;t<i.length;++t)e.push(i.charCodeAt(t)&255);return e}function jt(i,e){let t,s,p,d=[];for(let m=0;m<i.length&&!((e-=2)<0);++m)t=i.charCodeAt(m),s=t>>8,p=t%256,d.push(p),d.push(s);return d}function et(i){return r.toByteArray(zt(i))}function ue(i,e,t,s){let p;for(p=0;p<s&&!(p+t>=e.length||p>=i.length);++p)e[p+t]=i[p];return p}function M(i,e){return i instanceof e||i!=null&&i.constructor!=null&&i.constructor.name!=null&&i.constructor.name===e.name}function Ne(i){return i!==i}let Wt=function(){let i="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let s=t*16;for(let p=0;p<16;++p)e[s+p]=i[t]+i[p];}return e}();function $(i){return typeof BigInt>"u"?Yt:i}function Yt(){throw new Error("BigInt not supported")}return G}var j=Xt();j.Buffer;j.SlowBuffer;j.INSPECT_MAX_BYTES;j.kMaxLength;var T=j.Buffer;j.INSPECT_MAX_BYTES;j.kMaxLength;var re=class{constructor(n){this.config=n;}};var X=class extends Error{url;status;statusText;body;request;constructor(n,l,a){super(a),this.name="ApiError",this.url=l.url,this.status=l.status,this.statusText=l.statusText,this.body=l.body,this.request=n;}};var me=class extends Error{constructor(n){super(n),this.name="CancelError";}get isCancelled(){return !0}},ne=class{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(n){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((l,a)=>{this._resolve=l,this._reject=a;let u=h=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(h));},c=h=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(h));},o=h=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(h);};return Object.defineProperty(o,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(o,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(o,"isCancelled",{get:()=>this._isCancelled}),n(u,c,o)});}then(n,l){return this._promise.then(n,l)}catch(n){return this._promise.catch(n)}finally(n){return this._promise.finally(n)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let n of this._cancelHandlers)n();}catch(n){console.warn("Cancellation threw an error",n);return}this._cancelHandlers.length=0,this._reject?.(new me("Request aborted"));}}get isCancelled(){return this._isCancelled}};var De=r=>r!=null,he=r=>typeof r=="string",ke=r=>he(r)&&r!=="",st=r=>typeof r=="object"&&typeof r.type=="string"&&typeof r.stream=="function"&&typeof r.arrayBuffer=="function"&&typeof r.constructor=="function"&&typeof r.constructor.name=="string"&&/^(Blob|File)$/.test(r.constructor.name)&&/^(Blob|File)$/.test(r[Symbol.toStringTag]),Zt=r=>r instanceof ot,Qt=r=>r>=200&&r<300,er=r=>{try{return btoa(r)}catch{return T.from(r).toString("base64")}},tr=r=>{let n=[],l=(u,c)=>{n.push(`${encodeURIComponent(u)}=${encodeURIComponent(String(c))}`);},a=(u,c)=>{De(c)&&(Array.isArray(c)?c.forEach(o=>{a(u,o);}):typeof c=="object"?Object.entries(c).forEach(([o,h])=>{a(`${u}[${o}]`,h);}):l(u,c));};return Object.entries(r).forEach(([u,c])=>{a(u,c);}),n.length>0?`?${n.join("&")}`:""},rr=(r,n)=>{let l=r.ENCODE_PATH||encodeURI,a=n.url.replace("{api-version}",r.VERSION).replace(/{(.*?)}/g,(c,o)=>n.path?.hasOwnProperty(o)?l(String(n.path[o])):c),u=`${r.BASE}${a}`;return n.query?`${u}${tr(n.query)}`:u},nr=r=>{if(r.formData){let n=new ot,l=(a,u)=>{he(u)||st(u)?n.append(a,u):n.append(a,JSON.stringify(u));};return Object.entries(r.formData).filter(([a,u])=>De(u)).forEach(([a,u])=>{Array.isArray(u)?u.forEach(c=>l(a,c)):l(a,u);}),n}},fe=async(r,n)=>typeof n=="function"?n(r):n,ir=async(r,n,l)=>{let a=await fe(n,r.TOKEN),u=await fe(n,r.USERNAME),c=await fe(n,r.PASSWORD),o=await fe(n,r.HEADERS),h=typeof l?.getHeaders=="function"&&l?.getHeaders()||{},E=Object.entries({Accept:"application/json",...o,...n.headers,...h}).filter(([f,y])=>De(y)).reduce((f,[y,R])=>({...f,[y]:String(R)}),{});if(ke(a)&&(E.Authorization=`Bearer ${a}`),ke(u)&&ke(c)){let f=er(`${u}:${c}`);E.Authorization=`Basic ${f}`;}return n.body&&(n.mediaType?E["Content-Type"]=n.mediaType:st(n.body)?E["Content-Type"]=n.body.type||"application/octet-stream":he(n.body)?E["Content-Type"]="text/plain":Zt(n.body)||(E["Content-Type"]="application/json")),E},or=r=>{if(r.body)return r.body},sr=async(r,n,l,a,u,c,o)=>{let h=it.CancelToken.source(),E={url:l,headers:c,data:a??u,method:n.method,withCredentials:r.WITH_CREDENTIALS,cancelToken:h.token};o(()=>h.cancel("The user aborted a request."));try{return await it.request(E)}catch(f){let y=f;if(y.response)return y.response;throw f}},ar=(r,n)=>{if(n){let l=r.headers[n];if(he(l))return l}},lr=r=>{if(r.status!==204)return r.data},pr=(r,n)=>{let a={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...r.errors}[n.status];if(a)throw new X(r,n,a);if(!n.ok)throw new X(r,n,"Generic Error")},at=(r,n)=>new ne(async(l,a,u)=>{try{let c=rr(r,n),o=nr(n),h=or(n),E=await ir(r,n,o);if(!u.isCancelled){let f=await sr(r,n,c,h,o,E,u),y=lr(f),R=ar(f,n.responseHeader),g={url:c,ok:Qt(f.status),status:f.status,statusText:f.statusText,body:R??y};pr(n,g),l(g.body);}}catch(c){a(c);}});var ye=class extends re{constructor(n){super(n);}request(n){return at(this.config,n)}};var ie=class{constructor(n){this.httpRequest=n;}cancelOrders({chainName:n,requestBody:l}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:n},body:l,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:n,status:l,sellItemContractAddress:a,buyItemType:u,buyItemContractAddress:c,accountAddress:o,sellItemMetadataId:h,sellItemTokenId:E,fromUpdatedAt:f,pageSize:y,sortBy:R,sortDirection:g,pageCursor:C}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:n},query:{status:l,sell_item_contract_address:a,buy_item_type:u,buy_item_contract_address:c,account_address:o,sell_item_metadata_id:h,sell_item_token_id:E,from_updated_at:f,page_size:y,sort_by:R,sort_direction:g,page_cursor:C},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:n,requestBody:l}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:n},body:l,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listBids({chainName:n,status:l,buyItemContractAddress:a,sellItemContractAddress:u,accountAddress:c,buyItemMetadataId:o,buyItemTokenId:h,fromUpdatedAt:E,pageSize:f,sortBy:y,sortDirection:R,pageCursor:g}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:n},query:{status:l,buy_item_contract_address:a,sell_item_contract_address:u,account_address:c,buy_item_metadata_id:o,buy_item_token_id:h,from_updated_at:E,page_size:f,sort_by:y,sort_direction:R,page_cursor:g},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createBid({chainName:n,requestBody:l}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:n},body:l,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:n,status:l,buyItemContractAddress:a,sellItemContractAddress:u,accountAddress:c,fromUpdatedAt:o,pageSize:h,sortBy:E,sortDirection:f,pageCursor:y}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:n},query:{status:l,buy_item_contract_address:a,sell_item_contract_address:u,account_address:c,from_updated_at:o,page_size:h,sort_by:E,sort_direction:f,page_cursor:y},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createCollectionBid({chainName:n,requestBody:l}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:n},body:l,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:n,listingId:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:n,listing_id:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getBid({chainName:n,bidId:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids/{bid_id}",path:{chain_name:n,bid_id:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getCollectionBid({chainName:n,collectionBidId:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids/{collection_bid_id}",path:{chain_name:n,collection_bid_id:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:n,requestBody:l}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:n},body:l,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:n,accountAddress:l,sellItemContractAddress:a,fromIndexedAt:u,pageSize:c,sortBy:o,sortDirection:h,pageCursor:E}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:n},query:{account_address:l,sell_item_contract_address:a,from_indexed_at:u,page_size:c,sort_by:o,sort_direction:h,page_cursor:E},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:n,tradeId:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:n,trade_id:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}};var oe=class{orders;request;constructor(n,l=ye){this.request=new l({BASE:n?.BASE??"https://api.immutable.com",VERSION:n?.VERSION??"1.0.0",WITH_CREDENTIALS:n?.WITH_CREDENTIALS??!1,CREDENTIALS:n?.CREDENTIALS??"include",TOKEN:n?.TOKEN,USERNAME:n?.USERNAME,PASSWORD:n?.PASSWORD,HEADERS:n?.HEADERS,ENCODE_PATH:n?.ENCODE_PATH}),this.orders=new ie(this.request);}};var lt;(n=>{(c=>(c.ON_CHAIN="ON_CHAIN",c.OFF_CHAIN="OFF_CHAIN",c.UNDERFUNDED="UNDERFUNDED"))(n.cancellation_type||={});})(lt||={});var pt;(n=>{(a=>a.FILLED="FILLED")(n.reason_code||={});})(pt||={});var v;(n=>{(o=>(o.ROYALTY="ROYALTY",o.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",o.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",o.PROTOCOL="PROTOCOL"))(n.type||={});})(v||={});var H;(n=>{(c=>(c.LISTING="LISTING",c.BID="BID",c.COLLECTION_BID="COLLECTION_BID"))(n.type||={});})(H||={});var Ce=(o=>(o.PENDING="PENDING",o.ACTIVE="ACTIVE",o.INACTIVE="INACTIVE",o.FILLED="FILLED",o.EXPIRED="EXPIRED",o.CANCELLED="CANCELLED",o))(Ce||{});var V;(n=>{(u=>(u.FULL_RESTRICTED="FULL_RESTRICTED",u.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(n.order_type||={});})(V||={});function U(r){throw new Error("Unreachable")}function W(r){if(r.type!==H.type.LISTING)throw new Error("Order type must be LISTING");let n=r.sell.map(a=>{if(a.type==="ERC721")return {type:"ERC721",contractAddress:a.contract_address,tokenId:a.token_id};if(a.type==="ERC1155")return {type:"ERC1155",contractAddress:a.contract_address,tokenId:a.token_id,amount:a.amount};throw new Error("Listing sell items must either ERC721 or ERC1155")}),l=r.buy.map(a=>{if(a.type==="NATIVE")return {type:"NATIVE",amount:a.amount};if(a.type==="ERC20")return {type:"ERC20",contractAddress:a.contract_address,amount:a.amount};throw new Error("Listing buy items must be either NATIVE or ERC20")});return {id:r.id,type:r.type,chain:r.chain,accountAddress:r.account_address,sell:n,buy:l,fees:r.fees.map(a=>({amount:a.amount,recipientAddress:a.recipient_address,type:a.type})),status:r.status,fillStatus:r.fill_status,startAt:r.start_at,endAt:r.end_at,salt:r.salt,signature:r.signature,orderHash:r.order_hash,protocolData:{orderType:r.protocol_data.order_type,counter:r.protocol_data.counter,seaportAddress:r.protocol_data.seaport_address,seaportVersion:r.protocol_data.seaport_version,zoneAddress:r.protocol_data.zone_address},createdAt:r.created_at,updatedAt:r.updated_at}}function se(r){if(r.type!==H.type.BID)throw new Error("Order type must be BID");let n=r.sell.map(a=>{if(a.type==="ERC20")return {type:"ERC20",contractAddress:a.contract_address,amount:a.amount};throw new Error("Bid sell items must be ERC20")}),l=r.buy.map(a=>{if(a.type==="ERC721")return {type:"ERC721",contractAddress:a.contract_address,tokenId:a.token_id};if(a.type==="ERC1155")return {type:"ERC1155",contractAddress:a.contract_address,tokenId:a.token_id,amount:a.amount};throw new Error("Bid buy items must either ERC721 or ERC1155")});return {id:r.id,type:r.type,chain:r.chain,accountAddress:r.account_address,sell:n,buy:l,fees:r.fees.map(a=>({amount:a.amount,recipientAddress:a.recipient_address,type:a.type})),status:r.status,fillStatus:r.fill_status,startAt:r.start_at,endAt:r.end_at,salt:r.salt,signature:r.signature,orderHash:r.order_hash,protocolData:{orderType:r.protocol_data.order_type,counter:r.protocol_data.counter,seaportAddress:r.protocol_data.seaport_address,seaportVersion:r.protocol_data.seaport_version,zoneAddress:r.protocol_data.zone_address},createdAt:r.created_at,updatedAt:r.updated_at}}function ae(r){if(r.type!==H.type.COLLECTION_BID)throw new Error("Order type must be COLLECTION_BID");let n=r.sell.map(a=>{if(a.type==="ERC20")return {type:"ERC20",contractAddress:a.contract_address,amount:a.amount};throw new Error("Collection bid sell items must be ERC20")}),l=r.buy.map(a=>{if(a.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:a.contract_address,amount:a.amount};if(a.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:a.contract_address,amount:a.amount};throw new Error("Collection bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:r.id,type:r.type,chain:r.chain,accountAddress:r.account_address,sell:n,buy:l,fees:r.fees.map(a=>({amount:a.amount,recipientAddress:a.recipient_address,type:a.type})),status:r.status,fillStatus:r.fill_status,startAt:r.start_at,endAt:r.end_at,salt:r.salt,signature:r.signature,orderHash:r.order_hash,protocolData:{orderType:r.protocol_data.order_type,counter:r.protocol_data.counter,seaportAddress:r.protocol_data.seaport_address,seaportVersion:r.protocol_data.seaport_version,zoneAddress:r.protocol_data.zone_address},createdAt:r.created_at,updatedAt:r.updated_at}}function le(r){switch(r.type){case H.type.LISTING:return W(r);case H.type.BID:return se(r);case H.type.COLLECTION_BID:return ae(r);default:return U(r.type)}}function Fe(r){let n=r.buy.map(a=>{if(a.type==="NATIVE")return {type:"NATIVE",amount:a.amount};if(a.type==="ERC20")return {type:"ERC20",contractAddress:a.contract_address,amount:a.amount};if(a.type==="ERC721")return {type:"ERC721",contractAddress:a.contract_address,tokenId:a.token_id};if(a.type==="ERC1155")return {type:"ERC1155",contractAddress:a.contract_address,tokenId:a.token_id,amount:a.amount};throw new Error("Buy items must be NATIVE, ERC20, ERC721 or ERC1155")}),l=r.sell.map(a=>{if(a.type==="ERC20")return {type:"ERC20",contractAddress:a.contract_address,amount:a.amount};if(a.type==="ERC721")return {type:"ERC721",contractAddress:a.contract_address,tokenId:a.token_id};if(a.type==="ERC1155")return {type:"ERC1155",contractAddress:a.contract_address,tokenId:a.token_id,amount:a.amount};throw new Error("Sell items must be ERC20, ERC721 or ERC1155")});return {id:r.id,orderId:r.order_id,buy:n,sell:l,buyerFees:r.buyer_fees.map(a=>({amount:a.amount,recipientAddress:a.recipient_address,type:a.type})),fees:r.fees.map(a=>({amount:a.amount,recipientAddress:a.recipient_address,type:a.type})),chain:r.chain,indexedAt:r.indexed_at,blockchainMetadata:{blockNumber:r.blockchain_metadata.block_number,logIndex:r.blockchain_metadata.log_index,transactionHash:r.blockchain_metadata.transaction_hash,transactionIndex:r.blockchain_metadata.transaction_index},buyerAddress:r.buyer_address,makerAddress:r.maker_address,sellerAddress:r.seller_address,takerAddress:r.taker_address}}function pe(r){return {nextCursor:r.next_cursor,previousCursor:r.previous_cursor}}var cr=(u=>(u[u.MAKER_ECOSYSTEM=v.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",u[u.TAKER_ECOSYSTEM=v.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",u[u.PROTOCOL=v.type.PROTOCOL]="PROTOCOL",u[u.ROYALTY=v.type.ROYALTY]="ROYALTY",u))(cr||{}),ve=(l=>(l.TRANSACTION="TRANSACTION",l.SIGNABLE="SIGNABLE",l))(ve||{}),ct=(a=>(a.APPROVAL="APPROVAL",a.FULFILL_ORDER="FULFILL_ORDER",a.CANCEL="CANCEL",a))(ct||{}),Ue=(a=>(a.CREATE_LISTING="CREATE_ORDER",a.CREATE_ORDER="CREATE_ORDER",a.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",a))(Ue||{});var qe="ImmutableSeaport",Y="1.5",Ee={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 ur={integer:0,address:zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},He=r=>r===void 0?!1:r!=null&&(["string","number"].includes(typeof r)&&BigInt(r)===0n||Array.isArray(r)&&r.every(He)||typeof r=="object"&&Object.values(r).every(He)||typeof r=="boolean"&&r===!1);function dr(r){let[,n]=r.match(/^bytes(\d+)$/)??[];return n?zeroPadValue("0x",parseInt(n)):(r.match(/^(u?)int(\d*)$/)&&(r="integer"),ur[r])}var Z=class r{constructor(n){this.types=n;for(let l in n){let a=this.getDefaultValue(l);if(this.defaultValues[l]=a,!He(a))throw new Error(`Got non-empty value for type ${l} in default generator: ${a}`)}}defaultValues={};static from(n,l){let{defaultValues:a}=new r(n);return l?a[l]:a}getDefaultValue(n){if(this.defaultValues[n])return this.defaultValues[n];let l=dr(n);if(l!==void 0)return l;let a=n.match(/^(.*)(\x5b(\d*)\x5d)$/);if(a){let c=a[1],o=parseInt(a[3]);if(o>0){let h=this.getDefaultValue(c);return Array(o).fill(h)}return []}let u=this.types[n];if(u)return u.reduce((c,{name:o,type:h})=>({...c,[o]:this.getDefaultValue(h)}),{});throw new Error(`unknown type: ${n}`)}};var yr=(r,n)=>Array(r).fill(0).map((l,a)=>n(a)),Me=(r,n)=>yr(Math.ceil(r.length/n),l=>r.slice(l*n,(l+1)*n)),dt=r=>toBeHex(r.toString("hex")),Q=r=>T.from(r.slice(2),"hex"),ge=r=>Q(keccak256(r)),Cr=r=>ge(concat(r)),ce=(r,n,l)=>(n>r.length&&r.push(...Array(n-r.length).fill(l)),r),mt=(r,n=!0)=>{if(r.length===0)throw new Error("empty tree");let a=[r.map(u=>{let c=T.isBuffer(u)?u:Q(u);return n?ge(c):c})];for(;a[a.length-1].length>1;)a.push(Er(a[a.length-1]));return a[a.length-1][0]},Er=r=>Me(r,2).map(Cr);var Ar=(r,n)=>new MerkleTree(r.map(Q),ge,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:Q(n)}),Or=(r,n,l=`0x${"ff".repeat(64)}`)=>concat([l,`0x${r.toString(16).padStart(6,"0")}`,AbiCoder.defaultAbiCoder().encode([`uint256[${n.length}]`],[n])]),Re=class{constructor(n,l,a,u,c){this.types=n;this.rootType=l;this.leafType=a;this.elements=u;this.depth=c;let o=TypedDataEncoder.from(n);this.encoder=o,this.leafHasher=h=>o.hashStruct(a,h),this.defaultNode=Z.from(n,a),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=Ar(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:n}=this;return ce([...n],this.completedSize,this.defaultNode)}getCompleteLeaves(){let n=this.elements.map(this.leafHasher);return ce([...n],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(n){let a=this.getCompleteLeaves()[n],u=this.tree.getHexProof(a,n),c=this.tree.getHexRoot();return {leaf:a,proof:u,root:c}}getEncodedProofAndSignature(n,l){let{proof:a}=this.getProof(n);return Or(n,a,l)}getDataToSign(){let n=this.getCompleteElements();for(;n.length>2;)n=Me(n,2);return n}add(n){this.elements.push(n);}getBulkOrderHash(){let n=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),l=this.getCompleteLeaves().map(Q),a=dt(mt(l,!1)),u=keccak256(toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(keccak256(concat([u,a]))!==n)throw new Error("expected derived bulk order hash to match");return n}};function _r(r){return {...Ee,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(r)}`}]}}function Br(r){return Math.max(Math.ceil(Math.log2(r)),1)}function yt(r,n=0,l=Br(r.length+n)){let a=_r(l),u=Z.from(a,"OrderComponents"),c=[...r];return n>0&&(c=[...ce([],n,u),...r]),new Re(a,"BulkOrder","OrderComponents",c,l)}function gt(r){if([0,1,2,3].includes(Number(r)))return Number(r);throw new Error(`Unknown order type ${r}`)}function Ie(r){if([0,1,2,3,4,5].includes(Number(r)))return Number(r);throw new Error(`Unknown item type ${r}`)}function Rt(r){let l=JSON.parse(r).message;return {...l,orderType:gt(l.orderType),salt:toBeHex(BigInt(l.salt)),offer:l.offer.map(a=>({...a,itemType:Ie(a.itemType)})),consideration:l.consideration.map(a=>({...a,itemType:Ie(a.itemType)}))}}function It(r){let n=JSON.parse(r);return {components:n.message.tree.flat(1/0).filter(a=>a.offerer!=="0x0000000000000000000000000000000000000000").map(a=>({...a,orderType:gt(a.orderType),salt:toBeHex(BigInt(a.salt)),offer:a.offer.map(u=>({...u,itemType:Ie(u.itemType)})),consideration:a.consideration.map(u=>({...u,itemType:Ie(u.itemType)}))})),types:n.types,value:n.message}}function Tt(r,n){let l=yt(n);return n.map((a,u)=>l.getEncodedProofAndSignature(u,r))}function br(r){switch(r.type){case"NATIVE":throw new Error("NATIVE items are not supported in the offer");case"ERC20":return {itemType:1,token:r.contract_address,identifierOrCriteria:"0",startAmount:r.amount,endAmount:r.amount};case"ERC721":return {itemType:2,token:r.contract_address,identifierOrCriteria:r.token_id,startAmount:"1",endAmount:"1"};case"ERC1155":return {itemType:3,token:r.contract_address,identifierOrCriteria:r.token_id,startAmount:r.amount,endAmount:r.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 U()}}function Sr(r,n){switch(r.type){case"NATIVE":return {itemType:0,startAmount:r.amount,endAmount:r.amount,token:ZeroAddress,identifierOrCriteria:"0",recipient:n};case"ERC20":return {itemType:1,startAmount:r.amount,endAmount:r.amount,token:r.contract_address,identifierOrCriteria:"0",recipient:n};case"ERC721":return {itemType:2,startAmount:"1",endAmount:"1",token:r.contract_address,identifierOrCriteria:r.token_id,recipient:n};case"ERC1155":return {itemType:3,startAmount:r.amount,endAmount:r.amount,token:r.contract_address,identifierOrCriteria:r.token_id,recipient:n};case"ERC721_COLLECTION":return {itemType:4,startAmount:r.amount,endAmount:r.amount,token:r.contract_address,identifierOrCriteria:"0",recipient:n};case"ERC1155_COLLECTION":return {itemType:5,startAmount:r.amount,endAmount:r.amount,token:r.contract_address,identifierOrCriteria:"0",recipient:n};default:return U()}}function Ae(r){let n=r.sell.map(br),l=r.buy.map(o=>Sr(o,r.account_address)),a=function(o){switch(o){case H.type.LISTING:return l[0];case H.type.BID:case H.type.COLLECTION_BID:return n[0];default:return U()}}(r.type),u=function(o){switch(o){case V.order_type.FULL_RESTRICTED:return 2;case V.order_type.PARTIAL_RESTRICTED:return 3;default:return U()}}(r.protocol_data.order_type),c=r.fees.map(o=>({amount:o.amount,itemType:a.itemType,recipient:o.recipient_address,token:a.token,identifierOrCriteria:a.identifierOrCriteria}));return {orderComponents:{offerer:r.account_address,zone:r.protocol_data.zone_address,offer:n,consideration:l,orderType:u,startTime:Math.round(new Date(r.start_at).getTime()/1e3).toString(),endTime:Math.round(new Date(r.end_at).getTime()/1e3).toString(),zoneHash:ZeroHash,salt:r.salt,conduitKey:ZeroHash,counter:r.protocol_data.counter,totalOriginalConsiderationItems:l.length},tips:c}}function z(r,n,l){return async()=>{let a=await r.buildTransaction(),u={to:a.to,from:l,type:a.type,maxFeePerGas:a.maxFeePerGas?BigInt(a.maxFeePerGas):void 0,maxPriorityFeePerGas:a.maxPriorityFeePerGas?BigInt(a.maxPriorityFeePerGas):void 0,value:a.value?BigInt(a.value):void 0,data:a.data,nonce:a.nonce,chainId:n};return u.gasLimit=BigInt(await r.estimateGas()),u.gasLimit+=u.gasLimit/BigInt(5),u}}function Ot(r){switch(r.type){case"ERC20":return {token:r.contractAddress,amount:r.amount};case"ERC721":return {itemType:2,token:r.contractAddress,identifier:r.tokenId};case"ERC1155":return {itemType:3,token:r.contractAddress,identifier:r.tokenId,amount:r.amount};default:return U()}}function _t(r,n){switch(r.type){case"NATIVE":return {amount:r.amount,recipient:n};case"ERC20":return {token:r.contractAddress,amount:r.amount,recipient:n};case"ERC721":return {itemType:2,token:r.contractAddress,identifier:r.tokenId,recipient:n};case"ERC1155":return {itemType:3,token:r.contractAddress,identifier:r.tokenId,amount:r.amount,recipient:n};case"ERC721_COLLECTION":return {itemType:2,token:r.contractAddress,amount:r.amount,identifiers:[],recipient:n};case"ERC1155_COLLECTION":return {itemType:3,token:r.contractAddress,amount:r.amount,identifiers:[],recipient:n};default:return U()}}var Oe=class r{constructor(n,l,a,u,c){this.seaportLibFactory=n;this.provider=l;this.seaportContractAddress=a;this.zoneContractAddress=u;this.rateLimitingKey=c;}async prepareBulkSeaportOrders(n,l){let{actions:a}=await this.createSeaportOrders(n,l),u=a.filter(g=>g.type==="approval"),c=await this.provider.getNetwork(),o=u.map(g=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:z(g.transactionMethods,c.chainId,n)})),h=a.find(g=>g.type==="createBulk");if(!h)throw new Error("No create bulk order action found");let E=await h.getMessageToSign(),{components:f,types:y,value:R}=It(E);return o.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(y,R)}),{actions:o,preparedOrders:f.map(g=>({orderComponents:g,orderHash:this.getSeaportLib().getOrderHash(g)}))}}async prepareSeaportOrder(n,l,a,u,c,o){let{actions:h}=await this.createSeaportOrder(n,l,a,u,c,o),E=[],f=h.find(C=>C.type==="approval");f&&E.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:z(f.transactionMethods,(await this.provider.getNetwork()).chainId,n)});let y=h.find(C=>C.type==="create");if(!y)throw new Error("No create order action found");let R=await y.getMessageToSign(),g=Rt(R);return E.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromOrderComponents(g)}),{actions:E,orderComponents:g,orderHash:this.getSeaportLib().getOrderHash(g)}}async fulfillOrder(n,l,a,u,c){let{orderComponents:o,tips:h}=Ae(n),E=this.getSeaportLib(n),f=(await this.provider.getNetwork()).chainId,y={order:{parameters:o,signature:n.signature},unitsToFill:u,extraData:a,tips:h};c&&(y.considerationCriteria=c);let{actions:R}=await E.fulfillOrders({accountAddress:l,fulfillOrderDetails:[y]}),g=[],C=R.filter(_=>_.type==="approval");C.length>0&&C.forEach(_=>{g.push({type:"TRANSACTION",buildTransaction:z(_.transactionMethods,f,l),purpose:"APPROVAL"});});let I=R.find(_=>_.type==="exchange");if(!I)throw new Error("No exchange action found");return g.push({type:"TRANSACTION",buildTransaction:z(I.transactionMethods,f,l),purpose:"FULFILL_ORDER"}),{actions:g,expiration:r.getExpirationISOTimeFromExtraData(a),order:le(n)}}async fulfillBulkOrders(n,l){let a=n.map(f=>{let{orderComponents:y,tips:R}=Ae(f.order),g={order:{parameters:y,signature:f.order.signature},unitsToFill:f.unitsToFill,extraData:f.extraData,tips:R};return f.considerationCriteria&&f.considerationCriteria.length>0&&(g.considerationCriteria=f.considerationCriteria),g}),{actions:u}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:a,accountAddress:l}),c=[],o=u.filter(f=>f.type==="approval"),h=(await this.provider.getNetwork()).chainId;o.length>0&&o.forEach(f=>{c.push({type:"TRANSACTION",buildTransaction:z(f.transactionMethods,h,l),purpose:"APPROVAL"});});let E=u.find(f=>f.type==="exchange");if(!E)throw new Error("No exchange action found");return c.push({type:"TRANSACTION",buildTransaction:z(E.transactionMethods,(await this.provider.getNetwork()).chainId,l),purpose:"FULFILL_ORDER"}),{actions:c,expiration:a.map(f=>r.getExpirationISOTimeFromExtraData(f.extraData)).reduce((f,y)=>new Date(f)<new Date(y)?f:y)}}async cancelOrders(n,l){let a=n.map(o=>Ae(o).orderComponents),c=await this.getSeaportLib(n[0]).cancelOrders(a,l);return {type:"TRANSACTION",buildTransaction:z(c,(await this.provider.getNetwork()).chainId,l),purpose:"CANCEL"}}createSeaportOrders(n,l){return this.getSeaportLib().createBulkOrders(l.map(u=>{let{offerItem:c,considerationItem:o,allowPartialFills:h,orderStart:E,orderExpiry:f}=u;return {allowPartialFills:h,offer:[Ot(c)],consideration:[_t(o,n)],startTime:(E.getTime()/1e3).toFixed(0),endTime:(f.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),n)}createSeaportOrder(n,l,a,u,c,o){return this.getSeaportLib().createOrder({allowPartialFills:u,offer:[Ot(l)],consideration:[_t(a,n)],startTime:(c.getTime()/1e3).toFixed(0),endTime:(o.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},n)}async getTypedDataFromBulkOrderComponents(n,l){delete n.EIP712Domain;let{chainId:a}=await this.provider.getNetwork();return {domain:{name:qe,version:Y,chainId:a,verifyingContract:this.seaportContractAddress},types:n,value:l}}async getTypedDataFromOrderComponents(n){let{chainId:l}=await this.provider.getNetwork();return {domain:{name:qe,version:Y,chainId:l,verifyingContract:this.seaportContractAddress},types:Ee,value:n}}getSeaportLib(n){let l=n?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(l)}static getExpirationISOTimeFromExtraData(n){let l=n.slice(44,60),a=parseInt(l,16);return new Date(a*1e3).toISOString()}};function _e(r){switch(r.itemType){case 0:return {type:"NATIVE",amount:r.startAmount};case 1:return {type:"ERC20",contract_address:r.token,amount:r.startAmount};case 2:return {type:"ERC721",contract_address:r.token,token_id:r.identifierOrCriteria};case 3:return {type:"ERC1155",contract_address:r.token,token_id:r.identifierOrCriteria,amount:r.startAmount};case 4:return {type:"ERC721_COLLECTION",contract_address:r.token,amount:r.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:r.token,amount:r.startAmount};default:return U(r.itemType)}}function $e(r){if(r.itemType!==1)throw new Error(`Expected ERC20 item, got ${r.itemType}`);return {type:"ERC20",contract_address:r.token,amount:r.startAmount}}function Bt(r){switch(r.itemType){case 4:return {type:"ERC721_COLLECTION",contract_address:r.token,amount:r.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:r.token,amount:r.startAmount};case 1:case 0:case 2:case 3:throw new Error(`Unsupported item type ${r.itemType}`);default:return U(r.itemType)}}function Be(r){switch(r){case 2:return V.order_type.FULL_RESTRICTED;case 3:return V.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${r}`);default:return U()}}var we=class{constructor(n,l,a){this.orderbookService=n;this.chainName=l;this.seaportAddress=a;}async fulfillmentData(n){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:n})}async getListing(n){return this.orderbookService.getListing({chainName:this.chainName,listingId:n})}async getBid(n){return this.orderbookService.getBid({chainName:this.chainName,bidId:n})}async getCollectionBid(n){return this.orderbookService.getCollectionBid({chainName:this.chainName,collectionBidId:n})}async getTrade(n){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:n})}async listListings(n){return this.orderbookService.listListings({chainName:this.chainName,...n})}async listBids(n){return this.orderbookService.listBids({chainName:this.chainName,...n})}async listCollectionBids(n){return this.orderbookService.listCollectionBids({chainName:this.chainName,...n})}async listTrades(n){return this.orderbookService.listTrades({chainName:this.chainName,...n})}async cancelOrders(n,l,a){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:l,orders:n,signature:a}})}async createListing({orderHash:n,orderComponents:l,orderSignature:a,makerFees:u}){if(l.offer.length!==1)throw new Error("Only one item can be listed for a listing");if(l.consideration.length!==1)throw new Error("Only one item can be used as currency for a listing");if(![2,3].includes(l.offer[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be listed");if(![0,1].includes(l.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:l.offerer,buy:l.consideration.map(_e),fees:u.map(c=>({type:v.type.MAKER_ECOSYSTEM,amount:c.amount,recipient_address:c.recipientAddress})),end_at:new Date(parseInt(`${l.endTime.toString()}000`,10)).toISOString(),order_hash:n,protocol_data:{order_type:Be(l.orderType),zone_address:l.zone,seaport_address:this.seaportAddress,seaport_version:Y,counter:l.counter.toString()},salt:l.salt,sell:l.offer.map(_e),signature:a,start_at:new Date(parseInt(`${l.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:n,orderComponents:l,orderSignature:a,makerFees:u}){if(l.offer.length!==1)throw new Error("Only one item can be listed for a bid");if(l.consideration.length!==1)throw new Error("Only one item can be used as currency for a bid");if(1!==l.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a bid");if(![2,3].includes(l.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be bid against");return this.orderbookService.createBid({chainName:this.chainName,requestBody:{account_address:l.offerer,buy:l.consideration.map(_e),fees:u.map(c=>({type:v.type.MAKER_ECOSYSTEM,amount:c.amount,recipient_address:c.recipientAddress})),end_at:new Date(parseInt(`${l.endTime.toString()}000`,10)).toISOString(),order_hash:n,protocol_data:{order_type:Be(l.orderType),zone_address:l.zone,seaport_address:this.seaportAddress,seaport_version:Y,counter:l.counter.toString()},salt:l.salt,sell:l.offer.map($e),signature:a,start_at:new Date(parseInt(`${l.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:n,orderComponents:l,orderSignature:a,makerFees:u}){if(l.offer.length!==1)throw new Error("Only one item can be listed for a collection bid");if(l.consideration.length!==1)throw new Error("Only one item can be used as currency for a collection bid");if(1!==l.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a collection bid");if(![4,5].includes(l.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:l.offerer,buy:l.consideration.map(Bt),fees:u.map(c=>({type:v.type.MAKER_ECOSYSTEM,amount:c.amount,recipient_address:c.recipientAddress})),end_at:new Date(parseInt(`${l.endTime.toString()}000`,10)).toISOString(),order_hash:n,protocol_data:{order_type:Be(l.orderType),zone_address:l.zone,seaport_address:this.seaportAddress,seaport_version:Y,counter:l.counter.toString()},salt:l.salt,sell:l.offer.map($e),signature:a,start_at:new Date(parseInt(`${l.startTime.toString()}000`,10)).toISOString()}})}};var be=class{constructor(n,l,a,u){this.chainName=l;this.seaportAddress=a;this.orderbookClient=new oe({BASE:n,HEADERS:u?{"x-api-key":u}:void 0});}orderbookClient;create(){return new we(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var Pr="imtbl-zkevm-testnet",Nr="imtbl-zkevm-mainnet";function Se(r,n){let l=new FetchRequest(r);return n&&l.setHeader("x-api-key",n),new JsonRpcProvider(l)}function bt(r){switch(r.baseConfig.environment){case Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:Pr,provider:Se("https://rpc.testnet.immutable.com",r.baseConfig.rateLimitingKey)};case Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:Nr,provider:Se("https://rpc.immutable.com",r.baseConfig.rateLimitingKey)};default:return null}}var Le=class{constructor(n,l){this.defaultSeaportContractAddress=n;this.provider=l;}create(n){let l=n??this.defaultSeaportContractAddress,a=this.provider;return a.getSigner=async function(c){c==null&&(c=0);let o=this.send("eth_accounts",[]);if(typeof c=="number"){let h=await o;if(c>=h.length)throw new Error("no such account");return new JsonRpcSigner(this,h[c])}return new JsonRpcSigner(this,c)},new Seaport(a,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:l}})}};var Ve=class r{apiClient;seaport;orderbookConfig;constructor(n){let a={...bt(n),...n.overrides};if(n.overrides?.jsonRpcProviderUrl&&(a.provider=Se(n.overrides?.jsonRpcProviderUrl,n.baseConfig.rateLimitingKey)),!a)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=a;let{apiEndpoint:u,chainName:c}=this.orderbookConfig;if(!u)throw new Error("API endpoint must be provided");this.apiClient=new be(u,c,this.orderbookConfig.seaportContractAddress,n.baseConfig.rateLimitingKey).create();let o=new Le(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new Oe(o,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,n.baseConfig.rateLimitingKey);}static defaultOrderExpiry(){return new Date(Date.now()+1e3*60*60*24*365*2)}config(){return this.orderbookConfig}async getListing(n){let l=await this.apiClient.getListing(n);return {result:W(l.result)}}async getBid(n){let l=await this.apiClient.getBid(n);return {result:se(l.result)}}async getCollectionBid(n){let l=await this.apiClient.getCollectionBid(n);return {result:ae(l.result)}}async getTrade(n){let l=await this.apiClient.getTrade(n);return {result:Fe(l.result)}}async listListings(n){let l=await this.apiClient.listListings(n);return {page:pe(l.page),result:l.result.map(W)}}async listBids(n){let l=await this.apiClient.listBids(n);return {page:pe(l.page),result:l.result.map(se)}}async listCollectionBids(n){let l=await this.apiClient.listCollectionBids(n);return {page:pe(l.page),result:l.result.map(ae)}}async listTrades(n){let l=await this.apiClient.listTrades(n);return {page:pe(l.page),result:l.result.map(Fe)}}async prepareBulkListings({makerAddress:n,listingParams:l}){if(l.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(l.length===1){let o=await this.seaport.prepareSeaportOrder(n,l[0].sell,l[0].buy,l[0].sell.type==="ERC1155",l[0].orderStart||new Date,l[0].orderExpiry||r.defaultOrderExpiry());return {actions:o.actions,completeListings:async h=>{let E=await this.createListing({makerFees:l[0].makerFees,orderComponents:o.orderComponents,orderHash:o.orderHash,orderSignature:typeof h=="string"?h:h[0]});return {result:[{success:!0,orderHash:o.orderHash,order:E.result}]}}}}if(await this.orderbookConfig.provider.getCode(n)!=="0x"){track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:n,listingsCount:l.length});let o=await Promise.all(l.map(f=>this.seaport.prepareSeaportOrder(n,f.sell,f.buy,f.sell.type==="ERC1155",f.orderStart||new Date,f.orderExpiry||r.defaultOrderExpiry()))),h=[];return {actions:o.flatMap(f=>{let y=[];return f.actions.forEach(R=>{if(R.type==="TRANSACTION"){let g=f.orderComponents.offer[0].token;h.includes(g)||(h.push(g),y.push(R));}else y.push(R);}),y}),completeListings:async f=>{if(typeof f=="string")throw new Error("A signature per listing must be provided for smart contract wallets");return {result:(await Promise.all(o.map((g,C)=>{let I=f[C];return this.apiClient.createListing({makerFees:l[C].makerFees,orderComponents:g.orderComponents,orderHash:g.orderHash,orderSignature:I}).catch(()=>{})}))).map((g,C)=>({success:!!g,orderHash:o[C].orderHash,order:g?W(g.result):void 0}))}}}}track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:n,listingsCount:l.length});let{actions:u,preparedOrders:c}=await this.seaport.prepareBulkSeaportOrders(n,l.map(o=>({offerItem:o.sell,considerationItem:o.buy,allowPartialFills:o.sell.type==="ERC1155",orderStart:o.orderStart||new Date,orderExpiry:o.orderExpiry||r.defaultOrderExpiry()})));return {actions:u,completeListings:async o=>{let h=typeof o=="object";if(h&&o.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let E=c.map(g=>g.orderComponents),f=h?o[0]:o,y=Tt(f,E);return {result:(await Promise.all(E.map((g,C)=>{let I=y[C],_=c[C],L=l[C];return this.apiClient.createListing({orderComponents:g,orderHash:_.orderHash,orderSignature:I,makerFees:L.makerFees}).catch(()=>{})}))).map((g,C)=>({success:!!g,orderHash:c[C].orderHash,order:g?W(g.result):void 0}))}}}}async prepareListing({makerAddress:n,sell:l,buy:a,orderStart:u,orderExpiry:c}){return this.seaport.prepareSeaportOrder(n,l,a,l.type==="ERC1155",u||new Date,c||r.defaultOrderExpiry())}async createListing(n){let l=await this.apiClient.createListing(n);return {result:W(l.result)}}async prepareBid({makerAddress:n,sell:l,buy:a,orderStart:u,orderExpiry:c}){return this.seaport.prepareSeaportOrder(n,l,a,a.type==="ERC1155",u||new Date,c||r.defaultOrderExpiry())}async createBid(n){let l=await this.apiClient.createBid(n);return {result:se(l.result)}}async prepareCollectionBid({makerAddress:n,sell:l,buy:a,orderStart:u,orderExpiry:c}){return this.seaport.prepareSeaportOrder(n,l,a,!0,u||new Date,c||r.defaultOrderExpiry())}async createCollectionBid(n){let l=await this.apiClient.createCollectionBid(n);return {result:ae(l.result)}}async fulfillOrder(n,l,a,u,c){let o={order_id:n,taker_address:l,fees:a.map(R=>({type:v.type.TAKER_ECOSYSTEM,amount:R.amount,recipient_address:R.recipientAddress}))},h=c?[{identifier:c,proof:[]}]:void 0;c&&(o.token_id=c);let E=await this.apiClient.fulfillmentData([o]);if(E.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment data: ${E.result.unfulfillable_orders[0].reason}`);if(E.result.fulfillable_orders?.length!==1)throw new Error("unexpected fulfillable order result length");let f=E.result.fulfillable_orders[0].extra_data,y=E.result.fulfillable_orders[0].order;if(y.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${y.status}`);return this.seaport.fulfillOrder(y,l,f,u,h)}async fulfillBulkOrders(n,l){let a=n.map(c=>{let o="listingId"in c;return {orderId:o?c.listingId:c.orderId,takerFees:c.takerFees,amountToFill:c.amountToFill,tokenId:o?void 0:c.tokenId}}),u=await this.apiClient.fulfillmentData(a.map(c=>({order_id:c.orderId,taker_address:l,fees:c.takerFees.map(o=>({type:v.type.TAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),token_id:c?.tokenId})));try{let c=u.result.fulfillable_orders.map(o=>{let h=a.find(f=>f.orderId===o.order.id&&f.tokenId===o.token_id);if(!h){let f=`Could not find order for order ${o.order.id}`;throw o.token_id&&(f+=` and token ID ${o.token_id}`),new Error(f)}let E=[];return h.tokenId&&E.push({identifier:h.tokenId,proof:[]}),{extraData:o.extra_data,order:o.order,unitsToFill:h.amountToFill,considerationCriteria:E}});return {...await this.seaport.fulfillBulkOrders(c,l),fulfillableOrders:u.result.fulfillable_orders.map(o=>le(o.order)),unfulfillableOrders:u.result.unfulfillable_orders.map(o=>({orderId:o.order_id,tokenId:o.token_id,reason:o.reason})),sufficientBalance:!0}}catch(c){if(String(c).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:u.result.fulfillable_orders.map(o=>le(o.order)),unfulfillableOrders:u.result.unfulfillable_orders.map(o=>({orderId:o.order_id,reason:o.reason})),sufficientBalance:!1};throw c}}async prepareOrderCancellations(n){let a={name:"imtbl-order-book",chainId:(await this.orderbookConfig.provider.getNetwork()).chainId,verifyingContract:this.orderbookConfig.seaportContractAddress},u={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},c={orders:n.map(o=>({id:o}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:a,types:u,value:c}}}}async cancelOrders(n,l,a){return this.apiClient.cancelOrders(n,l,a)}async cancelOrdersOnChain(n,l){let a=Promise.all(n.map(y=>this.apiClient.getListing(y).catch(R=>{if(R.status!==404)throw R}))),u=Promise.all(n.map(y=>this.apiClient.getBid(y).catch(R=>{if(R.status!==404)throw R}))),c=Promise.all(n.map(y=>this.apiClient.getCollectionBid(y).catch(R=>{if(R.status!==404)throw R}))),o=[await Promise.all([a,u,c])].flat(2).filter(y=>y!==void 0).map(y=>y.result);if(o.length!==n.length){let y=n.filter(R=>!o.some(g=>g.id===R));throw new Error(`Orders ${y} not found`)}for(let y of o)if(y.account_address!==l.toLowerCase())throw new Error(`Only account ${y.account_address} can cancel order ${y.id}`);let h=o.map(y=>y.protocol_data.seaport_address);if(new Set(h).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(o,l)}}};var Dr={estimatedFulfillmentGasGwei:4e5};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
9
+ var te={},tt=!1;function Kt(){if(tt)return te;tt=!0,te.byteLength=h,te.toByteArray=f,te.fromByteArray=g;for(var r=[],n=[],l=typeof Uint8Array<"u"?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,p=a.length;c<p;++c)r[c]=a[c],n[a.charCodeAt(c)]=c;n[45]=62,n[95]=63;function o(C){var I=C.length;if(I%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var _=C.indexOf("=");_===-1&&(_=I);var L=_===I?0:4-_%4;return [_,L]}function h(C){var I=o(C),_=I[0],L=I[1];return (_+L)*3/4-L}function E(C,I,_){return (I+_)*3/4-_}function f(C){var I,_=o(C),L=_[0],k=_[1],x=new l(E(C,L,k)),D=0,q=k>0?L-4:L,N;for(N=0;N<q;N+=4)I=n[C.charCodeAt(N)]<<18|n[C.charCodeAt(N+1)]<<12|n[C.charCodeAt(N+2)]<<6|n[C.charCodeAt(N+3)],x[D++]=I>>16&255,x[D++]=I>>8&255,x[D++]=I&255;return k===2&&(I=n[C.charCodeAt(N)]<<2|n[C.charCodeAt(N+1)]>>4,x[D++]=I&255),k===1&&(I=n[C.charCodeAt(N)]<<10|n[C.charCodeAt(N+1)]<<4|n[C.charCodeAt(N+2)]>>2,x[D++]=I>>8&255,x[D++]=I&255),x}function y(C){return r[C>>18&63]+r[C>>12&63]+r[C>>6&63]+r[C&63]}function R(C,I,_){for(var L,k=[],x=I;x<_;x+=3)L=(C[x]<<16&16711680)+(C[x+1]<<8&65280)+(C[x+2]&255),k.push(y(L));return k.join("")}function g(C){for(var I,_=C.length,L=_%3,k=[],x=16383,D=0,q=_-L;D<q;D+=x)k.push(R(C,D,D+x>q?q:D+x));return L===1?(I=C[_-1],k.push(r[I>>2]+r[I<<4&63]+"==")):L===2&&(I=(C[_-2]<<8)+C[_-1],k.push(r[I>>10]+r[I>>4&63]+r[I<<2&63]+"=")),k.join("")}return te}var de={},rt=!1;function Jt(){if(rt)return de;rt=!0;return de.read=function(r,n,l,a,c){var p,o,h=c*8-a-1,E=(1<<h)-1,f=E>>1,y=-7,R=l?c-1:0,g=l?-1:1,C=r[n+R];for(R+=g,p=C&(1<<-y)-1,C>>=-y,y+=h;y>0;p=p*256+r[n+R],R+=g,y-=8);for(o=p&(1<<-y)-1,p>>=-y,y+=a;y>0;o=o*256+r[n+R],R+=g,y-=8);if(p===0)p=1-f;else {if(p===E)return o?NaN:(C?-1:1)*(1/0);o=o+Math.pow(2,a),p=p-f;}return (C?-1:1)*o*Math.pow(2,p-a)},de.write=function(r,n,l,a,c,p){var o,h,E,f=p*8-c-1,y=(1<<f)-1,R=y>>1,g=c===23?Math.pow(2,-24)-Math.pow(2,-77):0,C=a?0:p-1,I=a?1:-1,_=n<0||n===0&&1/n<0?1:0;for(n=Math.abs(n),isNaN(n)||n===1/0?(h=isNaN(n)?1:0,o=y):(o=Math.floor(Math.log(n)/Math.LN2),n*(E=Math.pow(2,-o))<1&&(o--,E*=2),o+R>=1?n+=g/E:n+=g*Math.pow(2,1-R),n*E>=2&&(o++,E/=2),o+R>=y?(h=0,o=y):o+R>=1?(h=(n*E-1)*Math.pow(2,c),o=o+R):(h=n*Math.pow(2,R-1)*Math.pow(2,c),o=0));c>=8;r[l+C]=h&255,C+=I,h/=256,c-=8);for(o=o<<c|h,f+=c;f>0;r[l+C]=o&255,C+=I,o/=256,f-=8);r[l+C-I]|=_*128;},de}var G={},nt=!1;function Xt(){if(nt)return G;nt=!0;let r=Kt(),n=Jt(),l=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;G.Buffer=o,G.SlowBuffer=k,G.INSPECT_MAX_BYTES=50;let a=2147483647;G.kMaxLength=a,o.TYPED_ARRAY_SUPPORT=c(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function c(){try{let i=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(i,e),i.foo()===42}catch{return !1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function p(i){if(i>a)throw new RangeError('The value "'+i+'" is invalid for option "size"');let e=new Uint8Array(i);return Object.setPrototypeOf(e,o.prototype),e}function o(i,e,t){if(typeof i=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return y(i)}return h(i,e,t)}o.poolSize=8192;function h(i,e,t){if(typeof i=="string")return R(i,e);if(ArrayBuffer.isView(i))return C(i);if(i==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof i);if(M(i,ArrayBuffer)||i&&M(i.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(M(i,SharedArrayBuffer)||i&&M(i.buffer,SharedArrayBuffer)))return I(i,e,t);if(typeof i=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let s=i.valueOf&&i.valueOf();if(s!=null&&s!==i)return o.from(s,e,t);let u=_(i);if(u)return u;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof i[Symbol.toPrimitive]=="function")return o.from(i[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof i)}o.from=function(i,e,t){return h(i,e,t)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function E(i){if(typeof i!="number")throw new TypeError('"size" argument must be of type number');if(i<0)throw new RangeError('The value "'+i+'" is invalid for option "size"')}function f(i,e,t){return E(i),i<=0?p(i):e!==void 0?typeof t=="string"?p(i).fill(e,t):p(i).fill(e):p(i)}o.alloc=function(i,e,t){return f(i,e,t)};function y(i){return E(i),p(i<0?0:L(i)|0)}o.allocUnsafe=function(i){return y(i)},o.allocUnsafeSlow=function(i){return y(i)};function R(i,e){if((typeof e!="string"||e==="")&&(e="utf8"),!o.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=x(i,e)|0,s=p(t),u=s.write(i,e);return u!==t&&(s=s.slice(0,u)),s}function g(i){let e=i.length<0?0:L(i.length)|0,t=p(e);for(let s=0;s<e;s+=1)t[s]=i[s]&255;return t}function C(i){if(M(i,Uint8Array)){let e=new Uint8Array(i);return I(e.buffer,e.byteOffset,e.byteLength)}return g(i)}function I(i,e,t){if(e<0||i.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(i.byteLength<e+(t||0))throw new RangeError('"length" is outside of buffer bounds');let s;return e===void 0&&t===void 0?s=new Uint8Array(i):t===void 0?s=new Uint8Array(i,e):s=new Uint8Array(i,e,t),Object.setPrototypeOf(s,o.prototype),s}function _(i){if(o.isBuffer(i)){let e=L(i.length)|0,t=p(e);return t.length===0||i.copy(t,0,0,e),t}if(i.length!==void 0)return typeof i.length!="number"||Ne(i.length)?p(0):g(i);if(i.type==="Buffer"&&Array.isArray(i.data))return g(i.data)}function L(i){if(i>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return i|0}function k(i){return +i!=i&&(i=0),o.alloc(+i)}o.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==o.prototype},o.compare=function(e,t){if(M(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),M(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let s=e.length,u=t.length;for(let d=0,m=Math.min(s,u);d<m;++d)if(e[d]!==t[d]){s=e[d],u=t[d];break}return s<u?-1:u<s?1:0},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return !0;default:return !1}},o.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return o.alloc(0);let s;if(t===void 0)for(t=0,s=0;s<e.length;++s)t+=e[s].length;let u=o.allocUnsafe(t),d=0;for(s=0;s<e.length;++s){let m=e[s];if(M(m,Uint8Array))d+m.length>u.length?(o.isBuffer(m)||(m=o.from(m)),m.copy(u,d)):Uint8Array.prototype.set.call(u,m,d);else if(o.isBuffer(m))m.copy(u,d);else throw new TypeError('"list" argument must be an Array of Buffers');d+=m.length;}return u};function x(i,e){if(o.isBuffer(i))return i.length;if(ArrayBuffer.isView(i)||M(i,ArrayBuffer))return i.byteLength;if(typeof i!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof i);let t=i.length,s=arguments.length>2&&arguments[2]===!0;if(!s&&t===0)return 0;let u=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":return Pe(i).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"base64":return et(i).length;default:if(u)return s?-1:Pe(i).length;e=(""+e).toLowerCase(),u=!0;}}o.byteLength=x;function D(i,e,t){let s=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return "";for(i||(i="utf8");;)switch(i){case"hex":return Ht(this,e,t);case"utf8":case"utf-8":return Ge(this,e,t);case"ascii":return Ut(this,e,t);case"latin1":case"binary":return qt(this,e,t);case"base64":return Ft(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Mt(this,e,t);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(i+"").toLowerCase(),s=!0;}}o.prototype._isBuffer=!0;function q(i,e,t){let s=i[e];i[e]=i[t],i[t]=s;}o.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)q(this,t,t+1);return this},o.prototype.swap32=function(){let e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)q(this,t,t+3),q(this,t+1,t+2);return this},o.prototype.swap64=function(){let e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)q(this,t,t+7),q(this,t+1,t+6),q(this,t+2,t+5),q(this,t+3,t+4);return this},o.prototype.toString=function(){let e=this.length;return e===0?"":arguments.length===0?Ge(this,0,e):D.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:o.compare(this,e)===0},o.prototype.inspect=function(){let e="",t=G.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},l&&(o.prototype[l]=o.prototype.inspect),o.prototype.compare=function(e,t,s,u,d){if(M(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),s===void 0&&(s=e?e.length:0),u===void 0&&(u=0),d===void 0&&(d=this.length),t<0||s>e.length||u<0||d>this.length)throw new RangeError("out of range index");if(u>=d&&t>=s)return 0;if(u>=d)return -1;if(t>=s)return 1;if(t>>>=0,s>>>=0,u>>>=0,d>>>=0,this===e)return 0;let m=d-u,A=s-t,b=Math.min(m,A),w=this.slice(u,d),S=e.slice(t,s);for(let B=0;B<b;++B)if(w[B]!==S[B]){m=w[B],A=S[B];break}return m<A?-1:A<m?1:0};function N(i,e,t,s,u){if(i.length===0)return -1;if(typeof t=="string"?(s=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,Ne(t)&&(t=u?0:i.length-1),t<0&&(t=i.length+t),t>=i.length){if(u)return -1;t=i.length-1;}else if(t<0)if(u)t=0;else return -1;if(typeof e=="string"&&(e=o.from(e,s)),o.isBuffer(e))return e.length===0?-1:ze(i,e,t,s,u);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?u?Uint8Array.prototype.indexOf.call(i,e,t):Uint8Array.prototype.lastIndexOf.call(i,e,t):ze(i,[e],t,s,u);throw new TypeError("val must be string, number or Buffer")}function ze(i,e,t,s,u){let d=1,m=i.length,A=e.length;if(s!==void 0&&(s=String(s).toLowerCase(),s==="ucs2"||s==="ucs-2"||s==="utf16le"||s==="utf-16le")){if(i.length<2||e.length<2)return -1;d=2,m/=2,A/=2,t/=2;}function b(S,B){return d===1?S[B]:S.readUInt16BE(B*d)}let w;if(u){let S=-1;for(w=t;w<m;w++)if(b(i,w)===b(e,S===-1?0:w-S)){if(S===-1&&(S=w),w-S+1===A)return S*d}else S!==-1&&(w-=w-S),S=-1;}else for(t+A>m&&(t=m-A),w=t;w>=0;w--){let S=!0;for(let B=0;B<A;B++)if(b(i,w+B)!==b(e,B)){S=!1;break}if(S)return w}return -1}o.prototype.includes=function(e,t,s){return this.indexOf(e,t,s)!==-1},o.prototype.indexOf=function(e,t,s){return N(this,e,t,s,!0)},o.prototype.lastIndexOf=function(e,t,s){return N(this,e,t,s,!1)};function xt(i,e,t,s){t=Number(t)||0;let u=i.length-t;s?(s=Number(s),s>u&&(s=u)):s=u;let d=e.length;s>d/2&&(s=d/2);let m;for(m=0;m<s;++m){let A=parseInt(e.substr(m*2,2),16);if(Ne(A))return m;i[t+m]=A;}return m}function Pt(i,e,t,s){return ce(Pe(e,i.length-t),i,t,s)}function Nt(i,e,t,s){return ce(Gt(e),i,t,s)}function kt(i,e,t,s){return ce(et(e),i,t,s)}function Dt(i,e,t,s){return ce(jt(e,i.length-t),i,t,s)}o.prototype.write=function(e,t,s,u){if(t===void 0)u="utf8",s=this.length,t=0;else if(s===void 0&&typeof t=="string")u=t,s=this.length,t=0;else if(isFinite(t))t=t>>>0,isFinite(s)?(s=s>>>0,u===void 0&&(u="utf8")):(u=s,s=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let d=this.length-t;if((s===void 0||s>d)&&(s=d),e.length>0&&(s<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");u||(u="utf8");let m=!1;for(;;)switch(u){case"hex":return xt(this,e,t,s);case"utf8":case"utf-8":return Pt(this,e,t,s);case"ascii":case"latin1":case"binary":return Nt(this,e,t,s);case"base64":return kt(this,e,t,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Dt(this,e,t,s);default:if(m)throw new TypeError("Unknown encoding: "+u);u=(""+u).toLowerCase(),m=!0;}},o.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ft(i,e,t){return e===0&&t===i.length?r.fromByteArray(i):r.fromByteArray(i.slice(e,t))}function Ge(i,e,t){t=Math.min(i.length,t);let s=[],u=e;for(;u<t;){let d=i[u],m=null,A=d>239?4:d>223?3:d>191?2:1;if(u+A<=t){let b,w,S,B;switch(A){case 1:d<128&&(m=d);break;case 2:b=i[u+1],(b&192)===128&&(B=(d&31)<<6|b&63,B>127&&(m=B));break;case 3:b=i[u+1],w=i[u+2],(b&192)===128&&(w&192)===128&&(B=(d&15)<<12|(b&63)<<6|w&63,B>2047&&(B<55296||B>57343)&&(m=B));break;case 4:b=i[u+1],w=i[u+2],S=i[u+3],(b&192)===128&&(w&192)===128&&(S&192)===128&&(B=(d&15)<<18|(b&63)<<12|(w&63)<<6|S&63,B>65535&&B<1114112&&(m=B));}}m===null?(m=65533,A=1):m>65535&&(m-=65536,s.push(m>>>10&1023|55296),m=56320|m&1023),s.push(m),u+=A;}return vt(s)}let je=4096;function vt(i){let e=i.length;if(e<=je)return String.fromCharCode.apply(String,i);let t="",s=0;for(;s<e;)t+=String.fromCharCode.apply(String,i.slice(s,s+=je));return t}function Ut(i,e,t){let s="";t=Math.min(i.length,t);for(let u=e;u<t;++u)s+=String.fromCharCode(i[u]&127);return s}function qt(i,e,t){let s="";t=Math.min(i.length,t);for(let u=e;u<t;++u)s+=String.fromCharCode(i[u]);return s}function Ht(i,e,t){let s=i.length;(!e||e<0)&&(e=0),(!t||t<0||t>s)&&(t=s);let u="";for(let d=e;d<t;++d)u+=Wt[i[d]];return u}function Mt(i,e,t){let s=i.slice(e,t),u="";for(let d=0;d<s.length-1;d+=2)u+=String.fromCharCode(s[d]+s[d+1]*256);return u}o.prototype.slice=function(e,t){let s=this.length;e=~~e,t=t===void 0?s:~~t,e<0?(e+=s,e<0&&(e=0)):e>s&&(e=s),t<0?(t+=s,t<0&&(t=0)):t>s&&(t=s),t<e&&(t=e);let u=this.subarray(e,t);return Object.setPrototypeOf(u,o.prototype),u};function P(i,e,t){if(i%1!==0||i<0)throw new RangeError("offset is not uint");if(i+e>t)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(e,t,s){e=e>>>0,t=t>>>0,s||P(e,t,this.length);let u=this[e],d=1,m=0;for(;++m<t&&(d*=256);)u+=this[e+m]*d;return u},o.prototype.readUintBE=o.prototype.readUIntBE=function(e,t,s){e=e>>>0,t=t>>>0,s||P(e,t,this.length);let u=this[e+--t],d=1;for(;t>0&&(d*=256);)u+=this[e+--t]*d;return u},o.prototype.readUint8=o.prototype.readUInt8=function(e,t){return e=e>>>0,t||P(e,1,this.length),this[e]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(e,t){return e=e>>>0,t||P(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(e,t){return e=e>>>0,t||P(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(e,t){return e=e>>>0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(e,t){return e=e>>>0,t||P(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readBigUInt64LE=$(function(e){e=e>>>0,J(e,"offset");let t=this[e],s=this[e+7];(t===void 0||s===void 0)&&ee(e,this.length-8);let u=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,d=this[++e]+this[++e]*2**8+this[++e]*2**16+s*2**24;return BigInt(u)+(BigInt(d)<<BigInt(32))}),o.prototype.readBigUInt64BE=$(function(e){e=e>>>0,J(e,"offset");let t=this[e],s=this[e+7];(t===void 0||s===void 0)&&ee(e,this.length-8);let u=t*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],d=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+s;return (BigInt(u)<<BigInt(32))+BigInt(d)}),o.prototype.readIntLE=function(e,t,s){e=e>>>0,t=t>>>0,s||P(e,t,this.length);let u=this[e],d=1,m=0;for(;++m<t&&(d*=256);)u+=this[e+m]*d;return d*=128,u>=d&&(u-=Math.pow(2,8*t)),u},o.prototype.readIntBE=function(e,t,s){e=e>>>0,t=t>>>0,s||P(e,t,this.length);let u=t,d=1,m=this[e+--u];for(;u>0&&(d*=256);)m+=this[e+--u]*d;return d*=128,m>=d&&(m-=Math.pow(2,8*t)),m},o.prototype.readInt8=function(e,t){return e=e>>>0,t||P(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},o.prototype.readInt16LE=function(e,t){e=e>>>0,t||P(e,2,this.length);let s=this[e]|this[e+1]<<8;return s&32768?s|4294901760:s},o.prototype.readInt16BE=function(e,t){e=e>>>0,t||P(e,2,this.length);let s=this[e+1]|this[e]<<8;return s&32768?s|4294901760:s},o.prototype.readInt32LE=function(e,t){return e=e>>>0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e=e>>>0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readBigInt64LE=$(function(e){e=e>>>0,J(e,"offset");let t=this[e],s=this[e+7];(t===void 0||s===void 0)&&ee(e,this.length-8);let u=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(s<<24);return (BigInt(u)<<BigInt(32))+BigInt(t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)}),o.prototype.readBigInt64BE=$(function(e){e=e>>>0,J(e,"offset");let t=this[e],s=this[e+7];(t===void 0||s===void 0)&&ee(e,this.length-8);let u=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return (BigInt(u)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+s)}),o.prototype.readFloatLE=function(e,t){return e=e>>>0,t||P(e,4,this.length),n.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e=e>>>0,t||P(e,4,this.length),n.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e=e>>>0,t||P(e,8,this.length),n.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e=e>>>0,t||P(e,8,this.length),n.read(this,e,!1,52,8)};function F(i,e,t,s,u,d){if(!o.isBuffer(i))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>u||e<d)throw new RangeError('"value" argument is out of bounds');if(t+s>i.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(e,t,s,u){if(e=+e,t=t>>>0,s=s>>>0,!u){let A=Math.pow(2,8*s)-1;F(this,e,t,s,A,0);}let d=1,m=0;for(this[t]=e&255;++m<s&&(d*=256);)this[t+m]=e/d&255;return t+s},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(e,t,s,u){if(e=+e,t=t>>>0,s=s>>>0,!u){let A=Math.pow(2,8*s)-1;F(this,e,t,s,A,0);}let d=s-1,m=1;for(this[t+d]=e&255;--d>=0&&(m*=256);)this[t+d]=e/m&255;return t+s},o.prototype.writeUint8=o.prototype.writeUInt8=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,1,255,0),this[t]=e&255,t+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4};function We(i,e,t,s,u){Qe(e,s,u,i,t,7);let d=Number(e&BigInt(4294967295));i[t++]=d,d=d>>8,i[t++]=d,d=d>>8,i[t++]=d,d=d>>8,i[t++]=d;let m=Number(e>>BigInt(32)&BigInt(4294967295));return i[t++]=m,m=m>>8,i[t++]=m,m=m>>8,i[t++]=m,m=m>>8,i[t++]=m,t}function Ye(i,e,t,s,u){Qe(e,s,u,i,t,7);let d=Number(e&BigInt(4294967295));i[t+7]=d,d=d>>8,i[t+6]=d,d=d>>8,i[t+5]=d,d=d>>8,i[t+4]=d;let m=Number(e>>BigInt(32)&BigInt(4294967295));return i[t+3]=m,m=m>>8,i[t+2]=m,m=m>>8,i[t+1]=m,m=m>>8,i[t]=m,t+8}o.prototype.writeBigUInt64LE=$(function(e,t=0){return We(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=$(function(e,t=0){return Ye(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(e,t,s,u){if(e=+e,t=t>>>0,!u){let b=Math.pow(2,8*s-1);F(this,e,t,s,b-1,-b);}let d=0,m=1,A=0;for(this[t]=e&255;++d<s&&(m*=256);)e<0&&A===0&&this[t+d-1]!==0&&(A=1),this[t+d]=(e/m>>0)-A&255;return t+s},o.prototype.writeIntBE=function(e,t,s,u){if(e=+e,t=t>>>0,!u){let b=Math.pow(2,8*s-1);F(this,e,t,s,b-1,-b);}let d=s-1,m=1,A=0;for(this[t+d]=e&255;--d>=0&&(m*=256);)e<0&&A===0&&this[t+d+1]!==0&&(A=1),this[t+d]=(e/m>>0)-A&255;return t+s},o.prototype.writeInt8=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},o.prototype.writeInt16LE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},o.prototype.writeInt32LE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,s){return e=+e,t=t>>>0,s||F(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},o.prototype.writeBigInt64LE=$(function(e,t=0){return We(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=$(function(e,t=0){return Ye(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Ke(i,e,t,s,u,d){if(t+s>i.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function Je(i,e,t,s,u){return e=+e,t=t>>>0,u||Ke(i,e,t,4),n.write(i,e,t,s,23,4),t+4}o.prototype.writeFloatLE=function(e,t,s){return Je(this,e,t,!0,s)},o.prototype.writeFloatBE=function(e,t,s){return Je(this,e,t,!1,s)};function Xe(i,e,t,s,u){return e=+e,t=t>>>0,u||Ke(i,e,t,8),n.write(i,e,t,s,52,8),t+8}o.prototype.writeDoubleLE=function(e,t,s){return Xe(this,e,t,!0,s)},o.prototype.writeDoubleBE=function(e,t,s){return Xe(this,e,t,!1,s)},o.prototype.copy=function(e,t,s,u){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(s||(s=0),!u&&u!==0&&(u=this.length),t>=e.length&&(t=e.length),t||(t=0),u>0&&u<s&&(u=s),u===s||e.length===0||this.length===0)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(s<0||s>=this.length)throw new RangeError("Index out of range");if(u<0)throw new RangeError("sourceEnd out of bounds");u>this.length&&(u=this.length),e.length-t<u-s&&(u=e.length-t+s);let d=u-s;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(t,s,u):Uint8Array.prototype.set.call(e,this.subarray(s,u),t),d},o.prototype.fill=function(e,t,s,u){if(typeof e=="string"){if(typeof t=="string"?(u=t,t=0,s=this.length):typeof s=="string"&&(u=s,s=this.length),u!==void 0&&typeof u!="string")throw new TypeError("encoding must be a string");if(typeof u=="string"&&!o.isEncoding(u))throw new TypeError("Unknown encoding: "+u);if(e.length===1){let m=e.charCodeAt(0);(u==="utf8"&&m<128||u==="latin1")&&(e=m);}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(t<0||this.length<t||this.length<s)throw new RangeError("Out of range index");if(s<=t)return this;t=t>>>0,s=s===void 0?this.length:s>>>0,e||(e=0);let d;if(typeof e=="number")for(d=t;d<s;++d)this[d]=e;else {let m=o.isBuffer(e)?e:o.from(e,u),A=m.length;if(A===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(d=0;d<s-t;++d)this[d+t]=m[d%A];}return this};let K={};function xe(i,e,t){K[i]=class extends t{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${i}]`,this.stack,delete this.name;}get code(){return i}set code(u){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:u,writable:!0});}toString(){return `${this.name} [${i}]: ${this.message}`}};}xe("ERR_BUFFER_OUT_OF_BOUNDS",function(i){return i?`${i} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),xe("ERR_INVALID_ARG_TYPE",function(i,e){return `The "${i}" argument must be of type number. Received type ${typeof e}`},TypeError),xe("ERR_OUT_OF_RANGE",function(i,e,t){let s=`The value of "${i}" is out of range.`,u=t;return Number.isInteger(t)&&Math.abs(t)>2**32?u=Ze(String(t)):typeof t=="bigint"&&(u=String(t),(t>BigInt(2)**BigInt(32)||t<-(BigInt(2)**BigInt(32)))&&(u=Ze(u)),u+="n"),s+=` It must be ${e}. Received ${u}`,s},RangeError);function Ze(i){let e="",t=i.length,s=i[0]==="-"?1:0;for(;t>=s+4;t-=3)e=`_${i.slice(t-3,t)}${e}`;return `${i.slice(0,t)}${e}`}function $t(i,e,t){J(e,"offset"),(i[e]===void 0||i[e+t]===void 0)&&ee(e,i.length-(t+1));}function Qe(i,e,t,s,u,d){if(i>t||i<e){let m=typeof e=="bigint"?"n":"",A;throw e===0||e===BigInt(0)?A=`>= 0${m} and < 2${m} ** ${(d+1)*8}${m}`:A=`>= -(2${m} ** ${(d+1)*8-1}${m}) and < 2 ** ${(d+1)*8-1}${m}`,new K.ERR_OUT_OF_RANGE("value",A,i)}$t(s,u,d);}function J(i,e){if(typeof i!="number")throw new K.ERR_INVALID_ARG_TYPE(e,"number",i)}function ee(i,e,t){throw Math.floor(i)!==i?(J(i,t),new K.ERR_OUT_OF_RANGE("offset","an integer",i)):e<0?new K.ERR_BUFFER_OUT_OF_BOUNDS:new K.ERR_OUT_OF_RANGE("offset",`>= ${0} and <= ${e}`,i)}let Vt=/[^+/0-9A-Za-z-_]/g;function zt(i){if(i=i.split("=")[0],i=i.trim().replace(Vt,""),i.length<2)return "";for(;i.length%4!==0;)i=i+"=";return i}function Pe(i,e){e=e||1/0;let t,s=i.length,u=null,d=[];for(let m=0;m<s;++m){if(t=i.charCodeAt(m),t>55295&&t<57344){if(!u){if(t>56319){(e-=3)>-1&&d.push(239,191,189);continue}else if(m+1===s){(e-=3)>-1&&d.push(239,191,189);continue}u=t;continue}if(t<56320){(e-=3)>-1&&d.push(239,191,189),u=t;continue}t=(u-55296<<10|t-56320)+65536;}else u&&(e-=3)>-1&&d.push(239,191,189);if(u=null,t<128){if((e-=1)<0)break;d.push(t);}else if(t<2048){if((e-=2)<0)break;d.push(t>>6|192,t&63|128);}else if(t<65536){if((e-=3)<0)break;d.push(t>>12|224,t>>6&63|128,t&63|128);}else if(t<1114112){if((e-=4)<0)break;d.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128);}else throw new Error("Invalid code point")}return d}function Gt(i){let e=[];for(let t=0;t<i.length;++t)e.push(i.charCodeAt(t)&255);return e}function jt(i,e){let t,s,u,d=[];for(let m=0;m<i.length&&!((e-=2)<0);++m)t=i.charCodeAt(m),s=t>>8,u=t%256,d.push(u),d.push(s);return d}function et(i){return r.toByteArray(zt(i))}function ce(i,e,t,s){let u;for(u=0;u<s&&!(u+t>=e.length||u>=i.length);++u)e[u+t]=i[u];return u}function M(i,e){return i instanceof e||i!=null&&i.constructor!=null&&i.constructor.name!=null&&i.constructor.name===e.name}function Ne(i){return i!==i}let Wt=function(){let i="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let s=t*16;for(let u=0;u<16;++u)e[s+u]=i[t]+i[u];}return e}();function $(i){return typeof BigInt>"u"?Yt:i}function Yt(){throw new Error("BigInt not supported")}return G}var j=Xt();j.Buffer;j.SlowBuffer;j.INSPECT_MAX_BYTES;j.kMaxLength;var T=j.Buffer;j.INSPECT_MAX_BYTES;j.kMaxLength;var re=class{constructor(n){this.config=n;}};var X=class extends Error{url;status;statusText;body;request;constructor(n,l,a){super(a),this.name="ApiError",this.url=l.url,this.status=l.status,this.statusText=l.statusText,this.body=l.body,this.request=n;}};var me=class extends Error{constructor(n){super(n),this.name="CancelError";}get isCancelled(){return !0}},ne=class{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(n){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((l,a)=>{this._resolve=l,this._reject=a;let c=h=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(h));},p=h=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(h));},o=h=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(h);};return Object.defineProperty(o,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(o,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(o,"isCancelled",{get:()=>this._isCancelled}),n(c,p,o)});}then(n,l){return this._promise.then(n,l)}catch(n){return this._promise.catch(n)}finally(n){return this._promise.finally(n)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let n of this._cancelHandlers)n();}catch(n){console.warn("Cancellation threw an error",n);return}this._cancelHandlers.length=0,this._reject?.(new me("Request aborted"));}}get isCancelled(){return this._isCancelled}};var De=r=>r!=null,he=r=>typeof r=="string",ke=r=>he(r)&&r!=="",st=r=>typeof r=="object"&&typeof r.type=="string"&&typeof r.stream=="function"&&typeof r.arrayBuffer=="function"&&typeof r.constructor=="function"&&typeof r.constructor.name=="string"&&/^(Blob|File)$/.test(r.constructor.name)&&/^(Blob|File)$/.test(r[Symbol.toStringTag]),Zt=r=>r instanceof ot,Qt=r=>r>=200&&r<300,er=r=>{try{return btoa(r)}catch{return T.from(r).toString("base64")}},tr=r=>{let n=[],l=(c,p)=>{n.push(`${encodeURIComponent(c)}=${encodeURIComponent(String(p))}`);},a=(c,p)=>{De(p)&&(Array.isArray(p)?p.forEach(o=>{a(c,o);}):typeof p=="object"?Object.entries(p).forEach(([o,h])=>{a(`${c}[${o}]`,h);}):l(c,p));};return Object.entries(r).forEach(([c,p])=>{a(c,p);}),n.length>0?`?${n.join("&")}`:""},rr=(r,n)=>{let l=r.ENCODE_PATH||encodeURI,a=n.url.replace("{api-version}",r.VERSION).replace(/{(.*?)}/g,(p,o)=>n.path?.hasOwnProperty(o)?l(String(n.path[o])):p),c=`${r.BASE}${a}`;return n.query?`${c}${tr(n.query)}`:c},nr=r=>{if(r.formData){let n=new ot,l=(a,c)=>{he(c)||st(c)?n.append(a,c):n.append(a,JSON.stringify(c));};return Object.entries(r.formData).filter(([a,c])=>De(c)).forEach(([a,c])=>{Array.isArray(c)?c.forEach(p=>l(a,p)):l(a,c);}),n}},fe=async(r,n)=>typeof n=="function"?n(r):n,ir=async(r,n,l)=>{let a=await fe(n,r.TOKEN),c=await fe(n,r.USERNAME),p=await fe(n,r.PASSWORD),o=await fe(n,r.HEADERS),h=typeof l?.getHeaders=="function"&&l?.getHeaders()||{},E=Object.entries({Accept:"application/json",...o,...n.headers,...h}).filter(([f,y])=>De(y)).reduce((f,[y,R])=>({...f,[y]:String(R)}),{});if(ke(a)&&(E.Authorization=`Bearer ${a}`),ke(c)&&ke(p)){let f=er(`${c}:${p}`);E.Authorization=`Basic ${f}`;}return n.body&&(n.mediaType?E["Content-Type"]=n.mediaType:st(n.body)?E["Content-Type"]=n.body.type||"application/octet-stream":he(n.body)?E["Content-Type"]="text/plain":Zt(n.body)||(E["Content-Type"]="application/json")),E},or=r=>{if(r.body)return r.body},sr=async(r,n,l,a,c,p,o)=>{let h=it.CancelToken.source(),E={url:l,headers:p,data:a??c,method:n.method,withCredentials:r.WITH_CREDENTIALS,cancelToken:h.token};o(()=>h.cancel("The user aborted a request."));try{return await it.request(E)}catch(f){let y=f;if(y.response)return y.response;throw f}},ar=(r,n)=>{if(n){let l=r.headers[n];if(he(l))return l}},lr=r=>{if(r.status!==204)return r.data},ur=(r,n)=>{let a={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...r.errors}[n.status];if(a)throw new X(r,n,a);if(!n.ok)throw new X(r,n,"Generic Error")},at=(r,n)=>new ne(async(l,a,c)=>{try{let p=rr(r,n),o=nr(n),h=or(n),E=await ir(r,n,o);if(!c.isCancelled){let f=await sr(r,n,p,h,o,E,c),y=lr(f),R=ar(f,n.responseHeader),g={url:p,ok:Qt(f.status),status:f.status,statusText:f.statusText,body:R??y};ur(n,g),l(g.body);}}catch(p){a(p);}});var ye=class extends re{constructor(n){super(n);}request(n){return at(this.config,n)}};var ie=class{constructor(n){this.httpRequest=n;}cancelOrders({chainName:n,requestBody:l}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:n},body:l,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:n,status:l,sellItemContractAddress:a,buyItemType:c,buyItemContractAddress:p,accountAddress:o,sellItemMetadataId:h,sellItemTokenId:E,fromUpdatedAt:f,pageSize:y,sortBy:R,sortDirection:g,pageCursor:C}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:n},query:{status:l,sell_item_contract_address:a,buy_item_type:c,buy_item_contract_address:p,account_address:o,sell_item_metadata_id:h,sell_item_token_id:E,from_updated_at:f,page_size:y,sort_by:R,sort_direction:g,page_cursor:C},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:n,requestBody:l}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:n},body:l,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listBids({chainName:n,status:l,buyItemContractAddress:a,sellItemContractAddress:c,accountAddress:p,buyItemMetadataId:o,buyItemTokenId:h,fromUpdatedAt:E,pageSize:f,sortBy:y,sortDirection:R,pageCursor:g}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:n},query:{status:l,buy_item_contract_address:a,sell_item_contract_address:c,account_address:p,buy_item_metadata_id:o,buy_item_token_id:h,from_updated_at:E,page_size:f,sort_by:y,sort_direction:R,page_cursor:g},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createBid({chainName:n,requestBody:l}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:n},body:l,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:n,status:l,buyItemContractAddress:a,sellItemContractAddress:c,accountAddress:p,fromUpdatedAt:o,pageSize:h,sortBy:E,sortDirection:f,pageCursor:y}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:n},query:{status:l,buy_item_contract_address:a,sell_item_contract_address:c,account_address:p,from_updated_at:o,page_size:h,sort_by:E,sort_direction:f,page_cursor:y},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createCollectionBid({chainName:n,requestBody:l}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:n},body:l,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:n,listingId:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:n,listing_id:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getBid({chainName:n,bidId:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids/{bid_id}",path:{chain_name:n,bid_id:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getCollectionBid({chainName:n,collectionBidId:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids/{collection_bid_id}",path:{chain_name:n,collection_bid_id:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:n,requestBody:l}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:n},body:l,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:n,accountAddress:l,sellItemContractAddress:a,fromIndexedAt:c,pageSize:p,sortBy:o,sortDirection:h,pageCursor:E}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:n},query:{account_address:l,sell_item_contract_address:a,from_indexed_at:c,page_size:p,sort_by:o,sort_direction:h,page_cursor:E},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:n,tradeId:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:n,trade_id:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}};var oe=class{orders;request;constructor(n,l=ye){this.request=new l({BASE:n?.BASE??"https://api.immutable.com",VERSION:n?.VERSION??"1.0.0",WITH_CREDENTIALS:n?.WITH_CREDENTIALS??!1,CREDENTIALS:n?.CREDENTIALS??"include",TOKEN:n?.TOKEN,USERNAME:n?.USERNAME,PASSWORD:n?.PASSWORD,HEADERS:n?.HEADERS,ENCODE_PATH:n?.ENCODE_PATH}),this.orders=new ie(this.request);}};var lt;(n=>{(p=>(p.ON_CHAIN="ON_CHAIN",p.OFF_CHAIN="OFF_CHAIN",p.UNDERFUNDED="UNDERFUNDED"))(n.cancellation_type||={});})(lt||={});var ut;(n=>{(a=>a.FILLED="FILLED")(n.reason_code||={});})(ut||={});var v;(n=>{(o=>(o.ROYALTY="ROYALTY",o.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",o.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",o.PROTOCOL="PROTOCOL"))(n.type||={});})(v||={});var H;(n=>{(p=>(p.LISTING="LISTING",p.BID="BID",p.COLLECTION_BID="COLLECTION_BID"))(n.type||={});})(H||={});var Ce=(o=>(o.PENDING="PENDING",o.ACTIVE="ACTIVE",o.INACTIVE="INACTIVE",o.FILLED="FILLED",o.EXPIRED="EXPIRED",o.CANCELLED="CANCELLED",o))(Ce||{});var V;(n=>{(c=>(c.FULL_RESTRICTED="FULL_RESTRICTED",c.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(n.order_type||={});})(V||={});function U(r){throw new Error("Unreachable")}function W(r){if(r.type!==H.type.LISTING)throw new Error("Order type must be LISTING");let n=r.sell.map(a=>{if(a.type==="ERC721")return {type:"ERC721",contractAddress:a.contract_address,tokenId:a.token_id};if(a.type==="ERC1155")return {type:"ERC1155",contractAddress:a.contract_address,tokenId:a.token_id,amount:a.amount};throw new Error("Listing sell items must either ERC721 or ERC1155")}),l=r.buy.map(a=>{if(a.type==="NATIVE")return {type:"NATIVE",amount:a.amount};if(a.type==="ERC20")return {type:"ERC20",contractAddress:a.contract_address,amount:a.amount};throw new Error("Listing buy items must be either NATIVE or ERC20")});return {id:r.id,type:r.type,chain:r.chain,accountAddress:r.account_address,sell:n,buy:l,fees:r.fees.map(a=>({amount:a.amount,recipientAddress:a.recipient_address,type:a.type})),status:r.status,fillStatus:r.fill_status,startAt:r.start_at,endAt:r.end_at,salt:r.salt,signature:r.signature,orderHash:r.order_hash,protocolData:{orderType:r.protocol_data.order_type,counter:r.protocol_data.counter,seaportAddress:r.protocol_data.seaport_address,seaportVersion:r.protocol_data.seaport_version,zoneAddress:r.protocol_data.zone_address},createdAt:r.created_at,updatedAt:r.updated_at}}function se(r){if(r.type!==H.type.BID)throw new Error("Order type must be BID");let n=r.sell.map(a=>{if(a.type==="ERC20")return {type:"ERC20",contractAddress:a.contract_address,amount:a.amount};throw new Error("Bid sell items must be ERC20")}),l=r.buy.map(a=>{if(a.type==="ERC721")return {type:"ERC721",contractAddress:a.contract_address,tokenId:a.token_id};if(a.type==="ERC1155")return {type:"ERC1155",contractAddress:a.contract_address,tokenId:a.token_id,amount:a.amount};throw new Error("Bid buy items must either ERC721 or ERC1155")});return {id:r.id,type:r.type,chain:r.chain,accountAddress:r.account_address,sell:n,buy:l,fees:r.fees.map(a=>({amount:a.amount,recipientAddress:a.recipient_address,type:a.type})),status:r.status,fillStatus:r.fill_status,startAt:r.start_at,endAt:r.end_at,salt:r.salt,signature:r.signature,orderHash:r.order_hash,protocolData:{orderType:r.protocol_data.order_type,counter:r.protocol_data.counter,seaportAddress:r.protocol_data.seaport_address,seaportVersion:r.protocol_data.seaport_version,zoneAddress:r.protocol_data.zone_address},createdAt:r.created_at,updatedAt:r.updated_at}}function ae(r){if(r.type!==H.type.COLLECTION_BID)throw new Error("Order type must be COLLECTION_BID");let n=r.sell.map(a=>{if(a.type==="ERC20")return {type:"ERC20",contractAddress:a.contract_address,amount:a.amount};throw new Error("Collection bid sell items must be ERC20")}),l=r.buy.map(a=>{if(a.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:a.contract_address,amount:a.amount};if(a.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:a.contract_address,amount:a.amount};throw new Error("Collection bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:r.id,type:r.type,chain:r.chain,accountAddress:r.account_address,sell:n,buy:l,fees:r.fees.map(a=>({amount:a.amount,recipientAddress:a.recipient_address,type:a.type})),status:r.status,fillStatus:r.fill_status,startAt:r.start_at,endAt:r.end_at,salt:r.salt,signature:r.signature,orderHash:r.order_hash,protocolData:{orderType:r.protocol_data.order_type,counter:r.protocol_data.counter,seaportAddress:r.protocol_data.seaport_address,seaportVersion:r.protocol_data.seaport_version,zoneAddress:r.protocol_data.zone_address},createdAt:r.created_at,updatedAt:r.updated_at}}function le(r){switch(r.type){case H.type.LISTING:return W(r);case H.type.BID:return se(r);case H.type.COLLECTION_BID:return ae(r);default:return U(r.type)}}function Fe(r){let n=r.buy.map(a=>{if(a.type==="NATIVE")return {type:"NATIVE",amount:a.amount};if(a.type==="ERC20")return {type:"ERC20",contractAddress:a.contract_address,amount:a.amount};if(a.type==="ERC721")return {type:"ERC721",contractAddress:a.contract_address,tokenId:a.token_id};if(a.type==="ERC1155")return {type:"ERC1155",contractAddress:a.contract_address,tokenId:a.token_id,amount:a.amount};throw new Error("Buy items must be NATIVE, ERC20, ERC721 or ERC1155")}),l=r.sell.map(a=>{if(a.type==="ERC20")return {type:"ERC20",contractAddress:a.contract_address,amount:a.amount};if(a.type==="ERC721")return {type:"ERC721",contractAddress:a.contract_address,tokenId:a.token_id};if(a.type==="ERC1155")return {type:"ERC1155",contractAddress:a.contract_address,tokenId:a.token_id,amount:a.amount};throw new Error("Sell items must be ERC20, ERC721 or ERC1155")});return {id:r.id,orderId:r.order_id,buy:n,sell:l,buyerFees:r.buyer_fees.map(a=>({amount:a.amount,recipientAddress:a.recipient_address,type:a.type})),fees:r.fees.map(a=>({amount:a.amount,recipientAddress:a.recipient_address,type:a.type})),chain:r.chain,indexedAt:r.indexed_at,blockchainMetadata:{blockNumber:r.blockchain_metadata.block_number,logIndex:r.blockchain_metadata.log_index,transactionHash:r.blockchain_metadata.transaction_hash,transactionIndex:r.blockchain_metadata.transaction_index},buyerAddress:r.buyer_address,makerAddress:r.maker_address,sellerAddress:r.seller_address,takerAddress:r.taker_address}}function ue(r){return {nextCursor:r.next_cursor,previousCursor:r.previous_cursor}}var pr=(c=>(c[c.MAKER_ECOSYSTEM=v.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",c[c.TAKER_ECOSYSTEM=v.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",c[c.PROTOCOL=v.type.PROTOCOL]="PROTOCOL",c[c.ROYALTY=v.type.ROYALTY]="ROYALTY",c))(pr||{}),ve=(l=>(l.TRANSACTION="TRANSACTION",l.SIGNABLE="SIGNABLE",l))(ve||{}),pt=(a=>(a.APPROVAL="APPROVAL",a.FULFILL_ORDER="FULFILL_ORDER",a.CANCEL="CANCEL",a))(pt||{}),Ue=(a=>(a.CREATE_LISTING="CREATE_ORDER",a.CREATE_ORDER="CREATE_ORDER",a.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",a))(Ue||{});var qe="ImmutableSeaport",Y="1.5",Ee={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 cr={integer:0,address:zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},He=r=>r===void 0?!1:r!=null&&(["string","number"].includes(typeof r)&&BigInt(r)===0n||Array.isArray(r)&&r.every(He)||typeof r=="object"&&Object.values(r).every(He)||typeof r=="boolean"&&r===!1);function dr(r){let[,n]=r.match(/^bytes(\d+)$/)??[];return n?zeroPadValue("0x",parseInt(n)):(r.match(/^(u?)int(\d*)$/)&&(r="integer"),cr[r])}var Z=class r{constructor(n){this.types=n;for(let l in n){let a=this.getDefaultValue(l);if(this.defaultValues[l]=a,!He(a))throw new Error(`Got non-empty value for type ${l} in default generator: ${a}`)}}defaultValues={};static from(n,l){let{defaultValues:a}=new r(n);return l?a[l]:a}getDefaultValue(n){if(this.defaultValues[n])return this.defaultValues[n];let l=dr(n);if(l!==void 0)return l;let a=n.match(/^(.*)(\x5b(\d*)\x5d)$/);if(a){let p=a[1],o=parseInt(a[3]);if(o>0){let h=this.getDefaultValue(p);return Array(o).fill(h)}return []}let c=this.types[n];if(c)return c.reduce((p,{name:o,type:h})=>({...p,[o]:this.getDefaultValue(h)}),{});throw new Error(`unknown type: ${n}`)}};var yr=(r,n)=>Array(r).fill(0).map((l,a)=>n(a)),Me=(r,n)=>yr(Math.ceil(r.length/n),l=>r.slice(l*n,(l+1)*n)),dt=r=>toBeHex(r.toString("hex")),Q=r=>T.from(r.slice(2),"hex"),ge=r=>Q(keccak256(r)),Cr=r=>ge(concat(r)),pe=(r,n,l)=>(n>r.length&&r.push(...Array(n-r.length).fill(l)),r),mt=(r,n=!0)=>{if(r.length===0)throw new Error("empty tree");let a=[r.map(c=>{let p=T.isBuffer(c)?c:Q(c);return n?ge(p):p})];for(;a[a.length-1].length>1;)a.push(Er(a[a.length-1]));return a[a.length-1][0]},Er=r=>Me(r,2).map(Cr);var Ar=(r,n)=>new MerkleTree(r.map(Q),ge,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:Q(n)}),Or=(r,n,l=`0x${"ff".repeat(64)}`)=>concat([l,`0x${r.toString(16).padStart(6,"0")}`,AbiCoder.defaultAbiCoder().encode([`uint256[${n.length}]`],[n])]),Re=class{constructor(n,l,a,c,p){this.types=n;this.rootType=l;this.leafType=a;this.elements=c;this.depth=p;let o=TypedDataEncoder.from(n);this.encoder=o,this.leafHasher=h=>o.hashStruct(a,h),this.defaultNode=Z.from(n,a),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=Ar(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:n}=this;return pe([...n],this.completedSize,this.defaultNode)}getCompleteLeaves(){let n=this.elements.map(this.leafHasher);return pe([...n],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(n){let a=this.getCompleteLeaves()[n],c=this.tree.getHexProof(a,n),p=this.tree.getHexRoot();return {leaf:a,proof:c,root:p}}getEncodedProofAndSignature(n,l){let{proof:a}=this.getProof(n);return Or(n,a,l)}getDataToSign(){let n=this.getCompleteElements();for(;n.length>2;)n=Me(n,2);return n}add(n){this.elements.push(n);}getBulkOrderHash(){let n=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),l=this.getCompleteLeaves().map(Q),a=dt(mt(l,!1)),c=keccak256(toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(keccak256(concat([c,a]))!==n)throw new Error("expected derived bulk order hash to match");return n}};function _r(r){return {...Ee,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(r)}`}]}}function Br(r){return Math.max(Math.ceil(Math.log2(r)),1)}function yt(r,n=0,l=Br(r.length+n)){let a=_r(l),c=Z.from(a,"OrderComponents"),p=[...r];return n>0&&(p=[...pe([],n,c),...r]),new Re(a,"BulkOrder","OrderComponents",p,l)}function gt(r){if([0,1,2,3].includes(Number(r)))return Number(r);throw new Error(`Unknown order type ${r}`)}function Ie(r){if([0,1,2,3,4,5].includes(Number(r)))return Number(r);throw new Error(`Unknown item type ${r}`)}function Rt(r){let l=JSON.parse(r).message;return {...l,orderType:gt(l.orderType),salt:toBeHex(BigInt(l.salt)),offer:l.offer.map(a=>({...a,itemType:Ie(a.itemType)})),consideration:l.consideration.map(a=>({...a,itemType:Ie(a.itemType)}))}}function It(r){let n=JSON.parse(r);return {components:n.message.tree.flat(1/0).filter(a=>a.offerer!=="0x0000000000000000000000000000000000000000").map(a=>({...a,orderType:gt(a.orderType),salt:toBeHex(BigInt(a.salt)),offer:a.offer.map(c=>({...c,itemType:Ie(c.itemType)})),consideration:a.consideration.map(c=>({...c,itemType:Ie(c.itemType)}))})),types:n.types,value:n.message}}function Tt(r,n){let l=yt(n);return n.map((a,c)=>l.getEncodedProofAndSignature(c,r))}function br(r){switch(r.type){case"NATIVE":throw new Error("NATIVE items are not supported in the offer");case"ERC20":return {itemType:1 .valueOf(),token:r.contract_address,identifierOrCriteria:"0",startAmount:r.amount,endAmount:r.amount};case"ERC721":return {itemType:2 .valueOf(),token:r.contract_address,identifierOrCriteria:r.token_id,startAmount:"1",endAmount:"1"};case"ERC1155":return {itemType:3 .valueOf(),token:r.contract_address,identifierOrCriteria:r.token_id,startAmount:r.amount,endAmount:r.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 U()}}function Sr(r,n){switch(r.type){case"NATIVE":return {itemType:0 .valueOf(),startAmount:r.amount,endAmount:r.amount,token:ZeroAddress,identifierOrCriteria:"0",recipient:n};case"ERC20":return {itemType:1 .valueOf(),startAmount:r.amount,endAmount:r.amount,token:r.contract_address,identifierOrCriteria:"0",recipient:n};case"ERC721":return {itemType:2 .valueOf(),startAmount:"1",endAmount:"1",token:r.contract_address,identifierOrCriteria:r.token_id,recipient:n};case"ERC1155":return {itemType:3 .valueOf(),startAmount:r.amount,endAmount:r.amount,token:r.contract_address,identifierOrCriteria:r.token_id,recipient:n};case"ERC721_COLLECTION":return {itemType:4 .valueOf(),startAmount:r.amount,endAmount:r.amount,token:r.contract_address,identifierOrCriteria:"0",recipient:n};case"ERC1155_COLLECTION":return {itemType:5 .valueOf(),startAmount:r.amount,endAmount:r.amount,token:r.contract_address,identifierOrCriteria:"0",recipient:n};default:return U()}}function Ae(r){let n=r.sell.map(br),l=r.buy.map(o=>Sr(o,r.account_address)),a=function(o){switch(o){case H.type.LISTING:return l[0];case H.type.BID:case H.type.COLLECTION_BID:return n[0];default:return U()}}(r.type),c=function(o){switch(o){case V.order_type.FULL_RESTRICTED:return 2;case V.order_type.PARTIAL_RESTRICTED:return 3;default:return U()}}(r.protocol_data.order_type),p=r.fees.map(o=>({amount:o.amount,itemType:a.itemType,recipient:o.recipient_address,token:a.token,identifierOrCriteria:a.identifierOrCriteria}));return {orderComponents:{offerer:r.account_address,zone:r.protocol_data.zone_address,offer:n,consideration:l,orderType:c.valueOf(),startTime:Math.round(new Date(r.start_at).getTime()/1e3).toString(),endTime:Math.round(new Date(r.end_at).getTime()/1e3).toString(),zoneHash:ZeroHash,salt:r.salt,conduitKey:ZeroHash,counter:r.protocol_data.counter,totalOriginalConsiderationItems:l.length},tips:p}}function z(r,n,l){return async()=>{let a=await r.buildTransaction(),c={to:a.to,from:l,type:a.type,maxFeePerGas:a.maxFeePerGas?BigInt(a.maxFeePerGas):void 0,maxPriorityFeePerGas:a.maxPriorityFeePerGas?BigInt(a.maxPriorityFeePerGas):void 0,value:a.value?BigInt(a.value):void 0,data:a.data,nonce:a.nonce,chainId:n};return c.gasLimit=BigInt(await r.estimateGas()),c.gasLimit+=c.gasLimit/BigInt(5),c}}function Ot(r){switch(r.type){case"ERC20":return {token:r.contractAddress,amount:r.amount};case"ERC721":return {itemType:2 .valueOf(),token:r.contractAddress,identifier:r.tokenId};case"ERC1155":return {itemType:3 .valueOf(),token:r.contractAddress,identifier:r.tokenId,amount:r.amount};default:return U()}}function _t(r,n){switch(r.type){case"NATIVE":return {amount:r.amount,recipient:n};case"ERC20":return {token:r.contractAddress,amount:r.amount,recipient:n};case"ERC721":return {itemType:2 .valueOf(),token:r.contractAddress,identifier:r.tokenId,recipient:n};case"ERC1155":return {itemType:3 .valueOf(),token:r.contractAddress,identifier:r.tokenId,amount:r.amount,recipient:n};case"ERC721_COLLECTION":return {itemType:2 .valueOf(),token:r.contractAddress,amount:r.amount,identifiers:[],recipient:n};case"ERC1155_COLLECTION":return {itemType:3 .valueOf(),token:r.contractAddress,amount:r.amount,identifiers:[],recipient:n};default:return U()}}var Oe=class r{constructor(n,l,a,c,p){this.seaportLibFactory=n;this.provider=l;this.seaportContractAddress=a;this.zoneContractAddress=c;this.rateLimitingKey=p;}async prepareBulkSeaportOrders(n,l){let{actions:a}=await this.createSeaportOrders(n,l),c=a.filter(g=>g.type==="approval"),p=await this.provider.getNetwork(),o=c.map(g=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:z(g.transactionMethods,p.chainId,n)})),h=a.find(g=>g.type==="createBulk");if(!h)throw new Error("No create bulk order action found");let E=await h.getMessageToSign(),{components:f,types:y,value:R}=It(E);return o.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(y,R)}),{actions:o,preparedOrders:f.map(g=>({orderComponents:g,orderHash:this.getSeaportLib().getOrderHash(g)}))}}async prepareSeaportOrder(n,l,a,c,p,o){let{actions:h}=await this.createSeaportOrder(n,l,a,c,p,o),E=[],f=h.find(C=>C.type==="approval");f&&E.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:z(f.transactionMethods,(await this.provider.getNetwork()).chainId,n)});let y=h.find(C=>C.type==="create");if(!y)throw new Error("No create order action found");let R=await y.getMessageToSign(),g=Rt(R);return E.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromOrderComponents(g)}),{actions:E,orderComponents:g,orderHash:this.getSeaportLib().getOrderHash(g)}}async fulfillOrder(n,l,a,c,p){let{orderComponents:o,tips:h}=Ae(n),E=this.getSeaportLib(n),f=(await this.provider.getNetwork()).chainId,y={order:{parameters:o,signature:n.signature},unitsToFill:c,extraData:a,tips:h};p&&(y.considerationCriteria=p);let{actions:R}=await E.fulfillOrders({accountAddress:l,fulfillOrderDetails:[y]}),g=[],C=R.filter(_=>_.type==="approval");C.length>0&&C.forEach(_=>{g.push({type:"TRANSACTION",buildTransaction:z(_.transactionMethods,f,l),purpose:"APPROVAL"});});let I=R.find(_=>_.type==="exchange");if(!I)throw new Error("No exchange action found");return g.push({type:"TRANSACTION",buildTransaction:z(I.transactionMethods,f,l),purpose:"FULFILL_ORDER"}),{actions:g,expiration:r.getExpirationISOTimeFromExtraData(a),order:le(n)}}async fulfillBulkOrders(n,l){let a=n.map(f=>{let{orderComponents:y,tips:R}=Ae(f.order),g={order:{parameters:y,signature:f.order.signature},unitsToFill:f.unitsToFill,extraData:f.extraData,tips:R};return f.considerationCriteria&&f.considerationCriteria.length>0&&(g.considerationCriteria=f.considerationCriteria),g}),{actions:c}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:a,accountAddress:l}),p=[],o=c.filter(f=>f.type==="approval"),h=(await this.provider.getNetwork()).chainId;o.length>0&&o.forEach(f=>{p.push({type:"TRANSACTION",buildTransaction:z(f.transactionMethods,h,l),purpose:"APPROVAL"});});let E=c.find(f=>f.type==="exchange");if(!E)throw new Error("No exchange action found");return p.push({type:"TRANSACTION",buildTransaction:z(E.transactionMethods,(await this.provider.getNetwork()).chainId,l),purpose:"FULFILL_ORDER"}),{actions:p,expiration:a.map(f=>r.getExpirationISOTimeFromExtraData(f.extraData)).reduce((f,y)=>new Date(f)<new Date(y)?f:y)}}async cancelOrders(n,l){let a=n.map(o=>Ae(o).orderComponents),p=await this.getSeaportLib(n[0]).cancelOrders(a,l);return {type:"TRANSACTION",buildTransaction:z(p,(await this.provider.getNetwork()).chainId,l),purpose:"CANCEL"}}createSeaportOrders(n,l){return this.getSeaportLib().createBulkOrders(l.map(c=>{let{offerItem:p,considerationItem:o,allowPartialFills:h,orderStart:E,orderExpiry:f}=c;return {allowPartialFills:h,offer:[Ot(p)],consideration:[_t(o,n)],startTime:(E.getTime()/1e3).toFixed(0),endTime:(f.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),n)}createSeaportOrder(n,l,a,c,p,o){return this.getSeaportLib().createOrder({allowPartialFills:c,offer:[Ot(l)],consideration:[_t(a,n)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(o.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},n)}async getTypedDataFromBulkOrderComponents(n,l){delete n.EIP712Domain;let{chainId:a}=await this.provider.getNetwork();return {domain:{name:qe,version:Y,chainId:a,verifyingContract:this.seaportContractAddress},types:n,value:l}}async getTypedDataFromOrderComponents(n){let{chainId:l}=await this.provider.getNetwork();return {domain:{name:qe,version:Y,chainId:l,verifyingContract:this.seaportContractAddress},types:Ee,value:n}}getSeaportLib(n){let l=n?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(l)}static getExpirationISOTimeFromExtraData(n){let l=n.slice(44,60),a=parseInt(l,16);return new Date(a*1e3).toISOString()}};function _e(r){switch(r.itemType){case 0:return {type:"NATIVE",amount:r.startAmount};case 1:return {type:"ERC20",contract_address:r.token,amount:r.startAmount};case 2:return {type:"ERC721",contract_address:r.token,token_id:r.identifierOrCriteria};case 3:return {type:"ERC1155",contract_address:r.token,token_id:r.identifierOrCriteria,amount:r.startAmount};case 4:return {type:"ERC721_COLLECTION",contract_address:r.token,amount:r.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:r.token,amount:r.startAmount};default:return U(r.itemType)}}function $e(r){if(r.itemType!==1)throw new Error(`Expected ERC20 item, got ${r.itemType}`);return {type:"ERC20",contract_address:r.token,amount:r.startAmount}}function Bt(r){switch(r.itemType){case 4:return {type:"ERC721_COLLECTION",contract_address:r.token,amount:r.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:r.token,amount:r.startAmount};case 1:case 0:case 2:case 3:throw new Error(`Unsupported item type ${r.itemType}`);default:return U(r.itemType)}}function Be(r){switch(r){case 2:return V.order_type.FULL_RESTRICTED;case 3:return V.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${r}`);default:return U()}}var we=class{constructor(n,l,a){this.orderbookService=n;this.chainName=l;this.seaportAddress=a;}async fulfillmentData(n){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:n})}async getListing(n){return this.orderbookService.getListing({chainName:this.chainName,listingId:n})}async getBid(n){return this.orderbookService.getBid({chainName:this.chainName,bidId:n})}async getCollectionBid(n){return this.orderbookService.getCollectionBid({chainName:this.chainName,collectionBidId:n})}async getTrade(n){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:n})}async listListings(n){return this.orderbookService.listListings({chainName:this.chainName,...n})}async listBids(n){return this.orderbookService.listBids({chainName:this.chainName,...n})}async listCollectionBids(n){return this.orderbookService.listCollectionBids({chainName:this.chainName,...n})}async listTrades(n){return this.orderbookService.listTrades({chainName:this.chainName,...n})}async cancelOrders(n,l,a){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:l,orders:n,signature:a}})}async createListing({orderHash:n,orderComponents:l,orderSignature:a,makerFees:c}){if(l.offer.length!==1)throw new Error("Only one item can be listed for a listing");if(l.consideration.length!==1)throw new Error("Only one item can be used as currency for a listing");if(![2,3].includes(l.offer[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be listed");if(![0,1].includes(l.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:l.offerer,buy:l.consideration.map(_e),fees:c.map(p=>({type:v.type.MAKER_ECOSYSTEM,amount:p.amount,recipient_address:p.recipientAddress})),end_at:new Date(parseInt(`${l.endTime.toString()}000`,10)).toISOString(),order_hash:n,protocol_data:{order_type:Be(l.orderType),zone_address:l.zone,seaport_address:this.seaportAddress,seaport_version:Y,counter:l.counter.toString()},salt:l.salt,sell:l.offer.map(_e),signature:a,start_at:new Date(parseInt(`${l.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:n,orderComponents:l,orderSignature:a,makerFees:c}){if(l.offer.length!==1)throw new Error("Only one item can be listed for a bid");if(l.consideration.length!==1)throw new Error("Only one item can be used as currency for a bid");if(1!==l.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a bid");if(![2,3].includes(l.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be bid against");return this.orderbookService.createBid({chainName:this.chainName,requestBody:{account_address:l.offerer,buy:l.consideration.map(_e),fees:c.map(p=>({type:v.type.MAKER_ECOSYSTEM,amount:p.amount,recipient_address:p.recipientAddress})),end_at:new Date(parseInt(`${l.endTime.toString()}000`,10)).toISOString(),order_hash:n,protocol_data:{order_type:Be(l.orderType),zone_address:l.zone,seaport_address:this.seaportAddress,seaport_version:Y,counter:l.counter.toString()},salt:l.salt,sell:l.offer.map($e),signature:a,start_at:new Date(parseInt(`${l.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:n,orderComponents:l,orderSignature:a,makerFees:c}){if(l.offer.length!==1)throw new Error("Only one item can be listed for a collection bid");if(l.consideration.length!==1)throw new Error("Only one item can be used as currency for a collection bid");if(1!==l.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a collection bid");if(![4,5].includes(l.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:l.offerer,buy:l.consideration.map(Bt),fees:c.map(p=>({type:v.type.MAKER_ECOSYSTEM,amount:p.amount,recipient_address:p.recipientAddress})),end_at:new Date(parseInt(`${l.endTime.toString()}000`,10)).toISOString(),order_hash:n,protocol_data:{order_type:Be(l.orderType),zone_address:l.zone,seaport_address:this.seaportAddress,seaport_version:Y,counter:l.counter.toString()},salt:l.salt,sell:l.offer.map($e),signature:a,start_at:new Date(parseInt(`${l.startTime.toString()}000`,10)).toISOString()}})}};var be=class{constructor(n,l,a,c){this.chainName=l;this.seaportAddress=a;this.orderbookClient=new oe({BASE:n,HEADERS:c?{"x-api-key":c}:void 0});}orderbookClient;create(){return new we(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var Pr="imtbl-zkevm-testnet",Nr="imtbl-zkevm-mainnet";function Se(r,n){let l=new FetchRequest(r);return n&&l.setHeader("x-api-key",n),new JsonRpcProvider(l)}function bt(r){switch(r.baseConfig.environment){case Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:Pr,provider:Se("https://rpc.testnet.immutable.com",r.baseConfig.rateLimitingKey)};case Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:Nr,provider:Se("https://rpc.immutable.com",r.baseConfig.rateLimitingKey)};default:return null}}var Le=class{constructor(n,l){this.defaultSeaportContractAddress=n;this.provider=l;}create(n){let l=n??this.defaultSeaportContractAddress,a=this.provider;return a.getSigner=async function(p){p==null&&(p=0);let o=this.send("eth_accounts",[]);if(typeof p=="number"){let h=await o;if(p>=h.length)throw new Error("no such account");return new JsonRpcSigner(this,h[p])}return new JsonRpcSigner(this,p)},new Seaport(a,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:l}})}};var Ve=class r{apiClient;seaport;orderbookConfig;constructor(n){let a={...bt(n),...n.overrides};if(n.overrides?.jsonRpcProviderUrl&&(a.provider=Se(n.overrides?.jsonRpcProviderUrl,n.baseConfig.rateLimitingKey)),!a)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=a;let{apiEndpoint:c,chainName:p}=this.orderbookConfig;if(!c)throw new Error("API endpoint must be provided");this.apiClient=new be(c,p,this.orderbookConfig.seaportContractAddress,n.baseConfig.rateLimitingKey).create();let o=new Le(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new Oe(o,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,n.baseConfig.rateLimitingKey);}static defaultOrderExpiry(){return new Date(Date.now()+1e3*60*60*24*365*2)}config(){return this.orderbookConfig}async getListing(n){let l=await this.apiClient.getListing(n);return {result:W(l.result)}}async getBid(n){let l=await this.apiClient.getBid(n);return {result:se(l.result)}}async getCollectionBid(n){let l=await this.apiClient.getCollectionBid(n);return {result:ae(l.result)}}async getTrade(n){let l=await this.apiClient.getTrade(n);return {result:Fe(l.result)}}async listListings(n){let l=await this.apiClient.listListings(n);return {page:ue(l.page),result:l.result.map(W)}}async listBids(n){let l=await this.apiClient.listBids(n);return {page:ue(l.page),result:l.result.map(se)}}async listCollectionBids(n){let l=await this.apiClient.listCollectionBids(n);return {page:ue(l.page),result:l.result.map(ae)}}async listTrades(n){let l=await this.apiClient.listTrades(n);return {page:ue(l.page),result:l.result.map(Fe)}}async prepareBulkListings({makerAddress:n,listingParams:l}){if(l.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(l.length===1){let o=await this.seaport.prepareSeaportOrder(n,l[0].sell,l[0].buy,l[0].sell.type==="ERC1155",l[0].orderStart||new Date,l[0].orderExpiry||r.defaultOrderExpiry());return {actions:o.actions,completeListings:async h=>{let E=await this.createListing({makerFees:l[0].makerFees,orderComponents:o.orderComponents,orderHash:o.orderHash,orderSignature:typeof h=="string"?h:h[0]});return {result:[{success:!0,orderHash:o.orderHash,order:E.result}]}}}}if(await this.orderbookConfig.provider.getCode(n)!=="0x"){track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:n,listingsCount:l.length});let o=await Promise.all(l.map(f=>this.seaport.prepareSeaportOrder(n,f.sell,f.buy,f.sell.type==="ERC1155",f.orderStart||new Date,f.orderExpiry||r.defaultOrderExpiry()))),h=[];return {actions:o.flatMap(f=>{let y=[];return f.actions.forEach(R=>{if(R.type==="TRANSACTION"){let g=f.orderComponents.offer[0].token;h.includes(g)||(h.push(g),y.push(R));}else y.push(R);}),y}),completeListings:async f=>{if(typeof f=="string")throw new Error("A signature per listing must be provided for smart contract wallets");return {result:(await Promise.all(o.map((g,C)=>{let I=f[C];return this.apiClient.createListing({makerFees:l[C].makerFees,orderComponents:g.orderComponents,orderHash:g.orderHash,orderSignature:I}).catch(()=>{})}))).map((g,C)=>({success:!!g,orderHash:o[C].orderHash,order:g?W(g.result):void 0}))}}}}track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:n,listingsCount:l.length});let{actions:c,preparedOrders:p}=await this.seaport.prepareBulkSeaportOrders(n,l.map(o=>({offerItem:o.sell,considerationItem:o.buy,allowPartialFills:o.sell.type==="ERC1155",orderStart:o.orderStart||new Date,orderExpiry:o.orderExpiry||r.defaultOrderExpiry()})));return {actions:c,completeListings:async o=>{let h=typeof o=="object";if(h&&o.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let E=p.map(g=>g.orderComponents),f=h?o[0]:o,y=Tt(f,E);return {result:(await Promise.all(E.map((g,C)=>{let I=y[C],_=p[C],L=l[C];return this.apiClient.createListing({orderComponents:g,orderHash:_.orderHash,orderSignature:I,makerFees:L.makerFees}).catch(()=>{})}))).map((g,C)=>({success:!!g,orderHash:p[C].orderHash,order:g?W(g.result):void 0}))}}}}async prepareListing({makerAddress:n,sell:l,buy:a,orderStart:c,orderExpiry:p}){return this.seaport.prepareSeaportOrder(n,l,a,l.type==="ERC1155",c||new Date,p||r.defaultOrderExpiry())}async createListing(n){let l=await this.apiClient.createListing(n);return {result:W(l.result)}}async prepareBid({makerAddress:n,sell:l,buy:a,orderStart:c,orderExpiry:p}){return this.seaport.prepareSeaportOrder(n,l,a,a.type==="ERC1155",c||new Date,p||r.defaultOrderExpiry())}async createBid(n){let l=await this.apiClient.createBid(n);return {result:se(l.result)}}async prepareCollectionBid({makerAddress:n,sell:l,buy:a,orderStart:c,orderExpiry:p}){return this.seaport.prepareSeaportOrder(n,l,a,!0,c||new Date,p||r.defaultOrderExpiry())}async createCollectionBid(n){let l=await this.apiClient.createCollectionBid(n);return {result:ae(l.result)}}async fulfillOrder(n,l,a,c,p){let o={order_id:n,taker_address:l,fees:a.map(R=>({type:v.type.TAKER_ECOSYSTEM,amount:R.amount,recipient_address:R.recipientAddress}))},h=p?[{identifier:p,proof:[]}]:void 0;p&&(o.token_id=p);let E=await this.apiClient.fulfillmentData([o]);if(E.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment data: ${E.result.unfulfillable_orders[0].reason}`);if(E.result.fulfillable_orders?.length!==1)throw new Error("unexpected fulfillable order result length");let f=E.result.fulfillable_orders[0].extra_data,y=E.result.fulfillable_orders[0].order;if(y.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${y.status}`);return this.seaport.fulfillOrder(y,l,f,c,h)}async fulfillBulkOrders(n,l){let a=n.map(p=>{let o="listingId"in p;return {orderId:o?p.listingId:p.orderId,takerFees:p.takerFees,amountToFill:p.amountToFill,tokenId:o?void 0:p.tokenId}}),c=await this.apiClient.fulfillmentData(a.map(p=>({order_id:p.orderId,taker_address:l,fees:p.takerFees.map(o=>({type:v.type.TAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),token_id:p?.tokenId})));try{let p=c.result.fulfillable_orders.map(o=>{let h=a.find(f=>f.orderId===o.order.id&&f.tokenId===o.token_id);if(!h){let f=`Could not find order for order ${o.order.id}`;throw o.token_id&&(f+=` and token ID ${o.token_id}`),new Error(f)}let E=[];return h.tokenId&&E.push({identifier:h.tokenId,proof:[]}),{extraData:o.extra_data,order:o.order,unitsToFill:h.amountToFill,considerationCriteria:E}});return {...await this.seaport.fulfillBulkOrders(p,l),fulfillableOrders:c.result.fulfillable_orders.map(o=>le(o.order)),unfulfillableOrders:c.result.unfulfillable_orders.map(o=>({orderId:o.order_id,tokenId:o.token_id,reason:o.reason})),sufficientBalance:!0}}catch(p){if(String(p).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:c.result.fulfillable_orders.map(o=>le(o.order)),unfulfillableOrders:c.result.unfulfillable_orders.map(o=>({orderId:o.order_id,reason:o.reason})),sufficientBalance:!1};throw p}}async prepareOrderCancellations(n){let a={name:"imtbl-order-book",chainId:(await this.orderbookConfig.provider.getNetwork()).chainId,verifyingContract:this.orderbookConfig.seaportContractAddress},c={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},p={orders:n.map(o=>({id:o}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:a,types:c,value:p}}}}async cancelOrders(n,l,a){return this.apiClient.cancelOrders(n,l,a)}async cancelOrdersOnChain(n,l){let a=Promise.all(n.map(y=>this.apiClient.getListing(y).catch(R=>{if(R.status!==404)throw R}))),c=Promise.all(n.map(y=>this.apiClient.getBid(y).catch(R=>{if(R.status!==404)throw R}))),p=Promise.all(n.map(y=>this.apiClient.getCollectionBid(y).catch(R=>{if(R.status!==404)throw R}))),o=[await Promise.all([a,c,p])].flat(2).filter(y=>y!==void 0).map(y=>y.result);if(o.length!==n.length){let y=n.filter(R=>!o.some(g=>g.id===R));throw new Error(`Orders ${y} not found`)}for(let y of o)if(y.account_address!==l.toLowerCase())throw new Error(`Only account ${y.account_address} can cancel order ${y.id}`);let h=o.map(y=>y.protocol_data.seaport_address);if(new Set(h).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(o,l)}}};var Dr={estimatedFulfillmentGasGwei:4e5};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
10
10
 
11
- export { ve as ActionType, cr as FeeType, Ce as OrderStatusName, Ve as Orderbook, Ue as SignablePurpose, ct as TransactionPurpose, Dr as constants };
11
+ export { ve as ActionType, pr as FeeType, Ce as OrderStatusName, Ve as Orderbook, Ue as SignablePurpose, pt as TransactionPurpose, Dr as constants };
@@ -13,7 +13,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
13
  var le__default = /*#__PURE__*/_interopDefault(le);
14
14
  var pe__default = /*#__PURE__*/_interopDefault(pe);
15
15
 
16
- var b=class{constructor(t){this.config=t;}};var T=class extends Error{url;status;statusText;body;request;constructor(t,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=t;}};var D=class extends Error{constructor(t){super(t),this.name="CancelError";}get isCancelled(){return !0}},L=class{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(t){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((r,s)=>{this._resolve=r,this._reject=s;let n=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(d));},i=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(d));},o=d=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(d);};return Object.defineProperty(o,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(o,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(o,"isCancelled",{get:()=>this._isCancelled}),t(n,i,o)});}then(t,r){return this._promise.then(t,r)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let t of this._cancelHandlers)t();}catch(t){console.warn("Cancellation threw an error",t);return}this._cancelHandlers.length=0,this._reject?.(new D("Request aborted"));}}get isCancelled(){return this._isCancelled}};var ee=e=>e!=null,F=e=>typeof e=="string",Q=e=>F(e)&&e!=="",ce=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof pe__default.default,qe=e=>e>=200&&e<300,He=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Me=e=>{let t=[],r=(n,i)=>{t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`);},s=(n,i)=>{ee(i)&&(Array.isArray(i)?i.forEach(o=>{s(n,o);}):typeof i=="object"?Object.entries(i).forEach(([o,d])=>{s(`${n}[${o}]`,d);}):r(n,i));};return Object.entries(e).forEach(([n,i])=>{s(n,i);}),t.length>0?`?${t.join("&")}`:""},Ve=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(i,o)=>t.path?.hasOwnProperty(o)?r(String(t.path[o])):i),n=`${e.BASE}${s}`;return t.query?`${n}${Me(t.query)}`:n},Ue=e=>{if(e.formData){let t=new pe__default.default,r=(s,n)=>{F(n)||ce(n)?t.append(s,n):t.append(s,JSON.stringify(n));};return Object.entries(e.formData).filter(([s,n])=>ee(n)).forEach(([s,n])=>{Array.isArray(n)?n.forEach(i=>r(s,i)):r(s,n);}),t}},v=async(e,t)=>typeof t=="function"?t(e):t,ze=async(e,t,r)=>{let s=await v(t,e.TOKEN),n=await v(t,e.USERNAME),i=await v(t,e.PASSWORD),o=await v(t,e.HEADERS),d=typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...o,...t.headers,...d}).filter(([a,l])=>ee(l)).reduce((a,[l,u])=>({...a,[l]:String(u)}),{});if(Q(s)&&(p.Authorization=`Bearer ${s}`),Q(n)&&Q(i)){let a=He(`${n}:${i}`);p.Authorization=`Basic ${a}`;}return t.body&&(t.mediaType?p["Content-Type"]=t.mediaType:ce(t.body)?p["Content-Type"]=t.body.type||"application/octet-stream":F(t.body)?p["Content-Type"]="text/plain":Fe(t.body)||(p["Content-Type"]="application/json")),p},je=e=>{if(e.body)return e.body},$e=async(e,t,r,s,n,i,o)=>{let d=le__default.default.CancelToken.source(),p={url:r,headers:i,data:s??n,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:d.token};o(()=>d.cancel("The user aborted a request."));try{return await le__default.default.request(p)}catch(a){let l=a;if(l.response)return l.response;throw a}},Ge=(e,t)=>{if(t){let r=e.headers[t];if(F(r))return r}},We=e=>{if(e.status!==204)return e.data},Ke=(e,t)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(s)throw new T(e,t,s);if(!t.ok)throw new T(e,t,"Generic Error")},ue=(e,t)=>new L(async(r,s,n)=>{try{let i=Ve(e,t),o=Ue(t),d=je(t),p=await ze(e,t,o);if(!n.isCancelled){let a=await $e(e,t,i,d,o,p,n),l=We(a),u=Ge(a,t.responseHeader),c={url:i,ok:qe(a.status),status:a.status,statusText:a.statusText,body:u??l};Ke(t,c),r(c.body);}}catch(i){s(i);}});var q=class extends b{constructor(t){super(t);}request(t){return ue(this.config,t)}};var S=class{constructor(t){this.httpRequest=t;}cancelOrders({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",401:"Unauthorised Request (401)",404:"The specified resource was not found (404)",429:"Too Many Requests (429)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listListings({chainName:t,status:r,sellItemContractAddress:s,buyItemType:n,buyItemContractAddress:i,accountAddress:o,sellItemMetadataId:d,sellItemTokenId:p,fromUpdatedAt:a,pageSize:l,sortBy:u,sortDirection:c,pageCursor:m}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},query:{status:r,sell_item_contract_address:s,buy_item_type:n,buy_item_contract_address:i,account_address:o,sell_item_metadata_id:d,sell_item_token_id:p,from_updated_at:a,page_size:l,sort_by:u,sort_direction:c,page_cursor:m},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,buyItemMetadataId:o,buyItemTokenId:d,fromUpdatedAt:p,pageSize:a,sortBy:l,sortDirection:u,pageCursor:c}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,buy_item_metadata_id:o,buy_item_token_id:d,from_updated_at:p,page_size:a,sort_by:l,sort_direction:u,page_cursor:c},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listCollectionBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,fromUpdatedAt:o,pageSize:d,sortBy:p,sortDirection:a,pageCursor:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,from_updated_at:o,page_size:d,sort_by:p,sort_direction:a,page_cursor:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createCollectionBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}getListing({chainName:t,listingId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:t,listing_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getBid({chainName:t,bidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids/{bid_id}",path:{chain_name:t,bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getCollectionBid({chainName:t,collectionBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids/{collection_bid_id}",path:{chain_name:t,collection_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:t,accountAddress:r,sellItemContractAddress:s,fromIndexedAt:n,pageSize:i,sortBy:o,sortDirection:d,pageCursor:p}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:t},query:{account_address:r,sell_item_contract_address:s,from_indexed_at:n,page_size:i,sort_by:o,sort_direction:d,page_cursor:p},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:t,tradeId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:t,trade_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}};var P=class{orders;request;constructor(t,r=q){this.request=new r({BASE:t?.BASE??"https://api.immutable.com",VERSION:t?.VERSION??"1.0.0",WITH_CREDENTIALS:t?.WITH_CREDENTIALS??!1,CREDENTIALS:t?.CREDENTIALS??"include",TOKEN:t?.TOKEN,USERNAME:t?.USERNAME,PASSWORD:t?.PASSWORD,HEADERS:t?.HEADERS,ENCODE_PATH:t?.ENCODE_PATH}),this.orders=new S(this.request);}};var me;(t=>{(i=>(i.ON_CHAIN="ON_CHAIN",i.OFF_CHAIN="OFF_CHAIN",i.UNDERFUNDED="UNDERFUNDED"))(t.cancellation_type||={});})(me||={});var fe;(t=>{(s=>s.FILLED="FILLED")(t.reason_code||={});})(fe||={});var f;(t=>{(o=>(o.ROYALTY="ROYALTY",o.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",o.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",o.PROTOCOL="PROTOCOL"))(t.type||={});})(f||={});var R;(t=>{(i=>(i.LISTING="LISTING",i.BID="BID",i.COLLECTION_BID="COLLECTION_BID"))(t.type||={});})(R||={});var H=(o=>(o.PENDING="PENDING",o.ACTIVE="ACTIVE",o.INACTIVE="INACTIVE",o.FILLED="FILLED",o.EXPIRED="EXPIRED",o.CANCELLED="CANCELLED",o))(H||{});var y;(t=>{(n=>(n.FULL_RESTRICTED="FULL_RESTRICTED",n.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(t.order_type||={});})(y||={});function C(e){throw new Error("Unreachable")}function h(e){if(e.type!==R.type.LISTING)throw new Error("Order type must be LISTING");let t=e.sell.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Listing sell items must either ERC721 or ERC1155")}),r=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Listing buy items must be either NATIVE or ERC20")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function x(e){if(e.type!==R.type.BID)throw new Error("Order type must be BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Bid buy items must either ERC721 or ERC1155")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function B(e){if(e.type!==R.type.COLLECTION_BID)throw new Error("Order type must be COLLECTION_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function N(e){switch(e.type){case R.type.LISTING:return h(e);case R.type.BID:return x(e);case R.type.COLLECTION_BID:return B(e);default:return C(e.type)}}function te(e){let t=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Buy items must be NATIVE, ERC20, ERC721 or ERC1155")}),r=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Sell items must be ERC20, ERC721 or ERC1155")});return {id:e.id,orderId:e.order_id,buy:t,sell:r,buyerFees:e.buyer_fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),chain:e.chain,indexedAt:e.indexed_at,blockchainMetadata:{blockNumber:e.blockchain_metadata.block_number,logIndex:e.blockchain_metadata.log_index,transactionHash:e.blockchain_metadata.transaction_hash,transactionIndex:e.blockchain_metadata.transaction_index},buyerAddress:e.buyer_address,makerAddress:e.maker_address,sellerAddress:e.seller_address,takerAddress:e.taker_address}}function k(e){return {nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}var Ye=(n=>(n[n.MAKER_ECOSYSTEM=f.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",n[n.TAKER_ECOSYSTEM=f.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",n[n.PROTOCOL=f.type.PROTOCOL]="PROTOCOL",n[n.ROYALTY=f.type.ROYALTY]="ROYALTY",n))(Ye||{}),re=(r=>(r.TRANSACTION="TRANSACTION",r.SIGNABLE="SIGNABLE",r))(re||{}),Ce=(s=>(s.APPROVAL="APPROVAL",s.FULFILL_ORDER="FULFILL_ORDER",s.CANCEL="CANCEL",s))(Ce||{}),se=(s=>(s.CREATE_LISTING="CREATE_ORDER",s.CREATE_ORDER="CREATE_ORDER",s.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",s))(se||{});var oe="ImmutableSeaport",I="1.5",M={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]};var Je={integer:0,address:ethers.zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},ne=e=>e===void 0?!1:e!=null&&(["string","number"].includes(typeof e)&&BigInt(e)===0n||Array.isArray(e)&&e.every(ne)||typeof e=="object"&&Object.values(e).every(ne)||typeof e=="boolean"&&e===!1);function Ze(e){let[,t]=e.match(/^bytes(\d+)$/)??[];return t?ethers.zeroPadValue("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),Je[e])}var A=class e{constructor(t){this.types=t;for(let r in t){let s=this.getDefaultValue(r);if(this.defaultValues[r]=s,!ne(s))throw new Error(`Got non-empty value for type ${r} in default generator: ${s}`)}}defaultValues={};static from(t,r){let{defaultValues:s}=new e(t);return r?s[r]:s}getDefaultValue(t){if(this.defaultValues[t])return this.defaultValues[t];let r=Ze(t);if(r!==void 0)return r;let s=t.match(/^(.*)(\x5b(\d*)\x5d)$/);if(s){let i=s[1],o=parseInt(s[3]);if(o>0){let d=this.getDefaultValue(i);return Array(o).fill(d)}return []}let n=this.types[t];if(n)return n.reduce((i,{name:o,type:d})=>({...i,[o]:this.getDefaultValue(d)}),{});throw new Error(`unknown type: ${t}`)}};var tt=(e,t)=>Array(e).fill(0).map((r,s)=>t(s)),ie=(e,t)=>tt(Math.ceil(e.length/t),r=>e.slice(r*t,(r+1)*t)),ye=e=>ethers.toBeHex(e.toString("hex")),_=e=>Buffer.from(e.slice(2),"hex"),V=e=>_(ethers.keccak256(e)),rt=e=>V(ethers.concat(e)),w=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),ge=(e,t=!0)=>{if(e.length===0)throw new Error("empty tree");let s=[e.map(n=>{let i=Buffer.isBuffer(n)?n:_(n);return t?V(i):i})];for(;s[s.length-1].length>1;)s.push(st(s[s.length-1]));return s[s.length-1][0]},st=e=>ie(e,2).map(rt);var dt=(e,t)=>new merkletreejs.MerkleTree(e.map(_),V,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:_(t)}),lt=(e,t,r=`0x${"ff".repeat(64)}`)=>ethers.concat([r,`0x${e.toString(16).padStart(6,"0")}`,ethers.AbiCoder.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]),U=class{constructor(t,r,s,n,i){this.types=t;this.rootType=r;this.leafType=s;this.elements=n;this.depth=i;let o=ethers.TypedDataEncoder.from(t);this.encoder=o,this.leafHasher=d=>o.hashStruct(s,d),this.defaultNode=A.from(t,s),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=dt(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:t}=this;return w([...t],this.completedSize,this.defaultNode)}getCompleteLeaves(){let t=this.elements.map(this.leafHasher);return w([...t],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(t){let s=this.getCompleteLeaves()[t],n=this.tree.getHexProof(s,t),i=this.tree.getHexRoot();return {leaf:s,proof:n,root:i}}getEncodedProofAndSignature(t,r){let{proof:s}=this.getProof(t);return lt(t,s,r)}getDataToSign(){let t=this.getCompleteElements();for(;t.length>2;)t=ie(t,2);return t}add(t){this.elements.push(t);}getBulkOrderHash(){let t=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),r=this.getCompleteLeaves().map(_),s=ye(ge(r,!1)),n=ethers.keccak256(ethers.toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(ethers.keccak256(ethers.concat([n,s]))!==t)throw new Error("expected derived bulk order hash to match");return t}};function pt(e){return {...M,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}function ct(e){return Math.max(Math.ceil(Math.log2(e)),1)}function Ie(e,t=0,r=ct(e.length+t)){let s=pt(r),n=A.from(s,"OrderComponents"),i=[...e];return t>0&&(i=[...w([],t,n),...e]),new U(s,"BulkOrder","OrderComponents",i,r)}function Ae(e){if([0,1,2,3].includes(Number(e)))return Number(e);throw new Error(`Unknown order type ${e}`)}function z(e){if([0,1,2,3,4,5].includes(Number(e)))return Number(e);throw new Error(`Unknown item type ${e}`)}function _e(e){let r=JSON.parse(e).message;return {...r,orderType:Ae(r.orderType),salt:ethers.toBeHex(BigInt(r.salt)),offer:r.offer.map(s=>({...s,itemType:z(s.itemType)})),consideration:r.consideration.map(s=>({...s,itemType:z(s.itemType)}))}}function be(e){let t=JSON.parse(e);return {components:t.message.tree.flat(1/0).filter(s=>s.offerer!=="0x0000000000000000000000000000000000000000").map(s=>({...s,orderType:Ae(s.orderType),salt:ethers.toBeHex(BigInt(s.salt)),offer:s.offer.map(n=>({...n,itemType:z(n.itemType)})),consideration:s.consideration.map(n=>({...n,itemType:z(n.itemType)}))})),types:t.types,value:t.message}}function Le(e,t){let r=Ie(t);return t.map((s,n)=>r.getEncodedProofAndSignature(n,e))}function mt(e){switch(e.type){case"NATIVE":throw new Error("NATIVE items are not supported in the offer");case"ERC20":return {itemType:1,token:e.contract_address,identifierOrCriteria:"0",startAmount:e.amount,endAmount:e.amount};case"ERC721":return {itemType:2,token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:"1",endAmount:"1"};case"ERC1155":return {itemType:3,token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:e.amount,endAmount:e.amount};case"ERC721_COLLECTION":throw new Error("ERC721_COLLECTION items are not supported in the offer");case"ERC1155_COLLECTION":throw new Error("ERC1155_COLLECTION items are not supported in the offer");default:return C()}}function ft(e,t){switch(e.type){case"NATIVE":return {itemType:0,startAmount:e.amount,endAmount:e.amount,token:ethers.ZeroAddress,identifierOrCriteria:"0",recipient:t};case"ERC20":return {itemType:1,startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC721":return {itemType:2,startAmount:"1",endAmount:"1",token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC1155":return {itemType:3,startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC721_COLLECTION":return {itemType:4,startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC1155_COLLECTION":return {itemType:5,startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};default:return C()}}function $(e){let t=e.sell.map(mt),r=e.buy.map(o=>ft(o,e.account_address)),s=function(o){switch(o){case R.type.LISTING:return r[0];case R.type.BID:case R.type.COLLECTION_BID:return t[0];default:return C()}}(e.type),n=function(o){switch(o){case y.order_type.FULL_RESTRICTED:return 2;case y.order_type.PARTIAL_RESTRICTED:return 3;default:return C()}}(e.protocol_data.order_type),i=e.fees.map(o=>({amount:o.amount,itemType:s.itemType,recipient:o.recipient_address,token:s.token,identifierOrCriteria:s.identifierOrCriteria}));return {orderComponents:{offerer:e.account_address,zone:e.protocol_data.zone_address,offer:t,consideration:r,orderType:n,startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),zoneHash:ethers.ZeroHash,salt:e.salt,conduitKey:ethers.ZeroHash,counter:e.protocol_data.counter,totalOriginalConsiderationItems:r.length},tips:i}}function g(e,t,r){return async()=>{let s=await e.buildTransaction(),n={to:s.to,from:r,type:s.type,maxFeePerGas:s.maxFeePerGas?BigInt(s.maxFeePerGas):void 0,maxPriorityFeePerGas:s.maxPriorityFeePerGas?BigInt(s.maxPriorityFeePerGas):void 0,value:s.value?BigInt(s.value):void 0,data:s.data,nonce:s.nonce,chainId:t};return n.gasLimit=BigInt(await e.estimateGas()),n.gasLimit+=n.gasLimit/BigInt(5),n}}function Pe(e){switch(e.type){case"ERC20":return {token:e.contractAddress,amount:e.amount};case"ERC721":return {itemType:2,token:e.contractAddress,identifier:e.tokenId};case"ERC1155":return {itemType:3,token:e.contractAddress,identifier:e.tokenId,amount:e.amount};default:return C()}}function xe(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,token:e.contractAddress,identifier:e.tokenId,recipient:t};case"ERC1155":return {itemType:3,token:e.contractAddress,identifier:e.tokenId,amount:e.amount,recipient:t};case"ERC721_COLLECTION":return {itemType:2,token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};case"ERC1155_COLLECTION":return {itemType:3,token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};default:return C()}}var G=class e{constructor(t,r,s,n,i){this.seaportLibFactory=t;this.provider=r;this.seaportContractAddress=s;this.zoneContractAddress=n;this.rateLimitingKey=i;}async prepareBulkSeaportOrders(t,r){let{actions:s}=await this.createSeaportOrders(t,r),n=s.filter(c=>c.type==="approval"),i=await this.provider.getNetwork(),o=n.map(c=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(c.transactionMethods,i.chainId,t)})),d=s.find(c=>c.type==="createBulk");if(!d)throw new Error("No create bulk order action found");let p=await d.getMessageToSign(),{components:a,types:l,value:u}=be(p);return o.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(l,u)}),{actions:o,preparedOrders:a.map(c=>({orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}))}}async prepareSeaportOrder(t,r,s,n,i,o){let{actions:d}=await this.createSeaportOrder(t,r,s,n,i,o),p=[],a=d.find(m=>m.type==="approval");a&&p.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(a.transactionMethods,(await this.provider.getNetwork()).chainId,t)});let l=d.find(m=>m.type==="create");if(!l)throw new Error("No create order action found");let u=await l.getMessageToSign(),c=_e(u);return p.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromOrderComponents(c)}),{actions:p,orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}}async fulfillOrder(t,r,s,n,i){let{orderComponents:o,tips:d}=$(t),p=this.getSeaportLib(t),a=(await this.provider.getNetwork()).chainId,l={order:{parameters:o,signature:t.signature},unitsToFill:n,extraData:s,tips:d};i&&(l.considerationCriteria=i);let{actions:u}=await p.fulfillOrders({accountAddress:r,fulfillOrderDetails:[l]}),c=[],m=u.filter(E=>E.type==="approval");m.length>0&&m.forEach(E=>{c.push({type:"TRANSACTION",buildTransaction:g(E.transactionMethods,a,r),purpose:"APPROVAL"});});let O=u.find(E=>E.type==="exchange");if(!O)throw new Error("No exchange action found");return c.push({type:"TRANSACTION",buildTransaction:g(O.transactionMethods,a,r),purpose:"FULFILL_ORDER"}),{actions:c,expiration:e.getExpirationISOTimeFromExtraData(s),order:N(t)}}async fulfillBulkOrders(t,r){let s=t.map(a=>{let{orderComponents:l,tips:u}=$(a.order),c={order:{parameters:l,signature:a.order.signature},unitsToFill:a.unitsToFill,extraData:a.extraData,tips:u};return a.considerationCriteria&&a.considerationCriteria.length>0&&(c.considerationCriteria=a.considerationCriteria),c}),{actions:n}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:s,accountAddress:r}),i=[],o=n.filter(a=>a.type==="approval"),d=(await this.provider.getNetwork()).chainId;o.length>0&&o.forEach(a=>{i.push({type:"TRANSACTION",buildTransaction:g(a.transactionMethods,d,r),purpose:"APPROVAL"});});let p=n.find(a=>a.type==="exchange");if(!p)throw new Error("No exchange action found");return i.push({type:"TRANSACTION",buildTransaction:g(p.transactionMethods,(await this.provider.getNetwork()).chainId,r),purpose:"FULFILL_ORDER"}),{actions:i,expiration:s.map(a=>e.getExpirationISOTimeFromExtraData(a.extraData)).reduce((a,l)=>new Date(a)<new Date(l)?a:l)}}async cancelOrders(t,r){let s=t.map(o=>$(o).orderComponents),i=await this.getSeaportLib(t[0]).cancelOrders(s,r);return {type:"TRANSACTION",buildTransaction:g(i,(await this.provider.getNetwork()).chainId,r),purpose:"CANCEL"}}createSeaportOrders(t,r){return this.getSeaportLib().createBulkOrders(r.map(n=>{let{offerItem:i,considerationItem:o,allowPartialFills:d,orderStart:p,orderExpiry:a}=n;return {allowPartialFills:d,offer:[Pe(i)],consideration:[xe(o,t)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(a.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),t)}createSeaportOrder(t,r,s,n,i,o){return this.getSeaportLib().createOrder({allowPartialFills:n,offer:[Pe(r)],consideration:[xe(s,t)],startTime:(i.getTime()/1e3).toFixed(0),endTime:(o.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},t)}async getTypedDataFromBulkOrderComponents(t,r){delete t.EIP712Domain;let{chainId:s}=await this.provider.getNetwork();return {domain:{name:oe,version:I,chainId:s,verifyingContract:this.seaportContractAddress},types:t,value:r}}async getTypedDataFromOrderComponents(t){let{chainId:r}=await this.provider.getNetwork();return {domain:{name:oe,version:I,chainId:r,verifyingContract:this.seaportContractAddress},types:M,value:t}}getSeaportLib(t){let r=t?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(r)}static getExpirationISOTimeFromExtraData(t){let r=t.slice(44,60),s=parseInt(r,16);return new Date(s*1e3).toISOString()}};function W(e){switch(e.itemType){case 0:return {type:"NATIVE",amount:e.startAmount};case 1:return {type:"ERC20",contract_address:e.token,amount:e.startAmount};case 2:return {type:"ERC721",contract_address:e.token,token_id:e.identifierOrCriteria};case 3:return {type:"ERC1155",contract_address:e.token,token_id:e.identifierOrCriteria,amount:e.startAmount};case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};default:return C(e.itemType)}}function ae(e){if(e.itemType!==1)throw new Error(`Expected ERC20 item, got ${e.itemType}`);return {type:"ERC20",contract_address:e.token,amount:e.startAmount}}function Be(e){switch(e.itemType){case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};case 1:case 0:case 2:case 3:throw new Error(`Unsupported item type ${e.itemType}`);default:return C(e.itemType)}}function K(e){switch(e){case 2:return y.order_type.FULL_RESTRICTED;case 3:return y.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${e}`);default:return C()}}var Y=class{constructor(t,r,s){this.orderbookService=t;this.chainName=r;this.seaportAddress=s;}async fulfillmentData(t){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:t})}async getListing(t){return this.orderbookService.getListing({chainName:this.chainName,listingId:t})}async getBid(t){return this.orderbookService.getBid({chainName:this.chainName,bidId:t})}async getCollectionBid(t){return this.orderbookService.getCollectionBid({chainName:this.chainName,collectionBidId:t})}async getTrade(t){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:t})}async listListings(t){return this.orderbookService.listListings({chainName:this.chainName,...t})}async listBids(t){return this.orderbookService.listBids({chainName:this.chainName,...t})}async listCollectionBids(t){return this.orderbookService.listCollectionBids({chainName:this.chainName,...t})}async listTrades(t){return this.orderbookService.listTrades({chainName:this.chainName,...t})}async cancelOrders(t,r,s){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:r,orders:t,signature:s}})}async createListing({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a listing");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a listing");if(![2,3].includes(r.offer[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be listed");if(![0,1].includes(r.consideration[0].itemType))throw new Error("Only Native / ERC20 tokens can be used as currency items in a listing");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:I,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(W),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a bid");if(![2,3].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be bid against");return this.orderbookService.createBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:I,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a collection bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a collection bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a collection bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");return this.orderbookService.createCollectionBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(Be),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:I,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}};var J=class{constructor(t,r,s,n){this.chainName=r;this.seaportAddress=s;this.orderbookClient=new P({BASE:t,HEADERS:n?{"x-api-key":n}:void 0});}orderbookClient;create(){return new Y(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var yt="imtbl-zkevm-testnet",gt="imtbl-zkevm-mainnet";function Z(e,t){let r=new ethers.FetchRequest(e);return t&&r.setHeader("x-api-key",t),new ethers.JsonRpcProvider(r)}function ke(e){switch(e.baseConfig.environment){case config.Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:yt,provider:Z("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case config.Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:gt,provider:Z("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}var X=class{constructor(t,r){this.defaultSeaportContractAddress=t;this.provider=r;}create(t){let r=t??this.defaultSeaportContractAddress,s=this.provider;return s.getSigner=async function(i){i==null&&(i=0);let o=this.send("eth_accounts",[]);if(typeof i=="number"){let d=await o;if(i>=d.length)throw new Error("no such account");return new ethers.JsonRpcSigner(this,d[i])}return new ethers.JsonRpcSigner(this,i)},new seaportJs.Seaport(s,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}};var de=class e{apiClient;seaport;orderbookConfig;constructor(t){let s={...ke(t),...t.overrides};if(t.overrides?.jsonRpcProviderUrl&&(s.provider=Z(t.overrides?.jsonRpcProviderUrl,t.baseConfig.rateLimitingKey)),!s)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=s;let{apiEndpoint:n,chainName:i}=this.orderbookConfig;if(!n)throw new Error("API endpoint must be provided");this.apiClient=new J(n,i,this.orderbookConfig.seaportContractAddress,t.baseConfig.rateLimitingKey).create();let o=new X(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new G(o,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,t.baseConfig.rateLimitingKey);}static defaultOrderExpiry(){return new Date(Date.now()+1e3*60*60*24*365*2)}config(){return this.orderbookConfig}async getListing(t){let r=await this.apiClient.getListing(t);return {result:h(r.result)}}async getBid(t){let r=await this.apiClient.getBid(t);return {result:x(r.result)}}async getCollectionBid(t){let r=await this.apiClient.getCollectionBid(t);return {result:B(r.result)}}async getTrade(t){let r=await this.apiClient.getTrade(t);return {result:te(r.result)}}async listListings(t){let r=await this.apiClient.listListings(t);return {page:k(r.page),result:r.result.map(h)}}async listBids(t){let r=await this.apiClient.listBids(t);return {page:k(r.page),result:r.result.map(x)}}async listCollectionBids(t){let r=await this.apiClient.listCollectionBids(t);return {page:k(r.page),result:r.result.map(B)}}async listTrades(t){let r=await this.apiClient.listTrades(t);return {page:k(r.page),result:r.result.map(te)}}async prepareBulkListings({makerAddress:t,listingParams:r}){if(r.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(r.length===1){let o=await this.seaport.prepareSeaportOrder(t,r[0].sell,r[0].buy,r[0].sell.type==="ERC1155",r[0].orderStart||new Date,r[0].orderExpiry||e.defaultOrderExpiry());return {actions:o.actions,completeListings:async d=>{let p=await this.createListing({makerFees:r[0].makerFees,orderComponents:o.orderComponents,orderHash:o.orderHash,orderSignature:typeof d=="string"?d:d[0]});return {result:[{success:!0,orderHash:o.orderHash,order:p.result}]}}}}if(await this.orderbookConfig.provider.getCode(t)!=="0x"){metrics.track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:t,listingsCount:r.length});let o=await Promise.all(r.map(a=>this.seaport.prepareSeaportOrder(t,a.sell,a.buy,a.sell.type==="ERC1155",a.orderStart||new Date,a.orderExpiry||e.defaultOrderExpiry()))),d=[];return {actions:o.flatMap(a=>{let l=[];return a.actions.forEach(u=>{if(u.type==="TRANSACTION"){let c=a.orderComponents.offer[0].token;d.includes(c)||(d.push(c),l.push(u));}else l.push(u);}),l}),completeListings:async a=>{if(typeof a=="string")throw new Error("A signature per listing must be provided for smart contract wallets");return {result:(await Promise.all(o.map((c,m)=>{let O=a[m];return this.apiClient.createListing({makerFees:r[m].makerFees,orderComponents:c.orderComponents,orderHash:c.orderHash,orderSignature:O}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:o[m].orderHash,order:c?h(c.result):void 0}))}}}}metrics.track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:t,listingsCount:r.length});let{actions:n,preparedOrders:i}=await this.seaport.prepareBulkSeaportOrders(t,r.map(o=>({offerItem:o.sell,considerationItem:o.buy,allowPartialFills:o.sell.type==="ERC1155",orderStart:o.orderStart||new Date,orderExpiry:o.orderExpiry||e.defaultOrderExpiry()})));return {actions:n,completeListings:async o=>{let d=typeof o=="object";if(d&&o.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let p=i.map(c=>c.orderComponents),a=d?o[0]:o,l=Le(a,p);return {result:(await Promise.all(p.map((c,m)=>{let O=l[m],E=i[m],ve=r[m];return this.apiClient.createListing({orderComponents:c,orderHash:E.orderHash,orderSignature:O,makerFees:ve.makerFees}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:i[m].orderHash,order:c?h(c.result):void 0}))}}}}async prepareListing({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,r.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createListing(t){let r=await this.apiClient.createListing(t);return {result:h(r.result)}}async prepareBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,s.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createBid(t){let r=await this.apiClient.createBid(t);return {result:x(r.result)}}async prepareCollectionBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,!0,n||new Date,i||e.defaultOrderExpiry())}async createCollectionBid(t){let r=await this.apiClient.createCollectionBid(t);return {result:B(r.result)}}async fulfillOrder(t,r,s,n,i){let o={order_id:t,taker_address:r,fees:s.map(u=>({type:f.type.TAKER_ECOSYSTEM,amount:u.amount,recipient_address:u.recipientAddress}))},d=i?[{identifier:i,proof:[]}]:void 0;i&&(o.token_id=i);let p=await this.apiClient.fulfillmentData([o]);if(p.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment data: ${p.result.unfulfillable_orders[0].reason}`);if(p.result.fulfillable_orders?.length!==1)throw new Error("unexpected fulfillable order result length");let a=p.result.fulfillable_orders[0].extra_data,l=p.result.fulfillable_orders[0].order;if(l.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${l.status}`);return this.seaport.fulfillOrder(l,r,a,n,d)}async fulfillBulkOrders(t,r){let s=t.map(i=>{let o="listingId"in i;return {orderId:o?i.listingId:i.orderId,takerFees:i.takerFees,amountToFill:i.amountToFill,tokenId:o?void 0:i.tokenId}}),n=await this.apiClient.fulfillmentData(s.map(i=>({order_id:i.orderId,taker_address:r,fees:i.takerFees.map(o=>({type:f.type.TAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),token_id:i?.tokenId})));try{let i=n.result.fulfillable_orders.map(o=>{let d=s.find(a=>a.orderId===o.order.id&&a.tokenId===o.token_id);if(!d){let a=`Could not find order for order ${o.order.id}`;throw o.token_id&&(a+=` and token ID ${o.token_id}`),new Error(a)}let p=[];return d.tokenId&&p.push({identifier:d.tokenId,proof:[]}),{extraData:o.extra_data,order:o.order,unitsToFill:d.amountToFill,considerationCriteria:p}});return {...await this.seaport.fulfillBulkOrders(i,r),fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,tokenId:o.token_id,reason:o.reason})),sufficientBalance:!0}}catch(i){if(String(i).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,reason:o.reason})),sufficientBalance:!1};throw i}}async prepareOrderCancellations(t){let s={name:"imtbl-order-book",chainId:(await this.orderbookConfig.provider.getNetwork()).chainId,verifyingContract:this.orderbookConfig.seaportContractAddress},n={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},i={orders:t.map(o=>({id:o}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:s,types:n,value:i}}}}async cancelOrders(t,r,s){return this.apiClient.cancelOrders(t,r,s)}async cancelOrdersOnChain(t,r){let s=Promise.all(t.map(l=>this.apiClient.getListing(l).catch(u=>{if(u.status!==404)throw u}))),n=Promise.all(t.map(l=>this.apiClient.getBid(l).catch(u=>{if(u.status!==404)throw u}))),i=Promise.all(t.map(l=>this.apiClient.getCollectionBid(l).catch(u=>{if(u.status!==404)throw u}))),o=[await Promise.all([s,n,i])].flat(2).filter(l=>l!==void 0).map(l=>l.result);if(o.length!==t.length){let l=t.filter(u=>!o.some(c=>c.id===u));throw new Error(`Orders ${l} not found`)}for(let l of o)if(l.account_address!==r.toLowerCase())throw new Error(`Only account ${l.account_address} can cancel order ${l.id}`);let d=o.map(l=>l.protocol_data.seaport_address);if(new Set(d).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(o,r)}}};var ht={estimatedFulfillmentGasGwei:4e5};
16
+ var b=class{constructor(t){this.config=t;}};var T=class extends Error{url;status;statusText;body;request;constructor(t,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=t;}};var v=class extends Error{constructor(t){super(t),this.name="CancelError";}get isCancelled(){return !0}},L=class{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(t){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((r,s)=>{this._resolve=r,this._reject=s;let n=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(d));},i=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(d));},o=d=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(d);};return Object.defineProperty(o,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(o,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(o,"isCancelled",{get:()=>this._isCancelled}),t(n,i,o)});}then(t,r){return this._promise.then(t,r)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let t of this._cancelHandlers)t();}catch(t){console.warn("Cancellation threw an error",t);return}this._cancelHandlers.length=0,this._reject?.(new v("Request aborted"));}}get isCancelled(){return this._isCancelled}};var ee=e=>e!=null,F=e=>typeof e=="string",Q=e=>F(e)&&e!=="",ce=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof pe__default.default,qe=e=>e>=200&&e<300,He=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Me=e=>{let t=[],r=(n,i)=>{t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`);},s=(n,i)=>{ee(i)&&(Array.isArray(i)?i.forEach(o=>{s(n,o);}):typeof i=="object"?Object.entries(i).forEach(([o,d])=>{s(`${n}[${o}]`,d);}):r(n,i));};return Object.entries(e).forEach(([n,i])=>{s(n,i);}),t.length>0?`?${t.join("&")}`:""},Ve=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(i,o)=>t.path?.hasOwnProperty(o)?r(String(t.path[o])):i),n=`${e.BASE}${s}`;return t.query?`${n}${Me(t.query)}`:n},Ue=e=>{if(e.formData){let t=new pe__default.default,r=(s,n)=>{F(n)||ce(n)?t.append(s,n):t.append(s,JSON.stringify(n));};return Object.entries(e.formData).filter(([s,n])=>ee(n)).forEach(([s,n])=>{Array.isArray(n)?n.forEach(i=>r(s,i)):r(s,n);}),t}},D=async(e,t)=>typeof t=="function"?t(e):t,ze=async(e,t,r)=>{let s=await D(t,e.TOKEN),n=await D(t,e.USERNAME),i=await D(t,e.PASSWORD),o=await D(t,e.HEADERS),d=typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...o,...t.headers,...d}).filter(([a,l])=>ee(l)).reduce((a,[l,u])=>({...a,[l]:String(u)}),{});if(Q(s)&&(p.Authorization=`Bearer ${s}`),Q(n)&&Q(i)){let a=He(`${n}:${i}`);p.Authorization=`Basic ${a}`;}return t.body&&(t.mediaType?p["Content-Type"]=t.mediaType:ce(t.body)?p["Content-Type"]=t.body.type||"application/octet-stream":F(t.body)?p["Content-Type"]="text/plain":Fe(t.body)||(p["Content-Type"]="application/json")),p},$e=e=>{if(e.body)return e.body},Ge=async(e,t,r,s,n,i,o)=>{let d=le__default.default.CancelToken.source(),p={url:r,headers:i,data:s??n,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:d.token};o(()=>d.cancel("The user aborted a request."));try{return await le__default.default.request(p)}catch(a){let l=a;if(l.response)return l.response;throw a}},je=(e,t)=>{if(t){let r=e.headers[t];if(F(r))return r}},We=e=>{if(e.status!==204)return e.data},Ke=(e,t)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(s)throw new T(e,t,s);if(!t.ok)throw new T(e,t,"Generic Error")},ue=(e,t)=>new L(async(r,s,n)=>{try{let i=Ve(e,t),o=Ue(t),d=$e(t),p=await ze(e,t,o);if(!n.isCancelled){let a=await Ge(e,t,i,d,o,p,n),l=We(a),u=je(a,t.responseHeader),c={url:i,ok:qe(a.status),status:a.status,statusText:a.statusText,body:u??l};Ke(t,c),r(c.body);}}catch(i){s(i);}});var q=class extends b{constructor(t){super(t);}request(t){return ue(this.config,t)}};var S=class{constructor(t){this.httpRequest=t;}cancelOrders({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",401:"Unauthorised Request (401)",404:"The specified resource was not found (404)",429:"Too Many Requests (429)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listListings({chainName:t,status:r,sellItemContractAddress:s,buyItemType:n,buyItemContractAddress:i,accountAddress:o,sellItemMetadataId:d,sellItemTokenId:p,fromUpdatedAt:a,pageSize:l,sortBy:u,sortDirection:c,pageCursor:m}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},query:{status:r,sell_item_contract_address:s,buy_item_type:n,buy_item_contract_address:i,account_address:o,sell_item_metadata_id:d,sell_item_token_id:p,from_updated_at:a,page_size:l,sort_by:u,sort_direction:c,page_cursor:m},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,buyItemMetadataId:o,buyItemTokenId:d,fromUpdatedAt:p,pageSize:a,sortBy:l,sortDirection:u,pageCursor:c}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,buy_item_metadata_id:o,buy_item_token_id:d,from_updated_at:p,page_size:a,sort_by:l,sort_direction:u,page_cursor:c},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listCollectionBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,fromUpdatedAt:o,pageSize:d,sortBy:p,sortDirection:a,pageCursor:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,from_updated_at:o,page_size:d,sort_by:p,sort_direction:a,page_cursor:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createCollectionBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}getListing({chainName:t,listingId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:t,listing_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getBid({chainName:t,bidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids/{bid_id}",path:{chain_name:t,bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getCollectionBid({chainName:t,collectionBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids/{collection_bid_id}",path:{chain_name:t,collection_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:t,accountAddress:r,sellItemContractAddress:s,fromIndexedAt:n,pageSize:i,sortBy:o,sortDirection:d,pageCursor:p}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:t},query:{account_address:r,sell_item_contract_address:s,from_indexed_at:n,page_size:i,sort_by:o,sort_direction:d,page_cursor:p},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:t,tradeId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:t,trade_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}};var P=class{orders;request;constructor(t,r=q){this.request=new r({BASE:t?.BASE??"https://api.immutable.com",VERSION:t?.VERSION??"1.0.0",WITH_CREDENTIALS:t?.WITH_CREDENTIALS??!1,CREDENTIALS:t?.CREDENTIALS??"include",TOKEN:t?.TOKEN,USERNAME:t?.USERNAME,PASSWORD:t?.PASSWORD,HEADERS:t?.HEADERS,ENCODE_PATH:t?.ENCODE_PATH}),this.orders=new S(this.request);}};var me;(t=>{(i=>(i.ON_CHAIN="ON_CHAIN",i.OFF_CHAIN="OFF_CHAIN",i.UNDERFUNDED="UNDERFUNDED"))(t.cancellation_type||={});})(me||={});var fe;(t=>{(s=>s.FILLED="FILLED")(t.reason_code||={});})(fe||={});var f;(t=>{(o=>(o.ROYALTY="ROYALTY",o.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",o.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",o.PROTOCOL="PROTOCOL"))(t.type||={});})(f||={});var R;(t=>{(i=>(i.LISTING="LISTING",i.BID="BID",i.COLLECTION_BID="COLLECTION_BID"))(t.type||={});})(R||={});var H=(o=>(o.PENDING="PENDING",o.ACTIVE="ACTIVE",o.INACTIVE="INACTIVE",o.FILLED="FILLED",o.EXPIRED="EXPIRED",o.CANCELLED="CANCELLED",o))(H||{});var y;(t=>{(n=>(n.FULL_RESTRICTED="FULL_RESTRICTED",n.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(t.order_type||={});})(y||={});function C(e){throw new Error("Unreachable")}function h(e){if(e.type!==R.type.LISTING)throw new Error("Order type must be LISTING");let t=e.sell.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Listing sell items must either ERC721 or ERC1155")}),r=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Listing buy items must be either NATIVE or ERC20")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function B(e){if(e.type!==R.type.BID)throw new Error("Order type must be BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Bid buy items must either ERC721 or ERC1155")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function x(e){if(e.type!==R.type.COLLECTION_BID)throw new Error("Order type must be COLLECTION_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function N(e){switch(e.type){case R.type.LISTING:return h(e);case R.type.BID:return B(e);case R.type.COLLECTION_BID:return x(e);default:return C(e.type)}}function te(e){let t=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Buy items must be NATIVE, ERC20, ERC721 or ERC1155")}),r=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Sell items must be ERC20, ERC721 or ERC1155")});return {id:e.id,orderId:e.order_id,buy:t,sell:r,buyerFees:e.buyer_fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),chain:e.chain,indexedAt:e.indexed_at,blockchainMetadata:{blockNumber:e.blockchain_metadata.block_number,logIndex:e.blockchain_metadata.log_index,transactionHash:e.blockchain_metadata.transaction_hash,transactionIndex:e.blockchain_metadata.transaction_index},buyerAddress:e.buyer_address,makerAddress:e.maker_address,sellerAddress:e.seller_address,takerAddress:e.taker_address}}function k(e){return {nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}var Ye=(n=>(n[n.MAKER_ECOSYSTEM=f.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",n[n.TAKER_ECOSYSTEM=f.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",n[n.PROTOCOL=f.type.PROTOCOL]="PROTOCOL",n[n.ROYALTY=f.type.ROYALTY]="ROYALTY",n))(Ye||{}),re=(r=>(r.TRANSACTION="TRANSACTION",r.SIGNABLE="SIGNABLE",r))(re||{}),Ce=(s=>(s.APPROVAL="APPROVAL",s.FULFILL_ORDER="FULFILL_ORDER",s.CANCEL="CANCEL",s))(Ce||{}),se=(s=>(s.CREATE_LISTING="CREATE_ORDER",s.CREATE_ORDER="CREATE_ORDER",s.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",s))(se||{});var oe="ImmutableSeaport",O="1.5",M={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]};var Je={integer:0,address:ethers.zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},ne=e=>e===void 0?!1:e!=null&&(["string","number"].includes(typeof e)&&BigInt(e)===0n||Array.isArray(e)&&e.every(ne)||typeof e=="object"&&Object.values(e).every(ne)||typeof e=="boolean"&&e===!1);function Ze(e){let[,t]=e.match(/^bytes(\d+)$/)??[];return t?ethers.zeroPadValue("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),Je[e])}var A=class e{constructor(t){this.types=t;for(let r in t){let s=this.getDefaultValue(r);if(this.defaultValues[r]=s,!ne(s))throw new Error(`Got non-empty value for type ${r} in default generator: ${s}`)}}defaultValues={};static from(t,r){let{defaultValues:s}=new e(t);return r?s[r]:s}getDefaultValue(t){if(this.defaultValues[t])return this.defaultValues[t];let r=Ze(t);if(r!==void 0)return r;let s=t.match(/^(.*)(\x5b(\d*)\x5d)$/);if(s){let i=s[1],o=parseInt(s[3]);if(o>0){let d=this.getDefaultValue(i);return Array(o).fill(d)}return []}let n=this.types[t];if(n)return n.reduce((i,{name:o,type:d})=>({...i,[o]:this.getDefaultValue(d)}),{});throw new Error(`unknown type: ${t}`)}};var tt=(e,t)=>Array(e).fill(0).map((r,s)=>t(s)),ie=(e,t)=>tt(Math.ceil(e.length/t),r=>e.slice(r*t,(r+1)*t)),ye=e=>ethers.toBeHex(e.toString("hex")),_=e=>Buffer.from(e.slice(2),"hex"),V=e=>_(ethers.keccak256(e)),rt=e=>V(ethers.concat(e)),w=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),ge=(e,t=!0)=>{if(e.length===0)throw new Error("empty tree");let s=[e.map(n=>{let i=Buffer.isBuffer(n)?n:_(n);return t?V(i):i})];for(;s[s.length-1].length>1;)s.push(st(s[s.length-1]));return s[s.length-1][0]},st=e=>ie(e,2).map(rt);var dt=(e,t)=>new merkletreejs.MerkleTree(e.map(_),V,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:_(t)}),lt=(e,t,r=`0x${"ff".repeat(64)}`)=>ethers.concat([r,`0x${e.toString(16).padStart(6,"0")}`,ethers.AbiCoder.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]),U=class{constructor(t,r,s,n,i){this.types=t;this.rootType=r;this.leafType=s;this.elements=n;this.depth=i;let o=ethers.TypedDataEncoder.from(t);this.encoder=o,this.leafHasher=d=>o.hashStruct(s,d),this.defaultNode=A.from(t,s),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=dt(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:t}=this;return w([...t],this.completedSize,this.defaultNode)}getCompleteLeaves(){let t=this.elements.map(this.leafHasher);return w([...t],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(t){let s=this.getCompleteLeaves()[t],n=this.tree.getHexProof(s,t),i=this.tree.getHexRoot();return {leaf:s,proof:n,root:i}}getEncodedProofAndSignature(t,r){let{proof:s}=this.getProof(t);return lt(t,s,r)}getDataToSign(){let t=this.getCompleteElements();for(;t.length>2;)t=ie(t,2);return t}add(t){this.elements.push(t);}getBulkOrderHash(){let t=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),r=this.getCompleteLeaves().map(_),s=ye(ge(r,!1)),n=ethers.keccak256(ethers.toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(ethers.keccak256(ethers.concat([n,s]))!==t)throw new Error("expected derived bulk order hash to match");return t}};function pt(e){return {...M,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}function ct(e){return Math.max(Math.ceil(Math.log2(e)),1)}function Oe(e,t=0,r=ct(e.length+t)){let s=pt(r),n=A.from(s,"OrderComponents"),i=[...e];return t>0&&(i=[...w([],t,n),...e]),new U(s,"BulkOrder","OrderComponents",i,r)}function Ae(e){if([0,1,2,3].includes(Number(e)))return Number(e);throw new Error(`Unknown order type ${e}`)}function z(e){if([0,1,2,3,4,5].includes(Number(e)))return Number(e);throw new Error(`Unknown item type ${e}`)}function _e(e){let r=JSON.parse(e).message;return {...r,orderType:Ae(r.orderType),salt:ethers.toBeHex(BigInt(r.salt)),offer:r.offer.map(s=>({...s,itemType:z(s.itemType)})),consideration:r.consideration.map(s=>({...s,itemType:z(s.itemType)}))}}function be(e){let t=JSON.parse(e);return {components:t.message.tree.flat(1/0).filter(s=>s.offerer!=="0x0000000000000000000000000000000000000000").map(s=>({...s,orderType:Ae(s.orderType),salt:ethers.toBeHex(BigInt(s.salt)),offer:s.offer.map(n=>({...n,itemType:z(n.itemType)})),consideration:s.consideration.map(n=>({...n,itemType:z(n.itemType)}))})),types:t.types,value:t.message}}function Le(e,t){let r=Oe(t);return t.map((s,n)=>r.getEncodedProofAndSignature(n,e))}function mt(e){switch(e.type){case"NATIVE":throw new Error("NATIVE items are not supported in the offer");case"ERC20":return {itemType:1 .valueOf(),token:e.contract_address,identifierOrCriteria:"0",startAmount:e.amount,endAmount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:"1",endAmount:"1"};case"ERC1155":return {itemType:3 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:e.amount,endAmount:e.amount};case"ERC721_COLLECTION":throw new Error("ERC721_COLLECTION items are not supported in the offer");case"ERC1155_COLLECTION":throw new Error("ERC1155_COLLECTION items are not supported in the offer");default:return C()}}function ft(e,t){switch(e.type){case"NATIVE":return {itemType:0 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:ethers.ZeroAddress,identifierOrCriteria:"0",recipient:t};case"ERC20":return {itemType:1 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC721":return {itemType:2 .valueOf(),startAmount:"1",endAmount:"1",token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC721_COLLECTION":return {itemType:4 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC1155_COLLECTION":return {itemType:5 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};default:return C()}}function G(e){let t=e.sell.map(mt),r=e.buy.map(o=>ft(o,e.account_address)),s=function(o){switch(o){case R.type.LISTING:return r[0];case R.type.BID:case R.type.COLLECTION_BID:return t[0];default:return C()}}(e.type),n=function(o){switch(o){case y.order_type.FULL_RESTRICTED:return 2;case y.order_type.PARTIAL_RESTRICTED:return 3;default:return C()}}(e.protocol_data.order_type),i=e.fees.map(o=>({amount:o.amount,itemType:s.itemType,recipient:o.recipient_address,token:s.token,identifierOrCriteria:s.identifierOrCriteria}));return {orderComponents:{offerer:e.account_address,zone:e.protocol_data.zone_address,offer:t,consideration:r,orderType:n.valueOf(),startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),zoneHash:ethers.ZeroHash,salt:e.salt,conduitKey:ethers.ZeroHash,counter:e.protocol_data.counter,totalOriginalConsiderationItems:r.length},tips:i}}function g(e,t,r){return async()=>{let s=await e.buildTransaction(),n={to:s.to,from:r,type:s.type,maxFeePerGas:s.maxFeePerGas?BigInt(s.maxFeePerGas):void 0,maxPriorityFeePerGas:s.maxPriorityFeePerGas?BigInt(s.maxPriorityFeePerGas):void 0,value:s.value?BigInt(s.value):void 0,data:s.data,nonce:s.nonce,chainId:t};return n.gasLimit=BigInt(await e.estimateGas()),n.gasLimit+=n.gasLimit/BigInt(5),n}}function Pe(e){switch(e.type){case"ERC20":return {token:e.contractAddress,amount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount};default:return C()}}function Be(e,t){switch(e.type){case"NATIVE":return {amount:e.amount,recipient:t};case"ERC20":return {token:e.contractAddress,amount:e.amount,recipient:t};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount,recipient:t};case"ERC721_COLLECTION":return {itemType:2 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};case"ERC1155_COLLECTION":return {itemType:3 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};default:return C()}}var j=class e{constructor(t,r,s,n,i){this.seaportLibFactory=t;this.provider=r;this.seaportContractAddress=s;this.zoneContractAddress=n;this.rateLimitingKey=i;}async prepareBulkSeaportOrders(t,r){let{actions:s}=await this.createSeaportOrders(t,r),n=s.filter(c=>c.type==="approval"),i=await this.provider.getNetwork(),o=n.map(c=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(c.transactionMethods,i.chainId,t)})),d=s.find(c=>c.type==="createBulk");if(!d)throw new Error("No create bulk order action found");let p=await d.getMessageToSign(),{components:a,types:l,value:u}=be(p);return o.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(l,u)}),{actions:o,preparedOrders:a.map(c=>({orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}))}}async prepareSeaportOrder(t,r,s,n,i,o){let{actions:d}=await this.createSeaportOrder(t,r,s,n,i,o),p=[],a=d.find(m=>m.type==="approval");a&&p.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(a.transactionMethods,(await this.provider.getNetwork()).chainId,t)});let l=d.find(m=>m.type==="create");if(!l)throw new Error("No create order action found");let u=await l.getMessageToSign(),c=_e(u);return p.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromOrderComponents(c)}),{actions:p,orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}}async fulfillOrder(t,r,s,n,i){let{orderComponents:o,tips:d}=G(t),p=this.getSeaportLib(t),a=(await this.provider.getNetwork()).chainId,l={order:{parameters:o,signature:t.signature},unitsToFill:n,extraData:s,tips:d};i&&(l.considerationCriteria=i);let{actions:u}=await p.fulfillOrders({accountAddress:r,fulfillOrderDetails:[l]}),c=[],m=u.filter(E=>E.type==="approval");m.length>0&&m.forEach(E=>{c.push({type:"TRANSACTION",buildTransaction:g(E.transactionMethods,a,r),purpose:"APPROVAL"});});let I=u.find(E=>E.type==="exchange");if(!I)throw new Error("No exchange action found");return c.push({type:"TRANSACTION",buildTransaction:g(I.transactionMethods,a,r),purpose:"FULFILL_ORDER"}),{actions:c,expiration:e.getExpirationISOTimeFromExtraData(s),order:N(t)}}async fulfillBulkOrders(t,r){let s=t.map(a=>{let{orderComponents:l,tips:u}=G(a.order),c={order:{parameters:l,signature:a.order.signature},unitsToFill:a.unitsToFill,extraData:a.extraData,tips:u};return a.considerationCriteria&&a.considerationCriteria.length>0&&(c.considerationCriteria=a.considerationCriteria),c}),{actions:n}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:s,accountAddress:r}),i=[],o=n.filter(a=>a.type==="approval"),d=(await this.provider.getNetwork()).chainId;o.length>0&&o.forEach(a=>{i.push({type:"TRANSACTION",buildTransaction:g(a.transactionMethods,d,r),purpose:"APPROVAL"});});let p=n.find(a=>a.type==="exchange");if(!p)throw new Error("No exchange action found");return i.push({type:"TRANSACTION",buildTransaction:g(p.transactionMethods,(await this.provider.getNetwork()).chainId,r),purpose:"FULFILL_ORDER"}),{actions:i,expiration:s.map(a=>e.getExpirationISOTimeFromExtraData(a.extraData)).reduce((a,l)=>new Date(a)<new Date(l)?a:l)}}async cancelOrders(t,r){let s=t.map(o=>G(o).orderComponents),i=await this.getSeaportLib(t[0]).cancelOrders(s,r);return {type:"TRANSACTION",buildTransaction:g(i,(await this.provider.getNetwork()).chainId,r),purpose:"CANCEL"}}createSeaportOrders(t,r){return this.getSeaportLib().createBulkOrders(r.map(n=>{let{offerItem:i,considerationItem:o,allowPartialFills:d,orderStart:p,orderExpiry:a}=n;return {allowPartialFills:d,offer:[Pe(i)],consideration:[Be(o,t)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(a.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),t)}createSeaportOrder(t,r,s,n,i,o){return this.getSeaportLib().createOrder({allowPartialFills:n,offer:[Pe(r)],consideration:[Be(s,t)],startTime:(i.getTime()/1e3).toFixed(0),endTime:(o.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},t)}async getTypedDataFromBulkOrderComponents(t,r){delete t.EIP712Domain;let{chainId:s}=await this.provider.getNetwork();return {domain:{name:oe,version:O,chainId:s,verifyingContract:this.seaportContractAddress},types:t,value:r}}async getTypedDataFromOrderComponents(t){let{chainId:r}=await this.provider.getNetwork();return {domain:{name:oe,version:O,chainId:r,verifyingContract:this.seaportContractAddress},types:M,value:t}}getSeaportLib(t){let r=t?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(r)}static getExpirationISOTimeFromExtraData(t){let r=t.slice(44,60),s=parseInt(r,16);return new Date(s*1e3).toISOString()}};function W(e){switch(e.itemType){case 0:return {type:"NATIVE",amount:e.startAmount};case 1:return {type:"ERC20",contract_address:e.token,amount:e.startAmount};case 2:return {type:"ERC721",contract_address:e.token,token_id:e.identifierOrCriteria};case 3:return {type:"ERC1155",contract_address:e.token,token_id:e.identifierOrCriteria,amount:e.startAmount};case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};default:return C(e.itemType)}}function ae(e){if(e.itemType!==1)throw new Error(`Expected ERC20 item, got ${e.itemType}`);return {type:"ERC20",contract_address:e.token,amount:e.startAmount}}function xe(e){switch(e.itemType){case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};case 1:case 0:case 2:case 3:throw new Error(`Unsupported item type ${e.itemType}`);default:return C(e.itemType)}}function K(e){switch(e){case 2:return y.order_type.FULL_RESTRICTED;case 3:return y.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${e}`);default:return C()}}var Y=class{constructor(t,r,s){this.orderbookService=t;this.chainName=r;this.seaportAddress=s;}async fulfillmentData(t){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:t})}async getListing(t){return this.orderbookService.getListing({chainName:this.chainName,listingId:t})}async getBid(t){return this.orderbookService.getBid({chainName:this.chainName,bidId:t})}async getCollectionBid(t){return this.orderbookService.getCollectionBid({chainName:this.chainName,collectionBidId:t})}async getTrade(t){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:t})}async listListings(t){return this.orderbookService.listListings({chainName:this.chainName,...t})}async listBids(t){return this.orderbookService.listBids({chainName:this.chainName,...t})}async listCollectionBids(t){return this.orderbookService.listCollectionBids({chainName:this.chainName,...t})}async listTrades(t){return this.orderbookService.listTrades({chainName:this.chainName,...t})}async cancelOrders(t,r,s){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:r,orders:t,signature:s}})}async createListing({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a listing");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a listing");if(![2,3].includes(r.offer[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be listed");if(![0,1].includes(r.consideration[0].itemType))throw new Error("Only Native / ERC20 tokens can be used as currency items in a listing");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(W),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a bid");if(![2,3].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be bid against");return this.orderbookService.createBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a collection bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a collection bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a collection bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");return this.orderbookService.createCollectionBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(xe),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}};var J=class{constructor(t,r,s,n){this.chainName=r;this.seaportAddress=s;this.orderbookClient=new P({BASE:t,HEADERS:n?{"x-api-key":n}:void 0});}orderbookClient;create(){return new Y(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var yt="imtbl-zkevm-testnet",gt="imtbl-zkevm-mainnet";function Z(e,t){let r=new ethers.FetchRequest(e);return t&&r.setHeader("x-api-key",t),new ethers.JsonRpcProvider(r)}function ke(e){switch(e.baseConfig.environment){case config.Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:yt,provider:Z("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case config.Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:gt,provider:Z("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}var X=class{constructor(t,r){this.defaultSeaportContractAddress=t;this.provider=r;}create(t){let r=t??this.defaultSeaportContractAddress,s=this.provider;return s.getSigner=async function(i){i==null&&(i=0);let o=this.send("eth_accounts",[]);if(typeof i=="number"){let d=await o;if(i>=d.length)throw new Error("no such account");return new ethers.JsonRpcSigner(this,d[i])}return new ethers.JsonRpcSigner(this,i)},new seaportJs.Seaport(s,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}};var de=class e{apiClient;seaport;orderbookConfig;constructor(t){let s={...ke(t),...t.overrides};if(t.overrides?.jsonRpcProviderUrl&&(s.provider=Z(t.overrides?.jsonRpcProviderUrl,t.baseConfig.rateLimitingKey)),!s)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=s;let{apiEndpoint:n,chainName:i}=this.orderbookConfig;if(!n)throw new Error("API endpoint must be provided");this.apiClient=new J(n,i,this.orderbookConfig.seaportContractAddress,t.baseConfig.rateLimitingKey).create();let o=new X(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new j(o,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,t.baseConfig.rateLimitingKey);}static defaultOrderExpiry(){return new Date(Date.now()+1e3*60*60*24*365*2)}config(){return this.orderbookConfig}async getListing(t){let r=await this.apiClient.getListing(t);return {result:h(r.result)}}async getBid(t){let r=await this.apiClient.getBid(t);return {result:B(r.result)}}async getCollectionBid(t){let r=await this.apiClient.getCollectionBid(t);return {result:x(r.result)}}async getTrade(t){let r=await this.apiClient.getTrade(t);return {result:te(r.result)}}async listListings(t){let r=await this.apiClient.listListings(t);return {page:k(r.page),result:r.result.map(h)}}async listBids(t){let r=await this.apiClient.listBids(t);return {page:k(r.page),result:r.result.map(B)}}async listCollectionBids(t){let r=await this.apiClient.listCollectionBids(t);return {page:k(r.page),result:r.result.map(x)}}async listTrades(t){let r=await this.apiClient.listTrades(t);return {page:k(r.page),result:r.result.map(te)}}async prepareBulkListings({makerAddress:t,listingParams:r}){if(r.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(r.length===1){let o=await this.seaport.prepareSeaportOrder(t,r[0].sell,r[0].buy,r[0].sell.type==="ERC1155",r[0].orderStart||new Date,r[0].orderExpiry||e.defaultOrderExpiry());return {actions:o.actions,completeListings:async d=>{let p=await this.createListing({makerFees:r[0].makerFees,orderComponents:o.orderComponents,orderHash:o.orderHash,orderSignature:typeof d=="string"?d:d[0]});return {result:[{success:!0,orderHash:o.orderHash,order:p.result}]}}}}if(await this.orderbookConfig.provider.getCode(t)!=="0x"){metrics.track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:t,listingsCount:r.length});let o=await Promise.all(r.map(a=>this.seaport.prepareSeaportOrder(t,a.sell,a.buy,a.sell.type==="ERC1155",a.orderStart||new Date,a.orderExpiry||e.defaultOrderExpiry()))),d=[];return {actions:o.flatMap(a=>{let l=[];return a.actions.forEach(u=>{if(u.type==="TRANSACTION"){let c=a.orderComponents.offer[0].token;d.includes(c)||(d.push(c),l.push(u));}else l.push(u);}),l}),completeListings:async a=>{if(typeof a=="string")throw new Error("A signature per listing must be provided for smart contract wallets");return {result:(await Promise.all(o.map((c,m)=>{let I=a[m];return this.apiClient.createListing({makerFees:r[m].makerFees,orderComponents:c.orderComponents,orderHash:c.orderHash,orderSignature:I}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:o[m].orderHash,order:c?h(c.result):void 0}))}}}}metrics.track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:t,listingsCount:r.length});let{actions:n,preparedOrders:i}=await this.seaport.prepareBulkSeaportOrders(t,r.map(o=>({offerItem:o.sell,considerationItem:o.buy,allowPartialFills:o.sell.type==="ERC1155",orderStart:o.orderStart||new Date,orderExpiry:o.orderExpiry||e.defaultOrderExpiry()})));return {actions:n,completeListings:async o=>{let d=typeof o=="object";if(d&&o.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let p=i.map(c=>c.orderComponents),a=d?o[0]:o,l=Le(a,p);return {result:(await Promise.all(p.map((c,m)=>{let I=l[m],E=i[m],De=r[m];return this.apiClient.createListing({orderComponents:c,orderHash:E.orderHash,orderSignature:I,makerFees:De.makerFees}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:i[m].orderHash,order:c?h(c.result):void 0}))}}}}async prepareListing({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,r.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createListing(t){let r=await this.apiClient.createListing(t);return {result:h(r.result)}}async prepareBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,s.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createBid(t){let r=await this.apiClient.createBid(t);return {result:B(r.result)}}async prepareCollectionBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,!0,n||new Date,i||e.defaultOrderExpiry())}async createCollectionBid(t){let r=await this.apiClient.createCollectionBid(t);return {result:x(r.result)}}async fulfillOrder(t,r,s,n,i){let o={order_id:t,taker_address:r,fees:s.map(u=>({type:f.type.TAKER_ECOSYSTEM,amount:u.amount,recipient_address:u.recipientAddress}))},d=i?[{identifier:i,proof:[]}]:void 0;i&&(o.token_id=i);let p=await this.apiClient.fulfillmentData([o]);if(p.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment data: ${p.result.unfulfillable_orders[0].reason}`);if(p.result.fulfillable_orders?.length!==1)throw new Error("unexpected fulfillable order result length");let a=p.result.fulfillable_orders[0].extra_data,l=p.result.fulfillable_orders[0].order;if(l.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${l.status}`);return this.seaport.fulfillOrder(l,r,a,n,d)}async fulfillBulkOrders(t,r){let s=t.map(i=>{let o="listingId"in i;return {orderId:o?i.listingId:i.orderId,takerFees:i.takerFees,amountToFill:i.amountToFill,tokenId:o?void 0:i.tokenId}}),n=await this.apiClient.fulfillmentData(s.map(i=>({order_id:i.orderId,taker_address:r,fees:i.takerFees.map(o=>({type:f.type.TAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),token_id:i?.tokenId})));try{let i=n.result.fulfillable_orders.map(o=>{let d=s.find(a=>a.orderId===o.order.id&&a.tokenId===o.token_id);if(!d){let a=`Could not find order for order ${o.order.id}`;throw o.token_id&&(a+=` and token ID ${o.token_id}`),new Error(a)}let p=[];return d.tokenId&&p.push({identifier:d.tokenId,proof:[]}),{extraData:o.extra_data,order:o.order,unitsToFill:d.amountToFill,considerationCriteria:p}});return {...await this.seaport.fulfillBulkOrders(i,r),fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,tokenId:o.token_id,reason:o.reason})),sufficientBalance:!0}}catch(i){if(String(i).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,reason:o.reason})),sufficientBalance:!1};throw i}}async prepareOrderCancellations(t){let s={name:"imtbl-order-book",chainId:(await this.orderbookConfig.provider.getNetwork()).chainId,verifyingContract:this.orderbookConfig.seaportContractAddress},n={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},i={orders:t.map(o=>({id:o}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:s,types:n,value:i}}}}async cancelOrders(t,r,s){return this.apiClient.cancelOrders(t,r,s)}async cancelOrdersOnChain(t,r){let s=Promise.all(t.map(l=>this.apiClient.getListing(l).catch(u=>{if(u.status!==404)throw u}))),n=Promise.all(t.map(l=>this.apiClient.getBid(l).catch(u=>{if(u.status!==404)throw u}))),i=Promise.all(t.map(l=>this.apiClient.getCollectionBid(l).catch(u=>{if(u.status!==404)throw u}))),o=[await Promise.all([s,n,i])].flat(2).filter(l=>l!==void 0).map(l=>l.result);if(o.length!==t.length){let l=t.filter(u=>!o.some(c=>c.id===u));throw new Error(`Orders ${l} not found`)}for(let l of o)if(l.account_address!==r.toLowerCase())throw new Error(`Only account ${l.account_address} can cancel order ${l.id}`);let d=o.map(l=>l.protocol_data.seaport_address);if(new Set(d).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(o,r)}}};var ht={estimatedFulfillmentGasGwei:4e5};
17
17
 
18
18
  exports.ActionType = re;
19
19
  exports.FeeType = Ye;
@@ -6,6 +6,6 @@ import { MerkleTree } from 'merkletreejs';
6
6
  import { Environment } from '@imtbl/config';
7
7
  import { Seaport } from '@opensea/seaport-js';
8
8
 
9
- var b=class{constructor(t){this.config=t;}};var T=class extends Error{url;status;statusText;body;request;constructor(t,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=t;}};var D=class extends Error{constructor(t){super(t),this.name="CancelError";}get isCancelled(){return !0}},L=class{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(t){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((r,s)=>{this._resolve=r,this._reject=s;let n=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(d));},i=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(d));},o=d=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(d);};return Object.defineProperty(o,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(o,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(o,"isCancelled",{get:()=>this._isCancelled}),t(n,i,o)});}then(t,r){return this._promise.then(t,r)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let t of this._cancelHandlers)t();}catch(t){console.warn("Cancellation threw an error",t);return}this._cancelHandlers.length=0,this._reject?.(new D("Request aborted"));}}get isCancelled(){return this._isCancelled}};var ee=e=>e!=null,F=e=>typeof e=="string",Q=e=>F(e)&&e!=="",ce=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof pe,qe=e=>e>=200&&e<300,He=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Me=e=>{let t=[],r=(n,i)=>{t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`);},s=(n,i)=>{ee(i)&&(Array.isArray(i)?i.forEach(o=>{s(n,o);}):typeof i=="object"?Object.entries(i).forEach(([o,d])=>{s(`${n}[${o}]`,d);}):r(n,i));};return Object.entries(e).forEach(([n,i])=>{s(n,i);}),t.length>0?`?${t.join("&")}`:""},Ve=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(i,o)=>t.path?.hasOwnProperty(o)?r(String(t.path[o])):i),n=`${e.BASE}${s}`;return t.query?`${n}${Me(t.query)}`:n},Ue=e=>{if(e.formData){let t=new pe,r=(s,n)=>{F(n)||ce(n)?t.append(s,n):t.append(s,JSON.stringify(n));};return Object.entries(e.formData).filter(([s,n])=>ee(n)).forEach(([s,n])=>{Array.isArray(n)?n.forEach(i=>r(s,i)):r(s,n);}),t}},v=async(e,t)=>typeof t=="function"?t(e):t,ze=async(e,t,r)=>{let s=await v(t,e.TOKEN),n=await v(t,e.USERNAME),i=await v(t,e.PASSWORD),o=await v(t,e.HEADERS),d=typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...o,...t.headers,...d}).filter(([a,l])=>ee(l)).reduce((a,[l,u])=>({...a,[l]:String(u)}),{});if(Q(s)&&(p.Authorization=`Bearer ${s}`),Q(n)&&Q(i)){let a=He(`${n}:${i}`);p.Authorization=`Basic ${a}`;}return t.body&&(t.mediaType?p["Content-Type"]=t.mediaType:ce(t.body)?p["Content-Type"]=t.body.type||"application/octet-stream":F(t.body)?p["Content-Type"]="text/plain":Fe(t.body)||(p["Content-Type"]="application/json")),p},je=e=>{if(e.body)return e.body},$e=async(e,t,r,s,n,i,o)=>{let d=le.CancelToken.source(),p={url:r,headers:i,data:s??n,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:d.token};o(()=>d.cancel("The user aborted a request."));try{return await le.request(p)}catch(a){let l=a;if(l.response)return l.response;throw a}},Ge=(e,t)=>{if(t){let r=e.headers[t];if(F(r))return r}},We=e=>{if(e.status!==204)return e.data},Ke=(e,t)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(s)throw new T(e,t,s);if(!t.ok)throw new T(e,t,"Generic Error")},ue=(e,t)=>new L(async(r,s,n)=>{try{let i=Ve(e,t),o=Ue(t),d=je(t),p=await ze(e,t,o);if(!n.isCancelled){let a=await $e(e,t,i,d,o,p,n),l=We(a),u=Ge(a,t.responseHeader),c={url:i,ok:qe(a.status),status:a.status,statusText:a.statusText,body:u??l};Ke(t,c),r(c.body);}}catch(i){s(i);}});var q=class extends b{constructor(t){super(t);}request(t){return ue(this.config,t)}};var S=class{constructor(t){this.httpRequest=t;}cancelOrders({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",401:"Unauthorised Request (401)",404:"The specified resource was not found (404)",429:"Too Many Requests (429)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listListings({chainName:t,status:r,sellItemContractAddress:s,buyItemType:n,buyItemContractAddress:i,accountAddress:o,sellItemMetadataId:d,sellItemTokenId:p,fromUpdatedAt:a,pageSize:l,sortBy:u,sortDirection:c,pageCursor:m}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},query:{status:r,sell_item_contract_address:s,buy_item_type:n,buy_item_contract_address:i,account_address:o,sell_item_metadata_id:d,sell_item_token_id:p,from_updated_at:a,page_size:l,sort_by:u,sort_direction:c,page_cursor:m},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,buyItemMetadataId:o,buyItemTokenId:d,fromUpdatedAt:p,pageSize:a,sortBy:l,sortDirection:u,pageCursor:c}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,buy_item_metadata_id:o,buy_item_token_id:d,from_updated_at:p,page_size:a,sort_by:l,sort_direction:u,page_cursor:c},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listCollectionBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,fromUpdatedAt:o,pageSize:d,sortBy:p,sortDirection:a,pageCursor:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,from_updated_at:o,page_size:d,sort_by:p,sort_direction:a,page_cursor:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createCollectionBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}getListing({chainName:t,listingId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:t,listing_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getBid({chainName:t,bidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids/{bid_id}",path:{chain_name:t,bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getCollectionBid({chainName:t,collectionBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids/{collection_bid_id}",path:{chain_name:t,collection_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:t,accountAddress:r,sellItemContractAddress:s,fromIndexedAt:n,pageSize:i,sortBy:o,sortDirection:d,pageCursor:p}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:t},query:{account_address:r,sell_item_contract_address:s,from_indexed_at:n,page_size:i,sort_by:o,sort_direction:d,page_cursor:p},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:t,tradeId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:t,trade_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}};var P=class{orders;request;constructor(t,r=q){this.request=new r({BASE:t?.BASE??"https://api.immutable.com",VERSION:t?.VERSION??"1.0.0",WITH_CREDENTIALS:t?.WITH_CREDENTIALS??!1,CREDENTIALS:t?.CREDENTIALS??"include",TOKEN:t?.TOKEN,USERNAME:t?.USERNAME,PASSWORD:t?.PASSWORD,HEADERS:t?.HEADERS,ENCODE_PATH:t?.ENCODE_PATH}),this.orders=new S(this.request);}};var me;(t=>{(i=>(i.ON_CHAIN="ON_CHAIN",i.OFF_CHAIN="OFF_CHAIN",i.UNDERFUNDED="UNDERFUNDED"))(t.cancellation_type||={});})(me||={});var fe;(t=>{(s=>s.FILLED="FILLED")(t.reason_code||={});})(fe||={});var f;(t=>{(o=>(o.ROYALTY="ROYALTY",o.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",o.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",o.PROTOCOL="PROTOCOL"))(t.type||={});})(f||={});var R;(t=>{(i=>(i.LISTING="LISTING",i.BID="BID",i.COLLECTION_BID="COLLECTION_BID"))(t.type||={});})(R||={});var H=(o=>(o.PENDING="PENDING",o.ACTIVE="ACTIVE",o.INACTIVE="INACTIVE",o.FILLED="FILLED",o.EXPIRED="EXPIRED",o.CANCELLED="CANCELLED",o))(H||{});var y;(t=>{(n=>(n.FULL_RESTRICTED="FULL_RESTRICTED",n.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(t.order_type||={});})(y||={});function C(e){throw new Error("Unreachable")}function h(e){if(e.type!==R.type.LISTING)throw new Error("Order type must be LISTING");let t=e.sell.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Listing sell items must either ERC721 or ERC1155")}),r=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Listing buy items must be either NATIVE or ERC20")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function x(e){if(e.type!==R.type.BID)throw new Error("Order type must be BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Bid buy items must either ERC721 or ERC1155")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function B(e){if(e.type!==R.type.COLLECTION_BID)throw new Error("Order type must be COLLECTION_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function N(e){switch(e.type){case R.type.LISTING:return h(e);case R.type.BID:return x(e);case R.type.COLLECTION_BID:return B(e);default:return C(e.type)}}function te(e){let t=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Buy items must be NATIVE, ERC20, ERC721 or ERC1155")}),r=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Sell items must be ERC20, ERC721 or ERC1155")});return {id:e.id,orderId:e.order_id,buy:t,sell:r,buyerFees:e.buyer_fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),chain:e.chain,indexedAt:e.indexed_at,blockchainMetadata:{blockNumber:e.blockchain_metadata.block_number,logIndex:e.blockchain_metadata.log_index,transactionHash:e.blockchain_metadata.transaction_hash,transactionIndex:e.blockchain_metadata.transaction_index},buyerAddress:e.buyer_address,makerAddress:e.maker_address,sellerAddress:e.seller_address,takerAddress:e.taker_address}}function k(e){return {nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}var Ye=(n=>(n[n.MAKER_ECOSYSTEM=f.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",n[n.TAKER_ECOSYSTEM=f.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",n[n.PROTOCOL=f.type.PROTOCOL]="PROTOCOL",n[n.ROYALTY=f.type.ROYALTY]="ROYALTY",n))(Ye||{}),re=(r=>(r.TRANSACTION="TRANSACTION",r.SIGNABLE="SIGNABLE",r))(re||{}),Ce=(s=>(s.APPROVAL="APPROVAL",s.FULFILL_ORDER="FULFILL_ORDER",s.CANCEL="CANCEL",s))(Ce||{}),se=(s=>(s.CREATE_LISTING="CREATE_ORDER",s.CREATE_ORDER="CREATE_ORDER",s.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",s))(se||{});var oe="ImmutableSeaport",I="1.5",M={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]};var Je={integer:0,address:zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},ne=e=>e===void 0?!1:e!=null&&(["string","number"].includes(typeof e)&&BigInt(e)===0n||Array.isArray(e)&&e.every(ne)||typeof e=="object"&&Object.values(e).every(ne)||typeof e=="boolean"&&e===!1);function Ze(e){let[,t]=e.match(/^bytes(\d+)$/)??[];return t?zeroPadValue("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),Je[e])}var A=class e{constructor(t){this.types=t;for(let r in t){let s=this.getDefaultValue(r);if(this.defaultValues[r]=s,!ne(s))throw new Error(`Got non-empty value for type ${r} in default generator: ${s}`)}}defaultValues={};static from(t,r){let{defaultValues:s}=new e(t);return r?s[r]:s}getDefaultValue(t){if(this.defaultValues[t])return this.defaultValues[t];let r=Ze(t);if(r!==void 0)return r;let s=t.match(/^(.*)(\x5b(\d*)\x5d)$/);if(s){let i=s[1],o=parseInt(s[3]);if(o>0){let d=this.getDefaultValue(i);return Array(o).fill(d)}return []}let n=this.types[t];if(n)return n.reduce((i,{name:o,type:d})=>({...i,[o]:this.getDefaultValue(d)}),{});throw new Error(`unknown type: ${t}`)}};var tt=(e,t)=>Array(e).fill(0).map((r,s)=>t(s)),ie=(e,t)=>tt(Math.ceil(e.length/t),r=>e.slice(r*t,(r+1)*t)),ye=e=>toBeHex(e.toString("hex")),_=e=>Buffer.from(e.slice(2),"hex"),V=e=>_(keccak256(e)),rt=e=>V(concat(e)),w=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),ge=(e,t=!0)=>{if(e.length===0)throw new Error("empty tree");let s=[e.map(n=>{let i=Buffer.isBuffer(n)?n:_(n);return t?V(i):i})];for(;s[s.length-1].length>1;)s.push(st(s[s.length-1]));return s[s.length-1][0]},st=e=>ie(e,2).map(rt);var dt=(e,t)=>new MerkleTree(e.map(_),V,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:_(t)}),lt=(e,t,r=`0x${"ff".repeat(64)}`)=>concat([r,`0x${e.toString(16).padStart(6,"0")}`,AbiCoder.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]),U=class{constructor(t,r,s,n,i){this.types=t;this.rootType=r;this.leafType=s;this.elements=n;this.depth=i;let o=TypedDataEncoder.from(t);this.encoder=o,this.leafHasher=d=>o.hashStruct(s,d),this.defaultNode=A.from(t,s),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=dt(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:t}=this;return w([...t],this.completedSize,this.defaultNode)}getCompleteLeaves(){let t=this.elements.map(this.leafHasher);return w([...t],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(t){let s=this.getCompleteLeaves()[t],n=this.tree.getHexProof(s,t),i=this.tree.getHexRoot();return {leaf:s,proof:n,root:i}}getEncodedProofAndSignature(t,r){let{proof:s}=this.getProof(t);return lt(t,s,r)}getDataToSign(){let t=this.getCompleteElements();for(;t.length>2;)t=ie(t,2);return t}add(t){this.elements.push(t);}getBulkOrderHash(){let t=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),r=this.getCompleteLeaves().map(_),s=ye(ge(r,!1)),n=keccak256(toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(keccak256(concat([n,s]))!==t)throw new Error("expected derived bulk order hash to match");return t}};function pt(e){return {...M,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}function ct(e){return Math.max(Math.ceil(Math.log2(e)),1)}function Ie(e,t=0,r=ct(e.length+t)){let s=pt(r),n=A.from(s,"OrderComponents"),i=[...e];return t>0&&(i=[...w([],t,n),...e]),new U(s,"BulkOrder","OrderComponents",i,r)}function Ae(e){if([0,1,2,3].includes(Number(e)))return Number(e);throw new Error(`Unknown order type ${e}`)}function z(e){if([0,1,2,3,4,5].includes(Number(e)))return Number(e);throw new Error(`Unknown item type ${e}`)}function _e(e){let r=JSON.parse(e).message;return {...r,orderType:Ae(r.orderType),salt:toBeHex(BigInt(r.salt)),offer:r.offer.map(s=>({...s,itemType:z(s.itemType)})),consideration:r.consideration.map(s=>({...s,itemType:z(s.itemType)}))}}function be(e){let t=JSON.parse(e);return {components:t.message.tree.flat(1/0).filter(s=>s.offerer!=="0x0000000000000000000000000000000000000000").map(s=>({...s,orderType:Ae(s.orderType),salt:toBeHex(BigInt(s.salt)),offer:s.offer.map(n=>({...n,itemType:z(n.itemType)})),consideration:s.consideration.map(n=>({...n,itemType:z(n.itemType)}))})),types:t.types,value:t.message}}function Le(e,t){let r=Ie(t);return t.map((s,n)=>r.getEncodedProofAndSignature(n,e))}function mt(e){switch(e.type){case"NATIVE":throw new Error("NATIVE items are not supported in the offer");case"ERC20":return {itemType:1,token:e.contract_address,identifierOrCriteria:"0",startAmount:e.amount,endAmount:e.amount};case"ERC721":return {itemType:2,token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:"1",endAmount:"1"};case"ERC1155":return {itemType:3,token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:e.amount,endAmount:e.amount};case"ERC721_COLLECTION":throw new Error("ERC721_COLLECTION items are not supported in the offer");case"ERC1155_COLLECTION":throw new Error("ERC1155_COLLECTION items are not supported in the offer");default:return C()}}function ft(e,t){switch(e.type){case"NATIVE":return {itemType:0,startAmount:e.amount,endAmount:e.amount,token:ZeroAddress,identifierOrCriteria:"0",recipient:t};case"ERC20":return {itemType:1,startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC721":return {itemType:2,startAmount:"1",endAmount:"1",token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC1155":return {itemType:3,startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC721_COLLECTION":return {itemType:4,startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC1155_COLLECTION":return {itemType:5,startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};default:return C()}}function $(e){let t=e.sell.map(mt),r=e.buy.map(o=>ft(o,e.account_address)),s=function(o){switch(o){case R.type.LISTING:return r[0];case R.type.BID:case R.type.COLLECTION_BID:return t[0];default:return C()}}(e.type),n=function(o){switch(o){case y.order_type.FULL_RESTRICTED:return 2;case y.order_type.PARTIAL_RESTRICTED:return 3;default:return C()}}(e.protocol_data.order_type),i=e.fees.map(o=>({amount:o.amount,itemType:s.itemType,recipient:o.recipient_address,token:s.token,identifierOrCriteria:s.identifierOrCriteria}));return {orderComponents:{offerer:e.account_address,zone:e.protocol_data.zone_address,offer:t,consideration:r,orderType:n,startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),zoneHash:ZeroHash,salt:e.salt,conduitKey:ZeroHash,counter:e.protocol_data.counter,totalOriginalConsiderationItems:r.length},tips:i}}function g(e,t,r){return async()=>{let s=await e.buildTransaction(),n={to:s.to,from:r,type:s.type,maxFeePerGas:s.maxFeePerGas?BigInt(s.maxFeePerGas):void 0,maxPriorityFeePerGas:s.maxPriorityFeePerGas?BigInt(s.maxPriorityFeePerGas):void 0,value:s.value?BigInt(s.value):void 0,data:s.data,nonce:s.nonce,chainId:t};return n.gasLimit=BigInt(await e.estimateGas()),n.gasLimit+=n.gasLimit/BigInt(5),n}}function Pe(e){switch(e.type){case"ERC20":return {token:e.contractAddress,amount:e.amount};case"ERC721":return {itemType:2,token:e.contractAddress,identifier:e.tokenId};case"ERC1155":return {itemType:3,token:e.contractAddress,identifier:e.tokenId,amount:e.amount};default:return C()}}function xe(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,token:e.contractAddress,identifier:e.tokenId,recipient:t};case"ERC1155":return {itemType:3,token:e.contractAddress,identifier:e.tokenId,amount:e.amount,recipient:t};case"ERC721_COLLECTION":return {itemType:2,token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};case"ERC1155_COLLECTION":return {itemType:3,token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};default:return C()}}var G=class e{constructor(t,r,s,n,i){this.seaportLibFactory=t;this.provider=r;this.seaportContractAddress=s;this.zoneContractAddress=n;this.rateLimitingKey=i;}async prepareBulkSeaportOrders(t,r){let{actions:s}=await this.createSeaportOrders(t,r),n=s.filter(c=>c.type==="approval"),i=await this.provider.getNetwork(),o=n.map(c=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(c.transactionMethods,i.chainId,t)})),d=s.find(c=>c.type==="createBulk");if(!d)throw new Error("No create bulk order action found");let p=await d.getMessageToSign(),{components:a,types:l,value:u}=be(p);return o.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(l,u)}),{actions:o,preparedOrders:a.map(c=>({orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}))}}async prepareSeaportOrder(t,r,s,n,i,o){let{actions:d}=await this.createSeaportOrder(t,r,s,n,i,o),p=[],a=d.find(m=>m.type==="approval");a&&p.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(a.transactionMethods,(await this.provider.getNetwork()).chainId,t)});let l=d.find(m=>m.type==="create");if(!l)throw new Error("No create order action found");let u=await l.getMessageToSign(),c=_e(u);return p.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromOrderComponents(c)}),{actions:p,orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}}async fulfillOrder(t,r,s,n,i){let{orderComponents:o,tips:d}=$(t),p=this.getSeaportLib(t),a=(await this.provider.getNetwork()).chainId,l={order:{parameters:o,signature:t.signature},unitsToFill:n,extraData:s,tips:d};i&&(l.considerationCriteria=i);let{actions:u}=await p.fulfillOrders({accountAddress:r,fulfillOrderDetails:[l]}),c=[],m=u.filter(E=>E.type==="approval");m.length>0&&m.forEach(E=>{c.push({type:"TRANSACTION",buildTransaction:g(E.transactionMethods,a,r),purpose:"APPROVAL"});});let O=u.find(E=>E.type==="exchange");if(!O)throw new Error("No exchange action found");return c.push({type:"TRANSACTION",buildTransaction:g(O.transactionMethods,a,r),purpose:"FULFILL_ORDER"}),{actions:c,expiration:e.getExpirationISOTimeFromExtraData(s),order:N(t)}}async fulfillBulkOrders(t,r){let s=t.map(a=>{let{orderComponents:l,tips:u}=$(a.order),c={order:{parameters:l,signature:a.order.signature},unitsToFill:a.unitsToFill,extraData:a.extraData,tips:u};return a.considerationCriteria&&a.considerationCriteria.length>0&&(c.considerationCriteria=a.considerationCriteria),c}),{actions:n}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:s,accountAddress:r}),i=[],o=n.filter(a=>a.type==="approval"),d=(await this.provider.getNetwork()).chainId;o.length>0&&o.forEach(a=>{i.push({type:"TRANSACTION",buildTransaction:g(a.transactionMethods,d,r),purpose:"APPROVAL"});});let p=n.find(a=>a.type==="exchange");if(!p)throw new Error("No exchange action found");return i.push({type:"TRANSACTION",buildTransaction:g(p.transactionMethods,(await this.provider.getNetwork()).chainId,r),purpose:"FULFILL_ORDER"}),{actions:i,expiration:s.map(a=>e.getExpirationISOTimeFromExtraData(a.extraData)).reduce((a,l)=>new Date(a)<new Date(l)?a:l)}}async cancelOrders(t,r){let s=t.map(o=>$(o).orderComponents),i=await this.getSeaportLib(t[0]).cancelOrders(s,r);return {type:"TRANSACTION",buildTransaction:g(i,(await this.provider.getNetwork()).chainId,r),purpose:"CANCEL"}}createSeaportOrders(t,r){return this.getSeaportLib().createBulkOrders(r.map(n=>{let{offerItem:i,considerationItem:o,allowPartialFills:d,orderStart:p,orderExpiry:a}=n;return {allowPartialFills:d,offer:[Pe(i)],consideration:[xe(o,t)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(a.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),t)}createSeaportOrder(t,r,s,n,i,o){return this.getSeaportLib().createOrder({allowPartialFills:n,offer:[Pe(r)],consideration:[xe(s,t)],startTime:(i.getTime()/1e3).toFixed(0),endTime:(o.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},t)}async getTypedDataFromBulkOrderComponents(t,r){delete t.EIP712Domain;let{chainId:s}=await this.provider.getNetwork();return {domain:{name:oe,version:I,chainId:s,verifyingContract:this.seaportContractAddress},types:t,value:r}}async getTypedDataFromOrderComponents(t){let{chainId:r}=await this.provider.getNetwork();return {domain:{name:oe,version:I,chainId:r,verifyingContract:this.seaportContractAddress},types:M,value:t}}getSeaportLib(t){let r=t?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(r)}static getExpirationISOTimeFromExtraData(t){let r=t.slice(44,60),s=parseInt(r,16);return new Date(s*1e3).toISOString()}};function W(e){switch(e.itemType){case 0:return {type:"NATIVE",amount:e.startAmount};case 1:return {type:"ERC20",contract_address:e.token,amount:e.startAmount};case 2:return {type:"ERC721",contract_address:e.token,token_id:e.identifierOrCriteria};case 3:return {type:"ERC1155",contract_address:e.token,token_id:e.identifierOrCriteria,amount:e.startAmount};case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};default:return C(e.itemType)}}function ae(e){if(e.itemType!==1)throw new Error(`Expected ERC20 item, got ${e.itemType}`);return {type:"ERC20",contract_address:e.token,amount:e.startAmount}}function Be(e){switch(e.itemType){case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};case 1:case 0:case 2:case 3:throw new Error(`Unsupported item type ${e.itemType}`);default:return C(e.itemType)}}function K(e){switch(e){case 2:return y.order_type.FULL_RESTRICTED;case 3:return y.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${e}`);default:return C()}}var Y=class{constructor(t,r,s){this.orderbookService=t;this.chainName=r;this.seaportAddress=s;}async fulfillmentData(t){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:t})}async getListing(t){return this.orderbookService.getListing({chainName:this.chainName,listingId:t})}async getBid(t){return this.orderbookService.getBid({chainName:this.chainName,bidId:t})}async getCollectionBid(t){return this.orderbookService.getCollectionBid({chainName:this.chainName,collectionBidId:t})}async getTrade(t){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:t})}async listListings(t){return this.orderbookService.listListings({chainName:this.chainName,...t})}async listBids(t){return this.orderbookService.listBids({chainName:this.chainName,...t})}async listCollectionBids(t){return this.orderbookService.listCollectionBids({chainName:this.chainName,...t})}async listTrades(t){return this.orderbookService.listTrades({chainName:this.chainName,...t})}async cancelOrders(t,r,s){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:r,orders:t,signature:s}})}async createListing({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a listing");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a listing");if(![2,3].includes(r.offer[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be listed");if(![0,1].includes(r.consideration[0].itemType))throw new Error("Only Native / ERC20 tokens can be used as currency items in a listing");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:I,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(W),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a bid");if(![2,3].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be bid against");return this.orderbookService.createBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:I,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a collection bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a collection bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a collection bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");return this.orderbookService.createCollectionBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(Be),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:I,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}};var J=class{constructor(t,r,s,n){this.chainName=r;this.seaportAddress=s;this.orderbookClient=new P({BASE:t,HEADERS:n?{"x-api-key":n}:void 0});}orderbookClient;create(){return new Y(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var yt="imtbl-zkevm-testnet",gt="imtbl-zkevm-mainnet";function Z(e,t){let r=new FetchRequest(e);return t&&r.setHeader("x-api-key",t),new JsonRpcProvider(r)}function ke(e){switch(e.baseConfig.environment){case Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:yt,provider:Z("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:gt,provider:Z("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}var X=class{constructor(t,r){this.defaultSeaportContractAddress=t;this.provider=r;}create(t){let r=t??this.defaultSeaportContractAddress,s=this.provider;return s.getSigner=async function(i){i==null&&(i=0);let o=this.send("eth_accounts",[]);if(typeof i=="number"){let d=await o;if(i>=d.length)throw new Error("no such account");return new JsonRpcSigner(this,d[i])}return new JsonRpcSigner(this,i)},new Seaport(s,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}};var de=class e{apiClient;seaport;orderbookConfig;constructor(t){let s={...ke(t),...t.overrides};if(t.overrides?.jsonRpcProviderUrl&&(s.provider=Z(t.overrides?.jsonRpcProviderUrl,t.baseConfig.rateLimitingKey)),!s)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=s;let{apiEndpoint:n,chainName:i}=this.orderbookConfig;if(!n)throw new Error("API endpoint must be provided");this.apiClient=new J(n,i,this.orderbookConfig.seaportContractAddress,t.baseConfig.rateLimitingKey).create();let o=new X(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new G(o,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,t.baseConfig.rateLimitingKey);}static defaultOrderExpiry(){return new Date(Date.now()+1e3*60*60*24*365*2)}config(){return this.orderbookConfig}async getListing(t){let r=await this.apiClient.getListing(t);return {result:h(r.result)}}async getBid(t){let r=await this.apiClient.getBid(t);return {result:x(r.result)}}async getCollectionBid(t){let r=await this.apiClient.getCollectionBid(t);return {result:B(r.result)}}async getTrade(t){let r=await this.apiClient.getTrade(t);return {result:te(r.result)}}async listListings(t){let r=await this.apiClient.listListings(t);return {page:k(r.page),result:r.result.map(h)}}async listBids(t){let r=await this.apiClient.listBids(t);return {page:k(r.page),result:r.result.map(x)}}async listCollectionBids(t){let r=await this.apiClient.listCollectionBids(t);return {page:k(r.page),result:r.result.map(B)}}async listTrades(t){let r=await this.apiClient.listTrades(t);return {page:k(r.page),result:r.result.map(te)}}async prepareBulkListings({makerAddress:t,listingParams:r}){if(r.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(r.length===1){let o=await this.seaport.prepareSeaportOrder(t,r[0].sell,r[0].buy,r[0].sell.type==="ERC1155",r[0].orderStart||new Date,r[0].orderExpiry||e.defaultOrderExpiry());return {actions:o.actions,completeListings:async d=>{let p=await this.createListing({makerFees:r[0].makerFees,orderComponents:o.orderComponents,orderHash:o.orderHash,orderSignature:typeof d=="string"?d:d[0]});return {result:[{success:!0,orderHash:o.orderHash,order:p.result}]}}}}if(await this.orderbookConfig.provider.getCode(t)!=="0x"){track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:t,listingsCount:r.length});let o=await Promise.all(r.map(a=>this.seaport.prepareSeaportOrder(t,a.sell,a.buy,a.sell.type==="ERC1155",a.orderStart||new Date,a.orderExpiry||e.defaultOrderExpiry()))),d=[];return {actions:o.flatMap(a=>{let l=[];return a.actions.forEach(u=>{if(u.type==="TRANSACTION"){let c=a.orderComponents.offer[0].token;d.includes(c)||(d.push(c),l.push(u));}else l.push(u);}),l}),completeListings:async a=>{if(typeof a=="string")throw new Error("A signature per listing must be provided for smart contract wallets");return {result:(await Promise.all(o.map((c,m)=>{let O=a[m];return this.apiClient.createListing({makerFees:r[m].makerFees,orderComponents:c.orderComponents,orderHash:c.orderHash,orderSignature:O}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:o[m].orderHash,order:c?h(c.result):void 0}))}}}}track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:t,listingsCount:r.length});let{actions:n,preparedOrders:i}=await this.seaport.prepareBulkSeaportOrders(t,r.map(o=>({offerItem:o.sell,considerationItem:o.buy,allowPartialFills:o.sell.type==="ERC1155",orderStart:o.orderStart||new Date,orderExpiry:o.orderExpiry||e.defaultOrderExpiry()})));return {actions:n,completeListings:async o=>{let d=typeof o=="object";if(d&&o.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let p=i.map(c=>c.orderComponents),a=d?o[0]:o,l=Le(a,p);return {result:(await Promise.all(p.map((c,m)=>{let O=l[m],E=i[m],ve=r[m];return this.apiClient.createListing({orderComponents:c,orderHash:E.orderHash,orderSignature:O,makerFees:ve.makerFees}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:i[m].orderHash,order:c?h(c.result):void 0}))}}}}async prepareListing({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,r.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createListing(t){let r=await this.apiClient.createListing(t);return {result:h(r.result)}}async prepareBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,s.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createBid(t){let r=await this.apiClient.createBid(t);return {result:x(r.result)}}async prepareCollectionBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,!0,n||new Date,i||e.defaultOrderExpiry())}async createCollectionBid(t){let r=await this.apiClient.createCollectionBid(t);return {result:B(r.result)}}async fulfillOrder(t,r,s,n,i){let o={order_id:t,taker_address:r,fees:s.map(u=>({type:f.type.TAKER_ECOSYSTEM,amount:u.amount,recipient_address:u.recipientAddress}))},d=i?[{identifier:i,proof:[]}]:void 0;i&&(o.token_id=i);let p=await this.apiClient.fulfillmentData([o]);if(p.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment data: ${p.result.unfulfillable_orders[0].reason}`);if(p.result.fulfillable_orders?.length!==1)throw new Error("unexpected fulfillable order result length");let a=p.result.fulfillable_orders[0].extra_data,l=p.result.fulfillable_orders[0].order;if(l.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${l.status}`);return this.seaport.fulfillOrder(l,r,a,n,d)}async fulfillBulkOrders(t,r){let s=t.map(i=>{let o="listingId"in i;return {orderId:o?i.listingId:i.orderId,takerFees:i.takerFees,amountToFill:i.amountToFill,tokenId:o?void 0:i.tokenId}}),n=await this.apiClient.fulfillmentData(s.map(i=>({order_id:i.orderId,taker_address:r,fees:i.takerFees.map(o=>({type:f.type.TAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),token_id:i?.tokenId})));try{let i=n.result.fulfillable_orders.map(o=>{let d=s.find(a=>a.orderId===o.order.id&&a.tokenId===o.token_id);if(!d){let a=`Could not find order for order ${o.order.id}`;throw o.token_id&&(a+=` and token ID ${o.token_id}`),new Error(a)}let p=[];return d.tokenId&&p.push({identifier:d.tokenId,proof:[]}),{extraData:o.extra_data,order:o.order,unitsToFill:d.amountToFill,considerationCriteria:p}});return {...await this.seaport.fulfillBulkOrders(i,r),fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,tokenId:o.token_id,reason:o.reason})),sufficientBalance:!0}}catch(i){if(String(i).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,reason:o.reason})),sufficientBalance:!1};throw i}}async prepareOrderCancellations(t){let s={name:"imtbl-order-book",chainId:(await this.orderbookConfig.provider.getNetwork()).chainId,verifyingContract:this.orderbookConfig.seaportContractAddress},n={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},i={orders:t.map(o=>({id:o}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:s,types:n,value:i}}}}async cancelOrders(t,r,s){return this.apiClient.cancelOrders(t,r,s)}async cancelOrdersOnChain(t,r){let s=Promise.all(t.map(l=>this.apiClient.getListing(l).catch(u=>{if(u.status!==404)throw u}))),n=Promise.all(t.map(l=>this.apiClient.getBid(l).catch(u=>{if(u.status!==404)throw u}))),i=Promise.all(t.map(l=>this.apiClient.getCollectionBid(l).catch(u=>{if(u.status!==404)throw u}))),o=[await Promise.all([s,n,i])].flat(2).filter(l=>l!==void 0).map(l=>l.result);if(o.length!==t.length){let l=t.filter(u=>!o.some(c=>c.id===u));throw new Error(`Orders ${l} not found`)}for(let l of o)if(l.account_address!==r.toLowerCase())throw new Error(`Only account ${l.account_address} can cancel order ${l.id}`);let d=o.map(l=>l.protocol_data.seaport_address);if(new Set(d).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(o,r)}}};var ht={estimatedFulfillmentGasGwei:4e5};
9
+ var b=class{constructor(t){this.config=t;}};var T=class extends Error{url;status;statusText;body;request;constructor(t,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=t;}};var v=class extends Error{constructor(t){super(t),this.name="CancelError";}get isCancelled(){return !0}},L=class{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(t){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((r,s)=>{this._resolve=r,this._reject=s;let n=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(d));},i=d=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(d));},o=d=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(d);};return Object.defineProperty(o,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(o,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(o,"isCancelled",{get:()=>this._isCancelled}),t(n,i,o)});}then(t,r){return this._promise.then(t,r)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(let t of this._cancelHandlers)t();}catch(t){console.warn("Cancellation threw an error",t);return}this._cancelHandlers.length=0,this._reject?.(new v("Request aborted"));}}get isCancelled(){return this._isCancelled}};var ee=e=>e!=null,F=e=>typeof e=="string",Q=e=>F(e)&&e!=="",ce=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof pe,qe=e=>e>=200&&e<300,He=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Me=e=>{let t=[],r=(n,i)=>{t.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`);},s=(n,i)=>{ee(i)&&(Array.isArray(i)?i.forEach(o=>{s(n,o);}):typeof i=="object"?Object.entries(i).forEach(([o,d])=>{s(`${n}[${o}]`,d);}):r(n,i));};return Object.entries(e).forEach(([n,i])=>{s(n,i);}),t.length>0?`?${t.join("&")}`:""},Ve=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(i,o)=>t.path?.hasOwnProperty(o)?r(String(t.path[o])):i),n=`${e.BASE}${s}`;return t.query?`${n}${Me(t.query)}`:n},Ue=e=>{if(e.formData){let t=new pe,r=(s,n)=>{F(n)||ce(n)?t.append(s,n):t.append(s,JSON.stringify(n));};return Object.entries(e.formData).filter(([s,n])=>ee(n)).forEach(([s,n])=>{Array.isArray(n)?n.forEach(i=>r(s,i)):r(s,n);}),t}},D=async(e,t)=>typeof t=="function"?t(e):t,ze=async(e,t,r)=>{let s=await D(t,e.TOKEN),n=await D(t,e.USERNAME),i=await D(t,e.PASSWORD),o=await D(t,e.HEADERS),d=typeof r?.getHeaders=="function"&&r?.getHeaders()||{},p=Object.entries({Accept:"application/json",...o,...t.headers,...d}).filter(([a,l])=>ee(l)).reduce((a,[l,u])=>({...a,[l]:String(u)}),{});if(Q(s)&&(p.Authorization=`Bearer ${s}`),Q(n)&&Q(i)){let a=He(`${n}:${i}`);p.Authorization=`Basic ${a}`;}return t.body&&(t.mediaType?p["Content-Type"]=t.mediaType:ce(t.body)?p["Content-Type"]=t.body.type||"application/octet-stream":F(t.body)?p["Content-Type"]="text/plain":Fe(t.body)||(p["Content-Type"]="application/json")),p},$e=e=>{if(e.body)return e.body},Ge=async(e,t,r,s,n,i,o)=>{let d=le.CancelToken.source(),p={url:r,headers:i,data:s??n,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:d.token};o(()=>d.cancel("The user aborted a request."));try{return await le.request(p)}catch(a){let l=a;if(l.response)return l.response;throw a}},je=(e,t)=>{if(t){let r=e.headers[t];if(F(r))return r}},We=e=>{if(e.status!==204)return e.data},Ke=(e,t)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(s)throw new T(e,t,s);if(!t.ok)throw new T(e,t,"Generic Error")},ue=(e,t)=>new L(async(r,s,n)=>{try{let i=Ve(e,t),o=Ue(t),d=$e(t),p=await ze(e,t,o);if(!n.isCancelled){let a=await Ge(e,t,i,d,o,p,n),l=We(a),u=je(a,t.responseHeader),c={url:i,ok:qe(a.status),status:a.status,statusText:a.statusText,body:u??l};Ke(t,c),r(c.body);}}catch(i){s(i);}});var q=class extends b{constructor(t){super(t);}request(t){return ue(this.config,t)}};var S=class{constructor(t){this.httpRequest=t;}cancelOrders({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",401:"Unauthorised Request (401)",404:"The specified resource was not found (404)",429:"Too Many Requests (429)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listListings({chainName:t,status:r,sellItemContractAddress:s,buyItemType:n,buyItemContractAddress:i,accountAddress:o,sellItemMetadataId:d,sellItemTokenId:p,fromUpdatedAt:a,pageSize:l,sortBy:u,sortDirection:c,pageCursor:m}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},query:{status:r,sell_item_contract_address:s,buy_item_type:n,buy_item_contract_address:i,account_address:o,sell_item_metadata_id:d,sell_item_token_id:p,from_updated_at:a,page_size:l,sort_by:u,sort_direction:c,page_cursor:m},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,buyItemMetadataId:o,buyItemTokenId:d,fromUpdatedAt:p,pageSize:a,sortBy:l,sortDirection:u,pageCursor:c}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,buy_item_metadata_id:o,buy_item_token_id:d,from_updated_at:p,page_size:a,sort_by:l,sort_direction:u,page_cursor:c},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listCollectionBids({chainName:t,status:r,buyItemContractAddress:s,sellItemContractAddress:n,accountAddress:i,fromUpdatedAt:o,pageSize:d,sortBy:p,sortDirection:a,pageCursor:l}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},query:{status:r,buy_item_contract_address:s,sell_item_contract_address:n,account_address:i,from_updated_at:o,page_size:d,sort_by:p,sort_direction:a,page_cursor:l},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createCollectionBid({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/collection-bids",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}getListing({chainName:t,listingId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:t,listing_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getBid({chainName:t,bidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/bids/{bid_id}",path:{chain_name:t,bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getCollectionBid({chainName:t,collectionBidId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/collection-bids/{collection_bid_id}",path:{chain_name:t,collection_bid_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:t,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:t},body:r,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:t,accountAddress:r,sellItemContractAddress:s,fromIndexedAt:n,pageSize:i,sortBy:o,sortDirection:d,pageCursor:p}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:t},query:{account_address:r,sell_item_contract_address:s,from_indexed_at:n,page_size:i,sort_by:o,sort_direction:d,page_cursor:p},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:t,tradeId:r}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:t,trade_id:r},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}};var P=class{orders;request;constructor(t,r=q){this.request=new r({BASE:t?.BASE??"https://api.immutable.com",VERSION:t?.VERSION??"1.0.0",WITH_CREDENTIALS:t?.WITH_CREDENTIALS??!1,CREDENTIALS:t?.CREDENTIALS??"include",TOKEN:t?.TOKEN,USERNAME:t?.USERNAME,PASSWORD:t?.PASSWORD,HEADERS:t?.HEADERS,ENCODE_PATH:t?.ENCODE_PATH}),this.orders=new S(this.request);}};var me;(t=>{(i=>(i.ON_CHAIN="ON_CHAIN",i.OFF_CHAIN="OFF_CHAIN",i.UNDERFUNDED="UNDERFUNDED"))(t.cancellation_type||={});})(me||={});var fe;(t=>{(s=>s.FILLED="FILLED")(t.reason_code||={});})(fe||={});var f;(t=>{(o=>(o.ROYALTY="ROYALTY",o.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",o.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",o.PROTOCOL="PROTOCOL"))(t.type||={});})(f||={});var R;(t=>{(i=>(i.LISTING="LISTING",i.BID="BID",i.COLLECTION_BID="COLLECTION_BID"))(t.type||={});})(R||={});var H=(o=>(o.PENDING="PENDING",o.ACTIVE="ACTIVE",o.INACTIVE="INACTIVE",o.FILLED="FILLED",o.EXPIRED="EXPIRED",o.CANCELLED="CANCELLED",o))(H||{});var y;(t=>{(n=>(n.FULL_RESTRICTED="FULL_RESTRICTED",n.PARTIAL_RESTRICTED="PARTIAL_RESTRICTED"))(t.order_type||={});})(y||={});function C(e){throw new Error("Unreachable")}function h(e){if(e.type!==R.type.LISTING)throw new Error("Order type must be LISTING");let t=e.sell.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Listing sell items must either ERC721 or ERC1155")}),r=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Listing buy items must be either NATIVE or ERC20")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function B(e){if(e.type!==R.type.BID)throw new Error("Order type must be BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Bid buy items must either ERC721 or ERC1155")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function x(e){if(e.type!==R.type.COLLECTION_BID)throw new Error("Order type must be COLLECTION_BID");let t=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid sell items must be ERC20")}),r=e.buy.map(s=>{if(s.type==="ERC721_COLLECTION")return {type:"ERC721_COLLECTION",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC1155_COLLECTION")return {type:"ERC1155_COLLECTION",contractAddress:s.contract_address,amount:s.amount};throw new Error("Collection bid buy items must either ERC721_COLLECTION or ERC1155_COLLECTION")});return {id:e.id,type:e.type,chain:e.chain,accountAddress:e.account_address,sell:t,buy:r,fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),status:e.status,fillStatus:e.fill_status,startAt:e.start_at,endAt:e.end_at,salt:e.salt,signature:e.signature,orderHash:e.order_hash,protocolData:{orderType:e.protocol_data.order_type,counter:e.protocol_data.counter,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},createdAt:e.created_at,updatedAt:e.updated_at}}function N(e){switch(e.type){case R.type.LISTING:return h(e);case R.type.BID:return B(e);case R.type.COLLECTION_BID:return x(e);default:return C(e.type)}}function te(e){let t=e.buy.map(s=>{if(s.type==="NATIVE")return {type:"NATIVE",amount:s.amount};if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Buy items must be NATIVE, ERC20, ERC721 or ERC1155")}),r=e.sell.map(s=>{if(s.type==="ERC20")return {type:"ERC20",contractAddress:s.contract_address,amount:s.amount};if(s.type==="ERC721")return {type:"ERC721",contractAddress:s.contract_address,tokenId:s.token_id};if(s.type==="ERC1155")return {type:"ERC1155",contractAddress:s.contract_address,tokenId:s.token_id,amount:s.amount};throw new Error("Sell items must be ERC20, ERC721 or ERC1155")});return {id:e.id,orderId:e.order_id,buy:t,sell:r,buyerFees:e.buyer_fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),fees:e.fees.map(s=>({amount:s.amount,recipientAddress:s.recipient_address,type:s.type})),chain:e.chain,indexedAt:e.indexed_at,blockchainMetadata:{blockNumber:e.blockchain_metadata.block_number,logIndex:e.blockchain_metadata.log_index,transactionHash:e.blockchain_metadata.transaction_hash,transactionIndex:e.blockchain_metadata.transaction_index},buyerAddress:e.buyer_address,makerAddress:e.maker_address,sellerAddress:e.seller_address,takerAddress:e.taker_address}}function k(e){return {nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}var Ye=(n=>(n[n.MAKER_ECOSYSTEM=f.type.MAKER_ECOSYSTEM]="MAKER_ECOSYSTEM",n[n.TAKER_ECOSYSTEM=f.type.TAKER_ECOSYSTEM]="TAKER_ECOSYSTEM",n[n.PROTOCOL=f.type.PROTOCOL]="PROTOCOL",n[n.ROYALTY=f.type.ROYALTY]="ROYALTY",n))(Ye||{}),re=(r=>(r.TRANSACTION="TRANSACTION",r.SIGNABLE="SIGNABLE",r))(re||{}),Ce=(s=>(s.APPROVAL="APPROVAL",s.FULFILL_ORDER="FULFILL_ORDER",s.CANCEL="CANCEL",s))(Ce||{}),se=(s=>(s.CREATE_LISTING="CREATE_ORDER",s.CREATE_ORDER="CREATE_ORDER",s.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION",s))(se||{});var oe="ImmutableSeaport",O="1.5",M={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]};var Je={integer:0,address:zeroPadValue("0x",20),bool:!1,bytes:"0x",string:""},ne=e=>e===void 0?!1:e!=null&&(["string","number"].includes(typeof e)&&BigInt(e)===0n||Array.isArray(e)&&e.every(ne)||typeof e=="object"&&Object.values(e).every(ne)||typeof e=="boolean"&&e===!1);function Ze(e){let[,t]=e.match(/^bytes(\d+)$/)??[];return t?zeroPadValue("0x",parseInt(t)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),Je[e])}var A=class e{constructor(t){this.types=t;for(let r in t){let s=this.getDefaultValue(r);if(this.defaultValues[r]=s,!ne(s))throw new Error(`Got non-empty value for type ${r} in default generator: ${s}`)}}defaultValues={};static from(t,r){let{defaultValues:s}=new e(t);return r?s[r]:s}getDefaultValue(t){if(this.defaultValues[t])return this.defaultValues[t];let r=Ze(t);if(r!==void 0)return r;let s=t.match(/^(.*)(\x5b(\d*)\x5d)$/);if(s){let i=s[1],o=parseInt(s[3]);if(o>0){let d=this.getDefaultValue(i);return Array(o).fill(d)}return []}let n=this.types[t];if(n)return n.reduce((i,{name:o,type:d})=>({...i,[o]:this.getDefaultValue(d)}),{});throw new Error(`unknown type: ${t}`)}};var tt=(e,t)=>Array(e).fill(0).map((r,s)=>t(s)),ie=(e,t)=>tt(Math.ceil(e.length/t),r=>e.slice(r*t,(r+1)*t)),ye=e=>toBeHex(e.toString("hex")),_=e=>Buffer.from(e.slice(2),"hex"),V=e=>_(keccak256(e)),rt=e=>V(concat(e)),w=(e,t,r)=>(t>e.length&&e.push(...Array(t-e.length).fill(r)),e),ge=(e,t=!0)=>{if(e.length===0)throw new Error("empty tree");let s=[e.map(n=>{let i=Buffer.isBuffer(n)?n:_(n);return t?V(i):i})];for(;s[s.length-1].length>1;)s.push(st(s[s.length-1]));return s[s.length-1][0]},st=e=>ie(e,2).map(rt);var dt=(e,t)=>new MerkleTree(e.map(_),V,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:_(t)}),lt=(e,t,r=`0x${"ff".repeat(64)}`)=>concat([r,`0x${e.toString(16).padStart(6,"0")}`,AbiCoder.defaultAbiCoder().encode([`uint256[${t.length}]`],[t])]),U=class{constructor(t,r,s,n,i){this.types=t;this.rootType=r;this.leafType=s;this.elements=n;this.depth=i;let o=TypedDataEncoder.from(t);this.encoder=o,this.leafHasher=d=>o.hashStruct(s,d),this.defaultNode=A.from(t,s),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=dt(this.getCompleteLeaves(),this.defaultLeaf);}tree;leafHasher;defaultNode;defaultLeaf;encoder;get completedSize(){return 2**this.depth}getCompleteElements(){let{elements:t}=this;return w([...t],this.completedSize,this.defaultNode)}getCompleteLeaves(){let t=this.elements.map(this.leafHasher);return w([...t],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(t){let s=this.getCompleteLeaves()[t],n=this.tree.getHexProof(s,t),i=this.tree.getHexRoot();return {leaf:s,proof:n,root:i}}getEncodedProofAndSignature(t,r){let{proof:s}=this.getProof(t);return lt(t,s,r)}getDataToSign(){let t=this.getCompleteElements();for(;t.length>2;)t=ie(t,2);return t}add(t){this.elements.push(t);}getBulkOrderHash(){let t=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),r=this.getCompleteLeaves().map(_),s=ye(ge(r,!1)),n=keccak256(toUtf8Bytes(this.encoder.types.BulkOrder[0].type));if(keccak256(concat([n,s]))!==t)throw new Error("expected derived bulk order hash to match");return t}};function pt(e){return {...M,BulkOrder:[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}]}}function ct(e){return Math.max(Math.ceil(Math.log2(e)),1)}function Oe(e,t=0,r=ct(e.length+t)){let s=pt(r),n=A.from(s,"OrderComponents"),i=[...e];return t>0&&(i=[...w([],t,n),...e]),new U(s,"BulkOrder","OrderComponents",i,r)}function Ae(e){if([0,1,2,3].includes(Number(e)))return Number(e);throw new Error(`Unknown order type ${e}`)}function z(e){if([0,1,2,3,4,5].includes(Number(e)))return Number(e);throw new Error(`Unknown item type ${e}`)}function _e(e){let r=JSON.parse(e).message;return {...r,orderType:Ae(r.orderType),salt:toBeHex(BigInt(r.salt)),offer:r.offer.map(s=>({...s,itemType:z(s.itemType)})),consideration:r.consideration.map(s=>({...s,itemType:z(s.itemType)}))}}function be(e){let t=JSON.parse(e);return {components:t.message.tree.flat(1/0).filter(s=>s.offerer!=="0x0000000000000000000000000000000000000000").map(s=>({...s,orderType:Ae(s.orderType),salt:toBeHex(BigInt(s.salt)),offer:s.offer.map(n=>({...n,itemType:z(n.itemType)})),consideration:s.consideration.map(n=>({...n,itemType:z(n.itemType)}))})),types:t.types,value:t.message}}function Le(e,t){let r=Oe(t);return t.map((s,n)=>r.getEncodedProofAndSignature(n,e))}function mt(e){switch(e.type){case"NATIVE":throw new Error("NATIVE items are not supported in the offer");case"ERC20":return {itemType:1 .valueOf(),token:e.contract_address,identifierOrCriteria:"0",startAmount:e.amount,endAmount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:"1",endAmount:"1"};case"ERC1155":return {itemType:3 .valueOf(),token:e.contract_address,identifierOrCriteria:e.token_id,startAmount:e.amount,endAmount:e.amount};case"ERC721_COLLECTION":throw new Error("ERC721_COLLECTION items are not supported in the offer");case"ERC1155_COLLECTION":throw new Error("ERC1155_COLLECTION items are not supported in the offer");default:return C()}}function ft(e,t){switch(e.type){case"NATIVE":return {itemType:0 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:ZeroAddress,identifierOrCriteria:"0",recipient:t};case"ERC20":return {itemType:1 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC721":return {itemType:2 .valueOf(),startAmount:"1",endAmount:"1",token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:e.token_id,recipient:t};case"ERC721_COLLECTION":return {itemType:4 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};case"ERC1155_COLLECTION":return {itemType:5 .valueOf(),startAmount:e.amount,endAmount:e.amount,token:e.contract_address,identifierOrCriteria:"0",recipient:t};default:return C()}}function G(e){let t=e.sell.map(mt),r=e.buy.map(o=>ft(o,e.account_address)),s=function(o){switch(o){case R.type.LISTING:return r[0];case R.type.BID:case R.type.COLLECTION_BID:return t[0];default:return C()}}(e.type),n=function(o){switch(o){case y.order_type.FULL_RESTRICTED:return 2;case y.order_type.PARTIAL_RESTRICTED:return 3;default:return C()}}(e.protocol_data.order_type),i=e.fees.map(o=>({amount:o.amount,itemType:s.itemType,recipient:o.recipient_address,token:s.token,identifierOrCriteria:s.identifierOrCriteria}));return {orderComponents:{offerer:e.account_address,zone:e.protocol_data.zone_address,offer:t,consideration:r,orderType:n.valueOf(),startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),zoneHash:ZeroHash,salt:e.salt,conduitKey:ZeroHash,counter:e.protocol_data.counter,totalOriginalConsiderationItems:r.length},tips:i}}function g(e,t,r){return async()=>{let s=await e.buildTransaction(),n={to:s.to,from:r,type:s.type,maxFeePerGas:s.maxFeePerGas?BigInt(s.maxFeePerGas):void 0,maxPriorityFeePerGas:s.maxPriorityFeePerGas?BigInt(s.maxPriorityFeePerGas):void 0,value:s.value?BigInt(s.value):void 0,data:s.data,nonce:s.nonce,chainId:t};return n.gasLimit=BigInt(await e.estimateGas()),n.gasLimit+=n.gasLimit/BigInt(5),n}}function Pe(e){switch(e.type){case"ERC20":return {token:e.contractAddress,amount:e.amount};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount};default:return C()}}function Be(e,t){switch(e.type){case"NATIVE":return {amount:e.amount,recipient:t};case"ERC20":return {token:e.contractAddress,amount:e.amount,recipient:t};case"ERC721":return {itemType:2 .valueOf(),token:e.contractAddress,identifier:e.tokenId,recipient:t};case"ERC1155":return {itemType:3 .valueOf(),token:e.contractAddress,identifier:e.tokenId,amount:e.amount,recipient:t};case"ERC721_COLLECTION":return {itemType:2 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};case"ERC1155_COLLECTION":return {itemType:3 .valueOf(),token:e.contractAddress,amount:e.amount,identifiers:[],recipient:t};default:return C()}}var j=class e{constructor(t,r,s,n,i){this.seaportLibFactory=t;this.provider=r;this.seaportContractAddress=s;this.zoneContractAddress=n;this.rateLimitingKey=i;}async prepareBulkSeaportOrders(t,r){let{actions:s}=await this.createSeaportOrders(t,r),n=s.filter(c=>c.type==="approval"),i=await this.provider.getNetwork(),o=n.map(c=>({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(c.transactionMethods,i.chainId,t)})),d=s.find(c=>c.type==="createBulk");if(!d)throw new Error("No create bulk order action found");let p=await d.getMessageToSign(),{components:a,types:l,value:u}=be(p);return o.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromBulkOrderComponents(l,u)}),{actions:o,preparedOrders:a.map(c=>({orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}))}}async prepareSeaportOrder(t,r,s,n,i,o){let{actions:d}=await this.createSeaportOrder(t,r,s,n,i,o),p=[],a=d.find(m=>m.type==="approval");a&&p.push({type:"TRANSACTION",purpose:"APPROVAL",buildTransaction:g(a.transactionMethods,(await this.provider.getNetwork()).chainId,t)});let l=d.find(m=>m.type==="create");if(!l)throw new Error("No create order action found");let u=await l.getMessageToSign(),c=_e(u);return p.push({type:"SIGNABLE",purpose:"CREATE_ORDER",message:await this.getTypedDataFromOrderComponents(c)}),{actions:p,orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}}async fulfillOrder(t,r,s,n,i){let{orderComponents:o,tips:d}=G(t),p=this.getSeaportLib(t),a=(await this.provider.getNetwork()).chainId,l={order:{parameters:o,signature:t.signature},unitsToFill:n,extraData:s,tips:d};i&&(l.considerationCriteria=i);let{actions:u}=await p.fulfillOrders({accountAddress:r,fulfillOrderDetails:[l]}),c=[],m=u.filter(E=>E.type==="approval");m.length>0&&m.forEach(E=>{c.push({type:"TRANSACTION",buildTransaction:g(E.transactionMethods,a,r),purpose:"APPROVAL"});});let I=u.find(E=>E.type==="exchange");if(!I)throw new Error("No exchange action found");return c.push({type:"TRANSACTION",buildTransaction:g(I.transactionMethods,a,r),purpose:"FULFILL_ORDER"}),{actions:c,expiration:e.getExpirationISOTimeFromExtraData(s),order:N(t)}}async fulfillBulkOrders(t,r){let s=t.map(a=>{let{orderComponents:l,tips:u}=G(a.order),c={order:{parameters:l,signature:a.order.signature},unitsToFill:a.unitsToFill,extraData:a.extraData,tips:u};return a.considerationCriteria&&a.considerationCriteria.length>0&&(c.considerationCriteria=a.considerationCriteria),c}),{actions:n}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:s,accountAddress:r}),i=[],o=n.filter(a=>a.type==="approval"),d=(await this.provider.getNetwork()).chainId;o.length>0&&o.forEach(a=>{i.push({type:"TRANSACTION",buildTransaction:g(a.transactionMethods,d,r),purpose:"APPROVAL"});});let p=n.find(a=>a.type==="exchange");if(!p)throw new Error("No exchange action found");return i.push({type:"TRANSACTION",buildTransaction:g(p.transactionMethods,(await this.provider.getNetwork()).chainId,r),purpose:"FULFILL_ORDER"}),{actions:i,expiration:s.map(a=>e.getExpirationISOTimeFromExtraData(a.extraData)).reduce((a,l)=>new Date(a)<new Date(l)?a:l)}}async cancelOrders(t,r){let s=t.map(o=>G(o).orderComponents),i=await this.getSeaportLib(t[0]).cancelOrders(s,r);return {type:"TRANSACTION",buildTransaction:g(i,(await this.provider.getNetwork()).chainId,r),purpose:"CANCEL"}}createSeaportOrders(t,r){return this.getSeaportLib().createBulkOrders(r.map(n=>{let{offerItem:i,considerationItem:o,allowPartialFills:d,orderStart:p,orderExpiry:a}=n;return {allowPartialFills:d,offer:[Pe(i)],consideration:[Be(o,t)],startTime:(p.getTime()/1e3).toFixed(0),endTime:(a.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0}}),t)}createSeaportOrder(t,r,s,n,i,o){return this.getSeaportLib().createOrder({allowPartialFills:n,offer:[Pe(r)],consideration:[Be(s,t)],startTime:(i.getTime()/1e3).toFixed(0),endTime:(o.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},t)}async getTypedDataFromBulkOrderComponents(t,r){delete t.EIP712Domain;let{chainId:s}=await this.provider.getNetwork();return {domain:{name:oe,version:O,chainId:s,verifyingContract:this.seaportContractAddress},types:t,value:r}}async getTypedDataFromOrderComponents(t){let{chainId:r}=await this.provider.getNetwork();return {domain:{name:oe,version:O,chainId:r,verifyingContract:this.seaportContractAddress},types:M,value:t}}getSeaportLib(t){let r=t?.protocol_data?.seaport_address??this.seaportContractAddress;return this.seaportLibFactory.create(r)}static getExpirationISOTimeFromExtraData(t){let r=t.slice(44,60),s=parseInt(r,16);return new Date(s*1e3).toISOString()}};function W(e){switch(e.itemType){case 0:return {type:"NATIVE",amount:e.startAmount};case 1:return {type:"ERC20",contract_address:e.token,amount:e.startAmount};case 2:return {type:"ERC721",contract_address:e.token,token_id:e.identifierOrCriteria};case 3:return {type:"ERC1155",contract_address:e.token,token_id:e.identifierOrCriteria,amount:e.startAmount};case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};default:return C(e.itemType)}}function ae(e){if(e.itemType!==1)throw new Error(`Expected ERC20 item, got ${e.itemType}`);return {type:"ERC20",contract_address:e.token,amount:e.startAmount}}function xe(e){switch(e.itemType){case 4:return {type:"ERC721_COLLECTION",contract_address:e.token,amount:e.startAmount};case 5:return {type:"ERC1155_COLLECTION",contract_address:e.token,amount:e.startAmount};case 1:case 0:case 2:case 3:throw new Error(`Unsupported item type ${e.itemType}`);default:return C(e.itemType)}}function K(e){switch(e){case 2:return y.order_type.FULL_RESTRICTED;case 3:return y.order_type.PARTIAL_RESTRICTED;case 0:case 1:throw new Error(`Unsupported order type ${e}`);default:return C()}}var Y=class{constructor(t,r,s){this.orderbookService=t;this.chainName=r;this.seaportAddress=s;}async fulfillmentData(t){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:t})}async getListing(t){return this.orderbookService.getListing({chainName:this.chainName,listingId:t})}async getBid(t){return this.orderbookService.getBid({chainName:this.chainName,bidId:t})}async getCollectionBid(t){return this.orderbookService.getCollectionBid({chainName:this.chainName,collectionBidId:t})}async getTrade(t){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:t})}async listListings(t){return this.orderbookService.listListings({chainName:this.chainName,...t})}async listBids(t){return this.orderbookService.listBids({chainName:this.chainName,...t})}async listCollectionBids(t){return this.orderbookService.listCollectionBids({chainName:this.chainName,...t})}async listTrades(t){return this.orderbookService.listTrades({chainName:this.chainName,...t})}async cancelOrders(t,r,s){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:r,orders:t,signature:s}})}async createListing({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a listing");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a listing");if(![2,3].includes(r.offer[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be listed");if(![0,1].includes(r.consideration[0].itemType))throw new Error("Only Native / ERC20 tokens can be used as currency items in a listing");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(W),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a bid");if(![2,3].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 tokens can be bid against");return this.orderbookService.createBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(W),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}async createCollectionBid({orderHash:t,orderComponents:r,orderSignature:s,makerFees:n}){if(r.offer.length!==1)throw new Error("Only one item can be listed for a collection bid");if(r.consideration.length!==1)throw new Error("Only one item can be used as currency for a collection bid");if(1!==r.offer[0].itemType)throw new Error("Only ERC20 tokens can be used as the currency item in a collection bid");if(![4,5].includes(r.consideration[0].itemType))throw new Error("Only ERC721 / ERC1155 collection based tokens can be bid against");return this.orderbookService.createCollectionBid({chainName:this.chainName,requestBody:{account_address:r.offerer,buy:r.consideration.map(xe),fees:n.map(i=>({type:f.type.MAKER_ECOSYSTEM,amount:i.amount,recipient_address:i.recipientAddress})),end_at:new Date(parseInt(`${r.endTime.toString()}000`,10)).toISOString(),order_hash:t,protocol_data:{order_type:K(r.orderType),zone_address:r.zone,seaport_address:this.seaportAddress,seaport_version:O,counter:r.counter.toString()},salt:r.salt,sell:r.offer.map(ae),signature:s,start_at:new Date(parseInt(`${r.startTime.toString()}000`,10)).toISOString()}})}};var J=class{constructor(t,r,s,n){this.chainName=r;this.seaportAddress=s;this.orderbookClient=new P({BASE:t,HEADERS:n?{"x-api-key":n}:void 0});}orderbookClient;create(){return new Y(this.orderbookClient.orders,this.chainName,this.seaportAddress)}};var yt="imtbl-zkevm-testnet",gt="imtbl-zkevm-mainnet";function Z(e,t){let r=new FetchRequest(e);return t&&r.setHeader("x-api-key",t),new JsonRpcProvider(r)}function ke(e){switch(e.baseConfig.environment){case Environment.SANDBOX:return {seaportContractAddress:"0x7d117aA8BD6D31c4fa91722f246388f38ab1942c",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.sandbox.immutable.com",chainName:yt,provider:Z("https://rpc.testnet.immutable.com",e.baseConfig.rateLimitingKey)};case Environment.PRODUCTION:return {seaportContractAddress:"0x6c12aD6F0bD274191075Eb2E78D7dA5ba6453424",zoneContractAddress:"0x1004f9615E79462c711Ff05a386BdbA91a7628C3",apiEndpoint:"https://api.immutable.com",chainName:gt,provider:Z("https://rpc.immutable.com",e.baseConfig.rateLimitingKey)};default:return null}}var X=class{constructor(t,r){this.defaultSeaportContractAddress=t;this.provider=r;}create(t){let r=t??this.defaultSeaportContractAddress,s=this.provider;return s.getSigner=async function(i){i==null&&(i=0);let o=this.send("eth_accounts",[]);if(typeof i=="number"){let d=await o;if(i>=d.length)throw new Error("no such account");return new JsonRpcSigner(this,d[i])}return new JsonRpcSigner(this,i)},new Seaport(s,{balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}};var de=class e{apiClient;seaport;orderbookConfig;constructor(t){let s={...ke(t),...t.overrides};if(t.overrides?.jsonRpcProviderUrl&&(s.provider=Z(t.overrides?.jsonRpcProviderUrl,t.baseConfig.rateLimitingKey)),!s)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=s;let{apiEndpoint:n,chainName:i}=this.orderbookConfig;if(!n)throw new Error("API endpoint must be provided");this.apiClient=new J(n,i,this.orderbookConfig.seaportContractAddress,t.baseConfig.rateLimitingKey).create();let o=new X(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new j(o,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress,t.baseConfig.rateLimitingKey);}static defaultOrderExpiry(){return new Date(Date.now()+1e3*60*60*24*365*2)}config(){return this.orderbookConfig}async getListing(t){let r=await this.apiClient.getListing(t);return {result:h(r.result)}}async getBid(t){let r=await this.apiClient.getBid(t);return {result:B(r.result)}}async getCollectionBid(t){let r=await this.apiClient.getCollectionBid(t);return {result:x(r.result)}}async getTrade(t){let r=await this.apiClient.getTrade(t);return {result:te(r.result)}}async listListings(t){let r=await this.apiClient.listListings(t);return {page:k(r.page),result:r.result.map(h)}}async listBids(t){let r=await this.apiClient.listBids(t);return {page:k(r.page),result:r.result.map(B)}}async listCollectionBids(t){let r=await this.apiClient.listCollectionBids(t);return {page:k(r.page),result:r.result.map(x)}}async listTrades(t){let r=await this.apiClient.listTrades(t);return {page:k(r.page),result:r.result.map(te)}}async prepareBulkListings({makerAddress:t,listingParams:r}){if(r.length>20)throw new Error("Bulk listing creation is limited to 20 orders");if(r.length===1){let o=await this.seaport.prepareSeaportOrder(t,r[0].sell,r[0].buy,r[0].sell.type==="ERC1155",r[0].orderStart||new Date,r[0].orderExpiry||e.defaultOrderExpiry());return {actions:o.actions,completeListings:async d=>{let p=await this.createListing({makerFees:r[0].makerFees,orderComponents:o.orderComponents,orderHash:o.orderHash,orderSignature:typeof d=="string"?d:d[0]});return {result:[{success:!0,orderHash:o.orderHash,order:p.result}]}}}}if(await this.orderbookConfig.provider.getCode(t)!=="0x"){track("orderbookmr","bulkListings",{walletType:"Passport",makerAddress:t,listingsCount:r.length});let o=await Promise.all(r.map(a=>this.seaport.prepareSeaportOrder(t,a.sell,a.buy,a.sell.type==="ERC1155",a.orderStart||new Date,a.orderExpiry||e.defaultOrderExpiry()))),d=[];return {actions:o.flatMap(a=>{let l=[];return a.actions.forEach(u=>{if(u.type==="TRANSACTION"){let c=a.orderComponents.offer[0].token;d.includes(c)||(d.push(c),l.push(u));}else l.push(u);}),l}),completeListings:async a=>{if(typeof a=="string")throw new Error("A signature per listing must be provided for smart contract wallets");return {result:(await Promise.all(o.map((c,m)=>{let I=a[m];return this.apiClient.createListing({makerFees:r[m].makerFees,orderComponents:c.orderComponents,orderHash:c.orderHash,orderSignature:I}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:o[m].orderHash,order:c?h(c.result):void 0}))}}}}track("orderbookmr","bulkListings",{walletType:"EOA",makerAddress:t,listingsCount:r.length});let{actions:n,preparedOrders:i}=await this.seaport.prepareBulkSeaportOrders(t,r.map(o=>({offerItem:o.sell,considerationItem:o.buy,allowPartialFills:o.sell.type==="ERC1155",orderStart:o.orderStart||new Date,orderExpiry:o.orderExpiry||e.defaultOrderExpiry()})));return {actions:n,completeListings:async o=>{let d=typeof o=="object";if(d&&o.length!==1)throw new Error("Only a single signature is expected for bulk listing creation");let p=i.map(c=>c.orderComponents),a=d?o[0]:o,l=Le(a,p);return {result:(await Promise.all(p.map((c,m)=>{let I=l[m],E=i[m],De=r[m];return this.apiClient.createListing({orderComponents:c,orderHash:E.orderHash,orderSignature:I,makerFees:De.makerFees}).catch(()=>{})}))).map((c,m)=>({success:!!c,orderHash:i[m].orderHash,order:c?h(c.result):void 0}))}}}}async prepareListing({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,r.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createListing(t){let r=await this.apiClient.createListing(t);return {result:h(r.result)}}async prepareBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,s.type==="ERC1155",n||new Date,i||e.defaultOrderExpiry())}async createBid(t){let r=await this.apiClient.createBid(t);return {result:B(r.result)}}async prepareCollectionBid({makerAddress:t,sell:r,buy:s,orderStart:n,orderExpiry:i}){return this.seaport.prepareSeaportOrder(t,r,s,!0,n||new Date,i||e.defaultOrderExpiry())}async createCollectionBid(t){let r=await this.apiClient.createCollectionBid(t);return {result:x(r.result)}}async fulfillOrder(t,r,s,n,i){let o={order_id:t,taker_address:r,fees:s.map(u=>({type:f.type.TAKER_ECOSYSTEM,amount:u.amount,recipient_address:u.recipientAddress}))},d=i?[{identifier:i,proof:[]}]:void 0;i&&(o.token_id=i);let p=await this.apiClient.fulfillmentData([o]);if(p.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment data: ${p.result.unfulfillable_orders[0].reason}`);if(p.result.fulfillable_orders?.length!==1)throw new Error("unexpected fulfillable order result length");let a=p.result.fulfillable_orders[0].extra_data,l=p.result.fulfillable_orders[0].order;if(l.status.name!=="ACTIVE")throw new Error(`Cannot fulfil order that is not active. Current status: ${l.status}`);return this.seaport.fulfillOrder(l,r,a,n,d)}async fulfillBulkOrders(t,r){let s=t.map(i=>{let o="listingId"in i;return {orderId:o?i.listingId:i.orderId,takerFees:i.takerFees,amountToFill:i.amountToFill,tokenId:o?void 0:i.tokenId}}),n=await this.apiClient.fulfillmentData(s.map(i=>({order_id:i.orderId,taker_address:r,fees:i.takerFees.map(o=>({type:f.type.TAKER_ECOSYSTEM,amount:o.amount,recipient_address:o.recipientAddress})),token_id:i?.tokenId})));try{let i=n.result.fulfillable_orders.map(o=>{let d=s.find(a=>a.orderId===o.order.id&&a.tokenId===o.token_id);if(!d){let a=`Could not find order for order ${o.order.id}`;throw o.token_id&&(a+=` and token ID ${o.token_id}`),new Error(a)}let p=[];return d.tokenId&&p.push({identifier:d.tokenId,proof:[]}),{extraData:o.extra_data,order:o.order,unitsToFill:d.amountToFill,considerationCriteria:p}});return {...await this.seaport.fulfillBulkOrders(i,r),fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,tokenId:o.token_id,reason:o.reason})),sufficientBalance:!0}}catch(i){if(String(i).includes("The fulfiller does not have the balances needed to fulfill."))return {fulfillableOrders:n.result.fulfillable_orders.map(o=>N(o.order)),unfulfillableOrders:n.result.unfulfillable_orders.map(o=>({orderId:o.order_id,reason:o.reason})),sufficientBalance:!1};throw i}}async prepareOrderCancellations(t){let s={name:"imtbl-order-book",chainId:(await this.orderbookConfig.provider.getNetwork()).chainId,verifyingContract:this.orderbookConfig.seaportContractAddress},n={CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},i={orders:t.map(o=>({id:o}))};return {signableAction:{purpose:"OFF_CHAIN_CANCELLATION",type:"SIGNABLE",message:{domain:s,types:n,value:i}}}}async cancelOrders(t,r,s){return this.apiClient.cancelOrders(t,r,s)}async cancelOrdersOnChain(t,r){let s=Promise.all(t.map(l=>this.apiClient.getListing(l).catch(u=>{if(u.status!==404)throw u}))),n=Promise.all(t.map(l=>this.apiClient.getBid(l).catch(u=>{if(u.status!==404)throw u}))),i=Promise.all(t.map(l=>this.apiClient.getCollectionBid(l).catch(u=>{if(u.status!==404)throw u}))),o=[await Promise.all([s,n,i])].flat(2).filter(l=>l!==void 0).map(l=>l.result);if(o.length!==t.length){let l=t.filter(u=>!o.some(c=>c.id===u));throw new Error(`Orders ${l} not found`)}for(let l of o)if(l.account_address!==r.toLowerCase())throw new Error(`Only account ${l.account_address} can cancel order ${l.id}`);let d=o.map(l=>l.protocol_data.seaport_address);if(new Set(d).size!==1)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return {cancellationAction:await this.seaport.cancelOrders(o,r)}}};var ht={estimatedFulfillmentGasGwei:4e5};
10
10
 
11
11
  export { re as ActionType, Ye as FeeType, H as OrderStatusName, de as Orderbook, se as SignablePurpose, Ce as TransactionPurpose, ht as constants };
@@ -1,4 +1,4 @@
1
- import type { OrderComponents } from '@opensea/seaport-js/lib/types';
1
+ import type { OrderComponents } from './types';
2
2
  export declare function getOrderComponentsFromMessage(orderMessage: string): OrderComponents;
3
3
  export declare function getBulkOrderComponentsFromMessage(orderMessage: string): {
4
4
  components: OrderComponents[];
@@ -1,6 +1,6 @@
1
- import type { OrderComponents } from '@opensea/seaport-js/lib/types';
1
+ import type { OrderComponents } from '../types';
2
2
  import { Eip712MerkleTree } from './merkle';
3
3
  export declare function getBulkOrderTreeHeight(length: number): number;
4
- export declare function getBulkOrderTree(orderComponents: OrderComponents[], startIndex?: number, height?: number): Eip712MerkleTree<OrderComponents>;
4
+ export declare function getBulkOrderTree(orderComponents: OrderComponents[], startIndex?: number, height?: number): Eip712MerkleTree<import("@opensea/seaport-js/lib/types").OrderComponents>;
5
5
  export declare function getBulkOrderTypeHash(height: number): string;
6
6
  export declare function getBulkOrderTypeHashes(maxHeight: number): string[];
@@ -1,6 +1,6 @@
1
- import { ConsiderationItem, OfferItem } from '@opensea/seaport-js/lib/types';
2
- import { AssetCollectionItem, ERC20Item, Item, ProtocolData } from '../openapi/sdk';
3
1
  import { OrderType } from './constants';
2
+ import { ConsiderationItem, OfferItem } from './types';
3
+ import { AssetCollectionItem, ERC20Item, Item, ProtocolData } from '../openapi/sdk';
4
4
  export declare function mapSeaportItemToImmutableItem(item: OfferItem | ConsiderationItem): Item;
5
5
  export declare function mapSeaportItemToImmutableERC20Item(item: OfferItem | ConsiderationItem): ERC20Item;
6
6
  export declare function mapSeaportItemToImmutableAssetCollectionItem(item: OfferItem | ConsiderationItem): AssetCollectionItem;
@@ -1,5 +1,5 @@
1
- import { OrderComponents, TipInputItem } from '@opensea/seaport-js/lib/types';
2
1
  import { Order } from '../openapi/sdk';
2
+ import { OrderComponents, TipInputItem } from './types';
3
3
  export declare function mapImmutableOrderToSeaportOrderComponents(order: Order): {
4
4
  orderComponents: OrderComponents;
5
5
  tips: Array<TipInputItem>;
@@ -1,8 +1,8 @@
1
- import type { InputCriteria } from '@opensea/seaport-js/lib/types';
2
1
  import { JsonRpcProvider } from 'ethers';
3
2
  import { Order as OpenApiOrder } from '../openapi/sdk';
4
3
  import { Action, ERC1155CollectionItem, ERC1155Item, ERC20Item, ERC721CollectionItem, ERC721Item, FulfillOrderResponse, NativeItem, PrepareBulkSeaportOrders, PrepareOrderResponse, TransactionAction } from '../types';
5
4
  import { SeaportLibFactory } from './seaport-lib-factory';
5
+ import { InputCriteria } from './types';
6
6
  export declare class Seaport {
7
7
  private seaportLibFactory;
8
8
  private provider;
@@ -1,3 +1,3 @@
1
- import type { TransactionMethods } from '@opensea/seaport-js/lib/utils/usecase';
2
1
  import { TransactionBuilder } from '../types';
2
+ import { TransactionMethods } from './types';
3
3
  export declare function prepareTransaction(transactionMethods: TransactionMethods, chainId: bigint, callerAddress: string): TransactionBuilder;
@@ -0,0 +1,46 @@
1
+ import { Seaport as SeaportLib } from '@opensea/seaport-js';
2
+ import { ItemType } from './constants';
3
+ type ElementType<T> = T extends (infer U)[] ? U : never;
4
+ export type DefaultReturnType<R> = R extends Array<any> ? R[0] : R;
5
+ export type OrderComponents = Parameters<SeaportLib['signOrder']>[0];
6
+ export type OrderParameters = Omit<OrderComponents, 'counter'>;
7
+ export type OfferItem = OrderParameters['offer'][0];
8
+ export type ConsiderationItem = OrderParameters['consideration'][0];
9
+ export type FulfillmentOrderDetails = Parameters<SeaportLib['fulfillOrders']>[0]['fulfillOrderDetails'][0];
10
+ export type OrderWithCounter = Parameters<SeaportLib['fulfillOrder']>[0]['order'];
11
+ export type CreateOrderInput = Parameters<SeaportLib['createOrder']>[0];
12
+ export type ConsiderationInputItem = CreateOrderInput['consideration'][0];
13
+ export type CreateInputItem = CreateOrderInput['offer'][0];
14
+ export type InputCriteria = ElementType<Parameters<SeaportLib['fulfillOrder']>[0]['offerCriteria']>;
15
+ export type TipInputItem = ElementType<Parameters<SeaportLib['fulfillOrder']>[0]['tips']>;
16
+ export type CreateBulkOrdersReturnType = Awaited<ReturnType<SeaportLib['createBulkOrders']>>;
17
+ export type CreateOrderReturnType = Awaited<ReturnType<SeaportLib['createOrder']>>;
18
+ export type TransactionMethods<T = unknown> = {
19
+ buildTransaction: (overrides?: any) => Promise<any>;
20
+ staticCall: (overrides?: any) => Promise<DefaultReturnType<T>>;
21
+ estimateGas: (overrides?: any) => Promise<bigint>;
22
+ transact: (overrides?: any) => Promise<any>;
23
+ };
24
+ export type CreateOrderAction = {
25
+ type: 'create';
26
+ getMessageToSign: () => Promise<string>;
27
+ createOrder: () => Promise<OrderWithCounter>;
28
+ };
29
+ export type ApprovalAction = {
30
+ type: 'approval';
31
+ token: string;
32
+ identifierOrCriteria: string;
33
+ itemType: ItemType;
34
+ operator: string;
35
+ transactionMethods: TransactionMethods;
36
+ };
37
+ export type ExchangeAction<T = unknown> = {
38
+ type: 'exchange';
39
+ transactionMethods: TransactionMethods<T>;
40
+ };
41
+ export type CreateBulkOrdersAction = {
42
+ type: 'createBulk';
43
+ getMessageToSign: () => Promise<string>;
44
+ createBulkOrders: () => Promise<OrderWithCounter[]>;
45
+ };
46
+ export {};
@@ -1,6 +1,6 @@
1
- import type { OrderComponents } from '@opensea/seaport-js/lib/types';
2
1
  import { PreparedTransactionRequest, TypedDataDomain, TypedDataField } from 'ethers';
3
2
  import { OrdersService, OrderStatus } from './openapi/sdk';
3
+ import { OrderComponents } from './seaport/types';
4
4
  export { OrderStatusName } from './openapi/sdk';
5
5
  export interface NativeItem {
6
6
  type: 'NATIVE';
@@ -1 +1 @@
1
- export declare function exhaustiveSwitch(param: never): never;
1
+ export declare function exhaustiveSwitch(param: unknown): never;
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@imtbl/orderbook",
3
- "version": "2.0.0-alpha.4",
3
+ "version": "2.0.0-alpha.5",
4
4
  "author": "Immutable",
5
5
  "bugs": "https://github.com/immutable/ts-immutable-sdk/issues",
6
6
  "dependencies": {
7
- "@imtbl/config": "2.0.0-alpha.4",
8
- "@imtbl/metrics": "2.0.0-alpha.4",
7
+ "@imtbl/config": "2.0.0-alpha.5",
8
+ "@imtbl/metrics": "2.0.0-alpha.5",
9
9
  "@opensea/seaport-js": "4.0.3",
10
10
  "axios": "^1.6.5",
11
11
  "ethers": "^6.13.4",