@imtbl/sdk 0.31.0 → 0.31.2-alpha
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc +13 -0
- package/.gitignore +8 -0
- package/blockchain_data.js +1 -0
- package/checkout_sdk.js +9 -0
- package/config.js +1 -0
- package/dist/browser/checkout/sdk.js +1 -1
- package/dist/index.browser.js +3 -3
- package/dist/index.browser.js.map +1 -1
- package/immutablex_client.js +1 -0
- package/index.cjs +9 -0
- package/index.d.ts +18603 -0
- package/index.js +9 -0
- package/module-release.json +30 -0
- package/orderbook.js +1 -0
- package/package.json +24 -18
- package/passport.js +1 -0
- package/provider.js +1 -0
- package/rollup.config.js +158 -0
- package/scripts/copyBrowserBundles.js +62 -0
- package/scripts/generate-package-list.sh +5 -0
- package/scripts/generateIndex.js +44 -0
- package/scripts/updateDependencies.js +137 -0
- package/scripts/updateExports.js +62 -0
- package/src/blockchain_data.ts +1 -0
- package/src/checkout_sdk.ts +1 -0
- package/src/checkout_widgets.ts +1 -0
- package/src/config.ts +1 -0
- package/src/immutablex_client.ts +1 -0
- package/src/index.ts +7 -0
- package/src/orderbook.ts +1 -0
- package/src/passport.ts +1 -0
- package/src/provider.ts +1 -0
- package/tsconfig.json +27 -0
- package/typedoc.json +4 -0
- package/workspace-packages.json +31 -0
- package/dist/blockchain_data.js +0 -4010
- package/dist/checkout_sdk.js +0 -26016
- package/dist/config.js +0 -37
- package/dist/immutablex_client.js +0 -523
- package/dist/index.cjs +0 -34452
- package/dist/index.js +0 -34424
- package/dist/orderbook.js +0 -1583
- package/dist/passport.js +0 -9159
- package/dist/provider.js +0 -1165
- /package/{dist/blockchain_data.d.ts → blockchain_data.d.ts} +0 -0
- /package/{dist/checkout_sdk.d.ts → checkout_sdk.d.ts} +0 -0
- /package/{dist/config.d.ts → config.d.ts} +0 -0
- /package/{dist/immutablex_client.d.ts → immutablex_client.d.ts} +0 -0
- /package/{dist/index.d.ts → index.d.cts} +0 -0
- /package/{dist/orderbook.d.ts → orderbook.d.ts} +0 -0
- /package/{dist/passport.d.ts → passport.d.ts} +0 -0
- /package/{dist/provider.d.ts → provider.d.ts} +0 -0
|
@@ -32,4 +32,4 @@ n.mode.CTRGladman=function(){var e=n.lib.BlockCipherMode.extend();function t(e){
|
|
|
32
32
|
|
|
33
33
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
34
34
|
*/
|
|
35
|
-
function(e){var t=n,r=t.lib,i=r.WordArray,a=r.Hasher,o=t.algo,s=i.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),u=i.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),c=i.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),l=i.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),d=i.create([0,1518500249,1859775393,2400959708,2840853838]),f=i.create([1352829926,1548603684,1836072691,2053994217,0]),p=o.RIPEMD160=a.extend({_doReset:function(){this._hash=i.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var n=0;n<16;n++){var r=t+n,i=e[r];e[r]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var a,o,p,w,T,A,E,_,I,R,C,k=this._hash.words,O=d.words,S=f.words,N=s.words,x=u.words,P=c.words,M=l.words;for(A=a=k[0],E=o=k[1],_=p=k[2],I=w=k[3],R=T=k[4],n=0;n<80;n+=1)C=a+e[t+N[n]]|0,C+=n<16?h(o,p,w)+O[0]:n<32?m(o,p,w)+O[1]:n<48?y(o,p,w)+O[2]:n<64?g(o,p,w)+O[3]:b(o,p,w)+O[4],C=(C=v(C|=0,P[n]))+T|0,a=T,T=w,w=v(p,10),p=o,o=C,C=A+e[t+x[n]]|0,C+=n<16?b(E,_,I)+S[0]:n<32?g(E,_,I)+S[1]:n<48?y(E,_,I)+S[2]:n<64?m(E,_,I)+S[3]:h(E,_,I)+S[4],C=(C=v(C|=0,M[n]))+R|0,A=R,R=I,I=v(_,10),_=E,E=C;C=k[1]+p+I|0,k[1]=k[2]+w+R|0,k[2]=k[3]+T+A|0,k[3]=k[4]+a+E|0,k[4]=k[0]+o+_|0,k[0]=C},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),e.sigBytes=4*(t.length+1),this._process();for(var i=this._hash,a=i.words,o=0;o<5;o++){var s=a[o];a[o]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8)}return i},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}});function h(e,t,n){return e^t^n}function m(e,t,n){return e&t|~e&n}function y(e,t,n){return(e|~t)^n}function g(e,t,n){return e&n|t&~n}function b(e,t,n){return e^(t|~n)}function v(e,t){return e<<t|e>>>32-t}t.RIPEMD160=a._createHelper(p),t.HmacRIPEMD160=a._createHmacHelper(p)}(),n.RIPEMD160)}(nO)),aO(),oO||(oO=1,function(e,t){var n;e.exports=(n=bk(),aO(),function(){var e=n,t=e.lib,r=t.Base,i=t.WordArray,a=e.algo,o=a.SHA256,s=a.HMAC,u=a.PBKDF2=r.extend({cfg:r.extend({keySize:4,hasher:o,iterations:25e4}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=this.cfg,r=s.create(n.hasher,e),a=i.create(),o=i.create([1]),u=a.words,c=o.words,l=n.keySize,d=n.iterations;u.length<l;){var f=r.update(t).finalize(o);r.reset();for(var p=f.words,h=p.length,m=f,y=1;y<d;y++){m=r.finalize(m),r.reset();for(var g=m.words,b=0;b<h;b++)p[b]^=g[b]}a.concat(f),c[0]++}return a.sigBytes=4*l,a}});e.PBKDF2=function(e,t,n){return u.create(n).compute(e,t)}}(),n.PBKDF2)}(sO)),lO(),pO(),yO(),vO(),AO(),IO(),RO||(RO=1,function(e,t){var n,r;e.exports=(r=bk(),pO(),r.mode.ECB=((n=r.lib.BlockCipherMode.extend()).Encryptor=n.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),n.Decryptor=n.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),n),r.mode.ECB)}(CO)),kO||(kO=1,function(e,t){var n;e.exports=(n=bk(),pO(),n.pad.AnsiX923={pad:function(e,t){var n=e.sigBytes,r=4*t,i=r-n%r,a=n+i-1;e.clamp(),e.words[a>>>2]|=i<<24-a%4*8,e.sigBytes+=i},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},n.pad.Ansix923)}(OO)),SO||(SO=1,function(e,t){var n;e.exports=(n=bk(),pO(),n.pad.Iso10126={pad:function(e,t){var r=4*t,i=r-e.sigBytes%r;e.concat(n.lib.WordArray.random(i-1)).concat(n.lib.WordArray.create([i<<24],1))},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},n.pad.Iso10126)}(NO)),xO||(xO=1,function(e,t){var n;e.exports=(n=bk(),pO(),n.pad.Iso97971={pad:function(e,t){e.concat(n.lib.WordArray.create([2147483648],1)),n.pad.ZeroPadding.pad(e,t)},unpad:function(e){n.pad.ZeroPadding.unpad(e),e.sigBytes--}},n.pad.Iso97971)}(PO)),MO||(MO=1,function(e,t){var n;e.exports=(n=bk(),pO(),n.pad.ZeroPadding={pad:function(e,t){var n=4*t;e.clamp(),e.sigBytes+=n-(e.sigBytes%n||n)},unpad:function(e){var t=e.words,n=e.sigBytes-1;for(n=e.sigBytes-1;n>=0;n--)if(t[n>>>2]>>>24-n%4*8&255){e.sigBytes=n+1;break}}},n.pad.ZeroPadding)}(BO)),DO||(DO=1,function(e,t){var n;e.exports=(n=bk(),pO(),n.pad.NoPadding={pad:function(){},unpad:function(){}},n.pad.NoPadding)}(FO)),LO||(LO=1,function(e,t){var n,r,i,a;e.exports=(a=bk(),pO(),r=(n=a).lib.CipherParams,i=n.enc.Hex,n.format.Hex={stringify:function(e){return e.ciphertext.toString(i)},parse:function(e){var t=i.parse(e);return r.create({ciphertext:t})}},a.format.Hex)}(UO)),qO||(qO=1,function(e,t){var n;e.exports=(n=bk(),Bk(),jk(),lO(),pO(),function(){var e=n,t=e.lib.BlockCipher,r=e.algo,i=[],a=[],o=[],s=[],u=[],c=[],l=[],d=[],f=[],p=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var n=0,r=0;for(t=0;t<256;t++){var h=r^r<<1^r<<2^r<<3^r<<4;h=h>>>8^255&h^99,i[n]=h,a[h]=n;var m=e[n],y=e[m],g=e[y],b=257*e[h]^16843008*h;o[n]=b<<24|b>>>8,s[n]=b<<16|b>>>16,u[n]=b<<8|b>>>24,c[n]=b,b=16843009*g^65537*y^257*m^16843008*n,l[h]=b<<24|b>>>8,d[h]=b<<16|b>>>16,f[h]=b<<8|b>>>24,p[h]=b,n?(n=m^e[e[e[g^m]]],r^=e[e[r]]):n=r=1}}();var h=[0,1,2,4,8,16,32,64,128,27,54],m=r.AES=t.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,n=e.sigBytes/4,r=4*((this._nRounds=n+6)+1),a=this._keySchedule=[],o=0;o<r;o++)o<n?a[o]=t[o]:(c=a[o-1],o%n?n>6&&o%n==4&&(c=i[c>>>24]<<24|i[c>>>16&255]<<16|i[c>>>8&255]<<8|i[255&c]):(c=i[(c=c<<8|c>>>24)>>>24]<<24|i[c>>>16&255]<<16|i[c>>>8&255]<<8|i[255&c],c^=h[o/n|0]<<24),a[o]=a[o-n]^c);for(var s=this._invKeySchedule=[],u=0;u<r;u++){if(o=r-u,u%4)var c=a[o];else c=a[o-4];s[u]=u<4||o<=4?c:l[i[c>>>24]]^d[i[c>>>16&255]]^f[i[c>>>8&255]]^p[i[255&c]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,o,s,u,c,i)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,l,d,f,p,a),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,r,i,a,o,s){for(var u=this._nRounds,c=e[t]^n[0],l=e[t+1]^n[1],d=e[t+2]^n[2],f=e[t+3]^n[3],p=4,h=1;h<u;h++){var m=r[c>>>24]^i[l>>>16&255]^a[d>>>8&255]^o[255&f]^n[p++],y=r[l>>>24]^i[d>>>16&255]^a[f>>>8&255]^o[255&c]^n[p++],g=r[d>>>24]^i[f>>>16&255]^a[c>>>8&255]^o[255&l]^n[p++],b=r[f>>>24]^i[c>>>16&255]^a[l>>>8&255]^o[255&d]^n[p++];c=m,l=y,d=g,f=b}m=(s[c>>>24]<<24|s[l>>>16&255]<<16|s[d>>>8&255]<<8|s[255&f])^n[p++],y=(s[l>>>24]<<24|s[d>>>16&255]<<16|s[f>>>8&255]<<8|s[255&c])^n[p++],g=(s[d>>>24]<<24|s[f>>>16&255]<<16|s[c>>>8&255]<<8|s[255&l])^n[p++],b=(s[f>>>24]<<24|s[c>>>16&255]<<16|s[l>>>8&255]<<8|s[255&d])^n[p++],e[t]=m,e[t+1]=y,e[t+2]=g,e[t+3]=b},keySize:8});e.AES=t._createHelper(m)}(),n.AES)}(jO)),zO(),VO||(VO=1,function(e,t){var n;e.exports=(n=bk(),Bk(),jk(),lO(),pO(),function(){var e=n,t=e.lib.StreamCipher,r=e.algo,i=r.RC4=t.extend({_doReset:function(){for(var e=this._key,t=e.words,n=e.sigBytes,r=this._S=[],i=0;i<256;i++)r[i]=i;i=0;for(var a=0;i<256;i++){var o=i%n,s=t[o>>>2]>>>24-o%4*8&255;a=(a+r[i]+s)%256;var u=r[i];r[i]=r[a],r[a]=u}this._i=this._j=0},_doProcessBlock:function(e,t){e[t]^=a.call(this)},keySize:8,ivSize:0});function a(){for(var e=this._S,t=this._i,n=this._j,r=0,i=0;i<4;i++){n=(n+e[t=(t+1)%256])%256;var a=e[t];e[t]=e[n],e[n]=a,r|=e[(e[t]+e[n])%256]<<24-8*i}return this._i=t,this._j=n,r}e.RC4=t._createHelper(i);var o=r.RC4Drop=i.extend({cfg:i.cfg.extend({drop:192}),_doReset:function(){i._doReset.call(this);for(var e=this.cfg.drop;e>0;e--)a.call(this)}});e.RC4Drop=t._createHelper(o)}(),n.RC4)}(WO)),KO||(KO=1,function(e,t){var n;e.exports=(n=bk(),Bk(),jk(),lO(),pO(),function(){var e=n,t=e.lib.StreamCipher,r=e.algo,i=[],a=[],o=[],s=r.Rabbit=t.extend({_doReset:function(){for(var e=this._key.words,t=this.cfg.iv,n=0;n<4;n++)e[n]=16711935&(e[n]<<8|e[n]>>>24)|4278255360&(e[n]<<24|e[n]>>>8);var r=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],i=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];for(this._b=0,n=0;n<4;n++)u.call(this);for(n=0;n<8;n++)i[n]^=r[n+4&7];if(t){var a=t.words,o=a[0],s=a[1],c=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),l=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=c>>>16|4294901760&l,f=l<<16|65535&c;for(i[0]^=c,i[1]^=d,i[2]^=l,i[3]^=f,i[4]^=c,i[5]^=d,i[6]^=l,i[7]^=f,n=0;n<4;n++)u.call(this)}},_doProcessBlock:function(e,t){var n=this._X;u.call(this),i[0]=n[0]^n[5]>>>16^n[3]<<16,i[1]=n[2]^n[7]>>>16^n[5]<<16,i[2]=n[4]^n[1]>>>16^n[7]<<16,i[3]=n[6]^n[3]>>>16^n[1]<<16;for(var r=0;r<4;r++)i[r]=16711935&(i[r]<<8|i[r]>>>24)|4278255360&(i[r]<<24|i[r]>>>8),e[t+r]^=i[r]},blockSize:4,ivSize:2});function u(){for(var e=this._X,t=this._C,n=0;n<8;n++)a[n]=t[n];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0<a[0]>>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0<a[1]>>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0<a[2]>>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0<a[3]>>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0<a[4]>>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0<a[5]>>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0<a[6]>>>0?1:0)|0,this._b=t[7]>>>0<a[7]>>>0?1:0,n=0;n<8;n++){var r=e[n]+t[n],i=65535&r,s=r>>>16,u=((i*i>>>17)+i*s>>>15)+s*s,c=((4294901760&r)*r|0)+((65535&r)*r|0);o[n]=u^c}e[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,e[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,e[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,e[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,e[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,e[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,e[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,e[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.Rabbit=t._createHelper(s)}(),n.Rabbit)}(XO)),JO||(JO=1,function(e,t){var n;e.exports=(n=bk(),Bk(),jk(),lO(),pO(),function(){var e=n,t=e.lib.StreamCipher,r=e.algo,i=[],a=[],o=[],s=r.RabbitLegacy=t.extend({_doReset:function(){var e=this._key.words,t=this.cfg.iv,n=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],r=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];this._b=0;for(var i=0;i<4;i++)u.call(this);for(i=0;i<8;i++)r[i]^=n[i+4&7];if(t){var a=t.words,o=a[0],s=a[1],c=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),l=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=c>>>16|4294901760&l,f=l<<16|65535&c;for(r[0]^=c,r[1]^=d,r[2]^=l,r[3]^=f,r[4]^=c,r[5]^=d,r[6]^=l,r[7]^=f,i=0;i<4;i++)u.call(this)}},_doProcessBlock:function(e,t){var n=this._X;u.call(this),i[0]=n[0]^n[5]>>>16^n[3]<<16,i[1]=n[2]^n[7]>>>16^n[5]<<16,i[2]=n[4]^n[1]>>>16^n[7]<<16,i[3]=n[6]^n[3]>>>16^n[1]<<16;for(var r=0;r<4;r++)i[r]=16711935&(i[r]<<8|i[r]>>>24)|4278255360&(i[r]<<24|i[r]>>>8),e[t+r]^=i[r]},blockSize:4,ivSize:2});function u(){for(var e=this._X,t=this._C,n=0;n<8;n++)a[n]=t[n];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0<a[0]>>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0<a[1]>>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0<a[2]>>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0<a[3]>>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0<a[4]>>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0<a[5]>>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0<a[6]>>>0?1:0)|0,this._b=t[7]>>>0<a[7]>>>0?1:0,n=0;n<8;n++){var r=e[n]+t[n],i=65535&r,s=r>>>16,u=((i*i>>>17)+i*s>>>15)+s*s,c=((4294901760&r)*r|0)+((65535&r)*r|0);o[n]=u^c}e[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,e[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,e[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,e[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,e[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,e[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,e[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,e[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.RabbitLegacy=t._createHelper(s)}(),n.RabbitLegacy)}(YO)),$O(),n)}(_k);var eS=_k.exports,tS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ek,"__esModule",{value:!0}),Ek.Base=void 0;const nS=hn,rS=tS(eS);class iS{print(){iS.print(this)}bufferIndexOf(e,t,n=!1){if(n)return this.binarySearch(e,t,nS.Buffer.compare);return this.linearSearch(e,t,((e,t)=>e.equals(t)))}static binarySearch(e,t,n){let r=0,i=e.length-1;for(;r<=i;){const a=Math.floor((r+i)/2),o=n(e[a],t);if(0===o){for(let r=a-1;r>=0;r--)if(0!==n(e[r],t))return r+1;return 0}o<0?r=a+1:i=a-1}return-1}binarySearch(e,t,n){return iS.binarySearch(e,t,n)}static linearSearch(e,t,n){for(let r=0;r<e.length;r++)if(n(e[r],t))return r;return-1}linearSearch(e,t,n){return iS.linearSearch(e,t,n)}static bufferify(e){if(!nS.Buffer.isBuffer(e)){if("object"==typeof e&&e.words)return nS.Buffer.from(e.toString(rS.default.enc.Hex),"hex");if(iS.isHexString(e))return nS.Buffer.from(e.replace(/^0x/,""),"hex");if("string"==typeof e)return nS.Buffer.from(e);if("bigint"==typeof e)return nS.Buffer.from(e.toString(16),"hex");if(e instanceof Uint8Array)return nS.Buffer.from(e.buffer);if("number"==typeof e){let t=e.toString();return t.length%2&&(t=`0${t}`),nS.Buffer.from(t,"hex")}if(ArrayBuffer.isView(e))return nS.Buffer.from(e.buffer,e.byteOffset,e.byteLength)}return e}bigNumberify(e){return iS.bigNumberify(e)}static bigNumberify(e){if("bigint"==typeof e)return e;if("string"==typeof e)return e.startsWith("0x")&&iS.isHexString(e)?BigInt("0x"+e.replace("0x","").toString()):BigInt(e);if(nS.Buffer.isBuffer(e))return BigInt("0x"+e.toString("hex"));if(e instanceof Uint8Array)return BigInt(e);if("number"==typeof e)return BigInt(e);throw new Error("cannot bigNumberify")}static isHexString(e){return"string"==typeof e&&/^(0x)?[0-9A-Fa-f]*$/.test(e)}static print(e){console.log(e.toString())}bufferToHex(e,t=!0){return iS.bufferToHex(e,t)}static bufferToHex(e,t=!0){return`${t?"0x":""}${(e||nS.Buffer.alloc(0)).toString("hex")}`}bufferify(e){return iS.bufferify(e)}bufferifyFn(e){return t=>{const n=e(t);return nS.Buffer.isBuffer(n)?n:this.isHexString(n)?nS.Buffer.from(n.replace("0x",""),"hex"):"string"==typeof n?nS.Buffer.from(n):"bigint"==typeof n?nS.Buffer.from(t.toString(16),"hex"):ArrayBuffer.isView(n)?nS.Buffer.from(n.buffer,n.byteOffset,n.byteLength):nS.Buffer.from(e(rS.default.enc.Hex.parse(t.toString("hex"))).toString(rS.default.enc.Hex),"hex")}}isHexString(e){return iS.isHexString(e)}log2(e){return 1===e?0:1+this.log2(e/2|0)}zip(e,t){return e.map(((e,n)=>[e,t[n]]))}static hexZeroPad(e,t){return"0x"+e.replace("0x","").padStart(t,"0")}}Ek.Base=iS,Ek.default=iS;var aS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(pk,"__esModule",{value:!0}),pk.MerkleTree=void 0;const oS=hn,sS=aS((function(e){for(var t=new Buffer(e.length),n=0,r=e.length-1;n<=r;++n,--r)t[n]=e[r],t[r]=e[n];return t})),uS=aS(vk),cS=aS(Ak),lS=aS(Ek);let dS=class e extends lS.default{constructor(e,t=uS.default,n={}){if(super(),this.duplicateOdd=!1,this.concatenator=oS.Buffer.concat,this.hashLeaves=!1,this.isBitcoinTree=!1,this.leaves=[],this.layers=[],this.sortLeaves=!1,this.sortPairs=!1,this.sort=!1,this.fillDefaultHash=null,this.complete=!1,n.complete){if(n.isBitcoinTree)throw new Error('option "complete" is incompatible with "isBitcoinTree"');if(n.duplicateOdd)throw new Error('option "complete" is incompatible with "duplicateOdd"')}if(this.isBitcoinTree=!!n.isBitcoinTree,this.hashLeaves=!!n.hashLeaves,this.sortLeaves=!!n.sortLeaves,this.sortPairs=!!n.sortPairs,this.complete=!!n.complete,n.fillDefaultHash)if("function"==typeof n.fillDefaultHash)this.fillDefaultHash=n.fillDefaultHash;else{if(!oS.Buffer.isBuffer(n.fillDefaultHash)&&"string"!=typeof n.fillDefaultHash)throw new Error('method "fillDefaultHash" must be a function, Buffer, or string');this.fillDefaultHash=(e,t)=>n.fillDefaultHash}this.sort=!!n.sort,this.sort&&(this.sortLeaves=!0,this.sortPairs=!0),this.duplicateOdd=!!n.duplicateOdd,n.concatenator&&(this.concatenator=n.concatenator),this.hashFn=this.bufferifyFn(t),this.processLeaves(e)}getOptions(){var e,t;return{complete:this.complete,isBitcoinTree:this.isBitcoinTree,hashLeaves:this.hashLeaves,sortLeaves:this.sortLeaves,sortPairs:this.sortPairs,sort:this.sort,fillDefaultHash:null!==(t=null===(e=this.fillDefaultHash)||void 0===e?void 0:e.toString())&&void 0!==t?t:null,duplicateOdd:this.duplicateOdd}}processLeaves(e){if(this.hashLeaves&&(e=e.map(this.hashFn)),this.leaves=e.map(this.bufferify),this.sortLeaves&&(this.leaves=this.leaves.sort(oS.Buffer.compare)),this.fillDefaultHash)for(let e=this.leaves.length;e<Math.pow(2,Math.ceil(Math.log2(this.leaves.length)));e++)this.leaves.push(this.bufferify(this.fillDefaultHash(e,this.hashFn)));this.createHashes(this.leaves)}createHashes(e){for(this.layers=[e];e.length>1;){const t=this.layers.length;this.layers.push([]);const n=this.complete&&1===t&&!Number.isInteger(Math.log2(e.length))?2*e.length-Math.pow(2,Math.ceil(Math.log2(e.length))):e.length;for(let r=0;r<e.length;r+=2){if(r>=n){this.layers[t].push(...e.slice(n));break}if(r+1===e.length&&e.length%2==1){const n=e[e.length-1];let i=n;if(this.isBitcoinTree){i=this.hashFn(this.concatenator([sS.default(n),sS.default(n)])),i=sS.default(this.hashFn(i)),this.layers[t].push(i);continue}if(!this.duplicateOdd){this.layers[t].push(e[r]);continue}}const i=e[r],a=r+1===e.length?i:e[r+1];let o=null;o=this.isBitcoinTree?[sS.default(i),sS.default(a)]:[i,a],this.sortPairs&&o.sort(oS.Buffer.compare);let s=this.hashFn(this.concatenator(o));this.isBitcoinTree&&(s=sS.default(this.hashFn(s))),this.layers[t].push(s)}e=this.layers[t]}}addLeaf(e,t=!1){t&&(e=this.hashFn(e)),this.processLeaves(this.leaves.concat(e))}addLeaves(e,t=!1){t&&(e=e.map(this.hashFn)),this.processLeaves(this.leaves.concat(e))}getLeaves(e){return Array.isArray(e)?(this.hashLeaves&&(e=e.map(this.hashFn),this.sortLeaves&&(e=e.sort(oS.Buffer.compare))),this.leaves.filter((t=>-1!==this.bufferIndexOf(e,t,this.sortLeaves)))):this.leaves}getLeaf(e){return e<0||e>this.leaves.length-1?oS.Buffer.from([]):this.leaves[e]}getLeafIndex(e){e=this.bufferify(e);const t=this.getLeaves();for(let n=0;n<t.length;n++){if(t[n].equals(e))return n}return-1}getLeafCount(){return this.leaves.length}getHexLeaves(){return this.leaves.map((e=>this.bufferToHex(e)))}static marshalLeaves(t){return JSON.stringify(t.map((t=>e.bufferToHex(t))),null,2)}static unmarshalLeaves(t){let n=null;if("string"==typeof t)n=JSON.parse(t);else{if(!(t instanceof Object))throw new Error("Expected type of string or object");n=t}if(!n)return[];if(!Array.isArray(n))throw new Error("Expected JSON string to be array");return n.map(e.bufferify)}getLayers(){return this.layers}getHexLayers(){return this.layers.reduce(((e,t)=>(Array.isArray(t)?e.push(t.map((e=>this.bufferToHex(e)))):e.push(t),e)),[])}getLayersFlat(){const e=this.layers.reduce(((e,t)=>(Array.isArray(t)?e.unshift(...t):e.unshift(t),e)),[]);return e.unshift(oS.Buffer.from([0])),e}getHexLayersFlat(){return this.getLayersFlat().map((e=>this.bufferToHex(e)))}getLayerCount(){return this.getLayers().length}getRoot(){return 0===this.layers.length?oS.Buffer.from([]):this.layers[this.layers.length-1][0]||oS.Buffer.from([])}getHexRoot(){return this.bufferToHex(this.getRoot())}getProof(e,t){if(void 0===e)throw new Error("leaf is required");e=this.bufferify(e);const n=[];if(!Number.isInteger(t)){t=-1;for(let n=0;n<this.leaves.length;n++)0===oS.Buffer.compare(e,this.leaves[n])&&(t=n)}if(t<=-1)return[];for(let e=0;e<this.layers.length;e++){const r=this.layers[e],i=t%2,a=i?t-1:this.isBitcoinTree&&t===r.length-1&&e<this.layers.length-1?t:t+1;a<r.length&&n.push({position:i?"left":"right",data:r[a]}),t=t/2|0}return n}getHexProof(e,t){return this.getProof(e,t).map((e=>this.bufferToHex(e.data)))}getProofs(){const e=[];return this.getProofsDFS(this.layers.length-1,0,[],e),e}getProofsDFS(e,t,n,r){const i=t%2;if(-1===e)return void(i||r.push([...n].reverse()));if(t>=this.layers[e].length)return;const a=this.layers[e],o=i?t-1:t+1;let s=!1;o<a.length&&(s=!0,n.push({position:i?"left":"right",data:a[o]}));const u=2*t,c=2*t+1;this.getProofsDFS(e-1,u,n,r),this.getProofsDFS(e-1,c,n,r),s&&n.splice(n.length-1,1)}getHexProofs(){return this.getProofs().map((e=>this.bufferToHex(e.data)))}getPositionalHexProof(e,t){return this.getProof(e,t).map((e=>["left"===e.position?0:1,this.bufferToHex(e.data)]))}static marshalProof(t){const n=t.map((t=>"string"==typeof t?t:oS.Buffer.isBuffer(t)?e.bufferToHex(t):{position:t.position,data:e.bufferToHex(t.data)}));return JSON.stringify(n,null,2)}static unmarshalProof(t){let n=null;if("string"==typeof t)n=JSON.parse(t);else{if(!(t instanceof Object))throw new Error("Expected type of string or object");n=t}if(!n)return[];if(!Array.isArray(n))throw new Error("Expected JSON string to be array");return n.map((t=>{if("string"==typeof t)return e.bufferify(t);if(t instanceof Object)return{position:t.position,data:e.bufferify(t.data)};throw new Error("Expected item to be of type string or object")}))}static marshalTree(t){const n=t.getHexRoot(),r=t.leaves.map((t=>e.bufferToHex(t))),i=t.getHexLayers(),a=t.getOptions();return JSON.stringify({options:a,root:n,layers:i,leaves:r},null,2)}static unmarshalTree(t,n=uS.default,r={}){let i=null;if("string"==typeof t)i=JSON.parse(t);else{if(!(t instanceof Object))throw new Error("Expected type of string or object");i=t}if(!i)throw new Error("could not parse json");return r=Object.assign({},i.options||{},r),new e(i.leaves,n,r)}getProofIndices(e,t){const n=Math.pow(2,t);let r=new Set;for(const t of e){let e=n+t;for(;e>1;)r.add(1^e),e=e/2|0}const i=e.map((e=>n+e)),a=Array.from(r).sort(((e,t)=>e-t)).reverse();r=i.concat(a);const o=new Set,s=[];for(let e of r)if(!o.has(e))for(s.push(e);e>1&&(o.add(e),o.has(1^e));)e=e/2|0;return s.filter((t=>!e.includes(t-n)))}getProofIndicesForUnevenTree(e,t){const n=Math.ceil(Math.log2(t)),r=[];for(let e=0;e<n;e++){t%2!=0&&r.push({index:e,leavesCount:t}),t=Math.ceil(t/2)}const i=[];let a=e;for(let e=0;e<n;e++){const t=a.map((e=>e%2==0?e+1:e-1));let n=t.filter((e=>!a.includes(e)));const o=r.find((({index:t})=>t===e));o&&a.includes(o.leavesCount-1)&&(n=n.slice(0,-1)),i.push(n),a=[...new Set(a.map((e=>e%2==0?e/2:e%2==0?(e+1)/2:(e-1)/2)))]}return i}getMultiProof(e,t){this.complete||console.warn("Warning: For correct multiProofs it's strongly recommended to set complete: true"),t||(t=e,e=this.getLayersFlat());if(this.isUnevenTree()&&t.every(Number.isInteger))return this.getMultiProofForUnevenTree(t);if(!t.every(Number.isInteger)){let e=t;this.sortPairs&&(e=e.sort(oS.Buffer.compare));let n=e.map((e=>this.bufferIndexOf(this.leaves,e,this.sortLeaves))).sort(((e,t)=>e===t?0:e>t?1:-1));if(!n.every((e=>-1!==e)))throw new Error("Element does not exist in Merkle tree");const r=[],i=[];let a=[];for(let e=0;e<this.layers.length;e++){const t=this.layers[e];for(let e=0;e<n.length;e++){const o=n[e],s=this.getPairNode(t,o);r.push(t[o]),s&&i.push(s),a.push(o/2|0)}n=a.filter(((e,t,n)=>n.indexOf(e)===t)),a=[]}return i.filter((e=>!r.includes(e)))}return this.getProofIndices(t,Math.log2(e.length/2|0)).map((t=>e[t]))}getMultiProofForUnevenTree(e,t){t||(t=e,e=this.getLayers());let n=[],r=t;for(const t of e){const e=[];for(const n of r){if(n%2==0){const i=n+1;if(!r.includes(i)&&t[i]){e.push(t[i]);continue}}const i=n-1;r.includes(i)||!t[i]||e.push(t[i])}n=n.concat(e);const i=new Set;for(const e of r)e%2!=0?e%2!=0?i.add((e-1)/2):i.add((e+1)/2):i.add(e/2);r=Array.from(i)}return n}getHexMultiProof(e,t){return this.getMultiProof(e,t).map((e=>this.bufferToHex(e)))}getProofFlags(e,t){if(!Array.isArray(e)||e.length<=0)throw new Error("Invalid Inputs!");let n;if(n=e.every(Number.isInteger)?[...e].sort(((e,t)=>e===t?0:e>t?1:-1)):e.map((e=>this.bufferIndexOf(this.leaves,e,this.sortLeaves))).sort(((e,t)=>e===t?0:e>t?1:-1)),!n.every((e=>-1!==e)))throw new Error("Element does not exist in Merkle tree");const r=t.map((e=>this.bufferify(e))),i=[],a=[];for(let e=0;e<this.layers.length;e++){const t=this.layers[e];n=n.reduce(((e,n)=>{if(!i.includes(t[n])){const e=this.getPairNode(t,n),o=r.includes(t[n])||r.includes(e);e&&a.push(!o),i.push(t[n]),i.push(e)}return e.push(n/2|0),e}),[])}return a}verify(e,t,n){let r=this.bufferify(t);if(n=this.bufferify(n),!Array.isArray(e)||!t||!n)return!1;for(let t=0;t<e.length;t++){const n=e[t];let i=null,a=null;if("string"==typeof n)i=this.bufferify(n),a=!0;else if(Array.isArray(n))a=0===n[0],i=this.bufferify(n[1]);else if(oS.Buffer.isBuffer(n))i=n,a=!0;else{if(!(n instanceof Object))throw new Error("Expected node to be of type string or object");i=this.bufferify(n.data),a="left"===n.position}const o=[];this.isBitcoinTree?(o.push(sS.default(r)),o[a?"unshift":"push"](sS.default(i)),r=this.hashFn(this.concatenator(o)),r=sS.default(this.hashFn(r))):this.sortPairs?-1===oS.Buffer.compare(r,i)?(o.push(r,i),r=this.hashFn(this.concatenator(o))):(o.push(i,r),r=this.hashFn(this.concatenator(o))):(o.push(r),o[a?"unshift":"push"](i),r=this.hashFn(this.concatenator(o)))}return 0===oS.Buffer.compare(r,n)}verifyMultiProof(e,t,n,r,i){if(this.isUnevenTree())return this.verifyMultiProofForUnevenTree(e,t,n,r,i);const a=Math.ceil(Math.log2(r));e=this.bufferify(e),n=n.map((e=>this.bufferify(e))),i=i.map((e=>this.bufferify(e)));const o={};for(const[e,r]of this.zip(t,n))o[Math.pow(2,a)+e]=r;for(const[e,n]of this.zip(this.getProofIndices(t,a),i))o[e]=n;let s=Object.keys(o).map((e=>+e)).sort(((e,t)=>e-t));s=s.slice(0,s.length-1);let u=0;for(;u<s.length;){const e=s[u];if(e>=2&&{}.hasOwnProperty.call(o,1^e)){let t=[o[e-e%2],o[e-e%2+1]];this.sortPairs&&(t=t.sort(oS.Buffer.compare));const n=t[1]?this.hashFn(this.concatenator(t)):t[0];o[e/2|0]=n,s.push(e/2|0)}u+=1}return!t.length||{}.hasOwnProperty.call(o,1)&&o[1].equals(e)}verifyMultiProofWithFlags(e,t,n,r){e=this.bufferify(e),t=t.map(this.bufferify),n=n.map(this.bufferify);const i=t.length,a=r.length,o=[];let s=0,u=0,c=0;for(let e=0;e<a;e++){const a=[r[e]?s<i?t[s++]:o[u++]:n[c++],s<i?t[s++]:o[u++]].sort(oS.Buffer.compare);o[e]=this.hashFn(this.concatenator(a))}return 0===oS.Buffer.compare(o[a-1],e)}verifyMultiProofForUnevenTree(e,t,n,r,i){e=this.bufferify(e),n=n.map((e=>this.bufferify(e))),i=i.map((e=>this.bufferify(e)));const a=this.calculateRootForUnevenTree(t,n,r,i);return e.equals(a)}getDepth(){return this.getLayers().length-1}getLayersAsObject(){const e=this.getLayers().map((e=>e.map((e=>this.bufferToHex(e,!1))))),t=[];for(let n=0;n<e.length;n++){const r=[];for(let i=0;i<e[n].length;i++){const a={[e[n][i]]:null};if(t.length){a[e[n][i]]={};const r=t.shift(),o=Object.keys(r)[0];if(a[e[n][i]][o]=r[o],t.length){const r=t.shift(),o=Object.keys(r)[0];a[e[n][i]][o]=r[o]}}r.push(a)}t.push(...r)}return t[0]}static verify(t,n,r,i=uS.default,a={}){return new e([],i,a).verify(t,n,r)}static getMultiProof(t,n){return new e([]).getMultiProof(t,n)}resetTree(){this.leaves=[],this.layers=[]}getPairNode(e,t){const n=t%2==0?t+1:t-1;return n<e.length?e[n]:null}toTreeString(){const e=this.getLayersAsObject();return cS.default.asTree(e,!0)}toString(){return this.toTreeString()}isUnevenTree(e){const t=(null==e?void 0:e.length)||this.getDepth();return!this.isPowOf2(t)}isPowOf2(e){return e&&!(e&e-1)}calculateRootForUnevenTree(e,t,n,r){const i=this.zip(e,t).sort((([e],[t])=>e-t)),a=i.map((([e])=>e)),o=this.getProofIndicesForUnevenTree(a,n);let s=0;const u=[];for(let e=0;e<o.length;e++){const t=o[e],n=s;s+=t.length,u[e]=this.zip(t,r.slice(n,s))}const c=[i];for(let e=0;e<u.length;e++){const t=u[e].concat(c[e]).sort((([e],[t])=>e-t)).map((([,e])=>e)),n=c[e].map((([e])=>e)),r=[...new Set(n.map((e=>e%2==0?e/2:e%2==0?(e+1)/2:(e-1)/2)))],i=[];for(let e=0;e<r.length;e++){const n=r[e],a=t[2*e],o=t[2*e+1],s=o?this.hashFn(this.concatenator([a,o])):a;i.push([n,s])}c.push(i)}return c[c.length-1][0][1]}};pk.MerkleTree=dS,"undefined"!=typeof window&&(window.MerkleTree=dS),pk.default=dS;var fS={},pS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(fS,"__esModule",{value:!0}),fS.MerkleMountainRange=void 0;const hS=hn,mS=pS(vk),yS=pS(Ek);class gS extends yS.default{constructor(e=mS.default,t=[],n,r,i){super(),this.root=hS.Buffer.alloc(0),this.size=0,this.width=0,this.hashes={},this.data={},t=t.map(this.bufferify),this.hashFn=this.bufferifyFn(e),this.hashLeafFn=n,this.peakBaggingFn=r,this.hashBranchFn=i;for(const e of t)this.append(e)}append(e){e=this.bufferify(e);const t=this.hashFn(e),n=this.bufferToHex(t);this.data[n]&&this.bufferToHex(this.hashFn(this.data[n]))===n||(this.data[n]=e);const r=this.hashLeaf(this.size+1,t);this.hashes[this.size+1]=r,this.width+=1;const i=this.getPeakIndexes(this.width);this.size=this.getSize(this.width);const a=[];for(let e=0;e<i.length;e++)a[e]=this._getOrCreateNode(i[e]);this.root=this.peakBagging(this.width,a)}hashLeaf(e,t){return t=this.bufferify(t),this.hashLeafFn?this.bufferify(this.hashLeafFn(e,t)):this.hashFn(hS.Buffer.concat([this.bufferify(e),t]))}hashBranch(e,t,n){return this.hashBranchFn?this.bufferify(this.hashBranchFn(e,t,n)):this.hashFn(hS.Buffer.concat([this.bufferify(e),this.bufferify(t),this.bufferify(n)]))}getPeaks(){const e=this.getPeakIndexes(this.width),t=[];for(let n=0;n<e.length;n++)t[n]=this.hashes[e[n]];return t}getLeafIndex(e){return e%2==1?this.getSize(e):this.getSize(e-1)+1}getPeakIndexes(e){const t=this.numOfPeaks(e),n=[];let r=0,i=0;for(let a=255;a>0&&!(0!=(e&1<<a-1)&&(i=i+(1<<a)-1,n[r++]=i,n.length>=t));a--);if(r!==n.length)throw new Error("invalid bit calculation");return n}numOfPeaks(e){let t=e,n=0;for(;t>0;)t%2==1&&n++,t>>=1;return n}peakBagging(e,t){const n=this.getSize(e);if(this.numOfPeaks(e)!==t.length)throw new Error("received invalid number of peaks");return 0!==e||t.length?this.peakBaggingFn?this.bufferify(this.peakBaggingFn(n,t)):this.hashFn(hS.Buffer.concat([this.bufferify(n),...t.map(this.bufferify)])):hS.Buffer.alloc(0)}getSize(e){return(e<<1)-this.numOfPeaks(e)}getRoot(){return this.root}getHexRoot(){return this.bufferToHex(this.getRoot())}getNode(e){return this.hashes[e]}mountainHeight(e){let t=1;for(;1<<t<=e+t;)t++;return t-1}heightAt(e){let t=e,n=0,r=0;for(;t>n;)t-=(1<<r)-1,r=this.mountainHeight(t),n=(1<<r)-1;return r-(n-t)}isLeaf(e){return 1===this.heightAt(e)}getChildren(e){const t=e-(1<<this.heightAt(e)-1),n=e-1;if(t===n)throw new Error("not a parent");return[t,n]}getMerkleProof(e){if(e>this.size)throw new Error("out of range");if(!this.isLeaf(e))throw new Error("not a leaf");const t=this.root,n=this.width,r=this.getPeakIndexes(this.width),i=[];let a=0;for(let t=0;t<r.length;t++)i[t]=this.hashes[r[t]],r[t]>=e&&0===a&&(a=r[t]);let o=0,s=0,u=this.heightAt(a);const c=[];for(;a!==e;)u--,[o,s]=this.getChildren(a),a=e<=o?o:s,c[u-1]=this.hashes[e<=o?s:o];return{root:t,width:n,peakBagging:i,siblings:c}}verify(e,t,n,r,i,a){r=this.bufferify(r);if(this.getSize(t)<n)throw new Error("index is out of range");if(!e.equals(this.peakBagging(t,i)))throw new Error("invalid root hash from the peaks");let o,s=0;const u=this.getPeakIndexes(t);for(let e=0;e<u.length;e++)if(u[e]>=n){o=i[e],s=u[e];break}if(!o)throw new Error("target not found");let c=a.length+1;const l=new Array(c);let d,f=0,p=0;for(;c>0&&(l[--c]=s,s!==n);)[f,p]=this.getChildren(s),s=n>f?p:f;for(;c<l.length;)s=l[c],d=0===c?this.hashLeaf(s,this.hashFn(r)):s-1===l[c-1]?this.hashBranch(s,a[c-1],d):this.hashBranch(s,d,a[c-1]),c++;if(!d.equals(o))throw new Error("hashed peak is invalid");return!0}peaksToPeakMap(e,t){const n={};let r=0,i=0,a=t.length;for(let o=1;o<=32;o++)r=32-o,i=1<<o-1,n[r]=0!=(e&i)?t[--a]:0;if(0!==a)throw new Error("invalid number of peaks");return n}peakMapToPeaks(e,t){const n=this.numOfPeaks(e),r=new Array(n);let i=0;for(let e=0;e<32;e++)0!==t[e]&&(r[i++]=t[e]);if(i!==n)throw new Error("invalid number of peaks");return r}peakUpdate(e,t,n){const r={},i=e+1;let a=this.getLeafIndex(i),o=this.hashLeaf(a,n),s=0,u=0,c=!1,l=!1,d=!1;for(let n=1;n<=32;n++)s=32-n,d?r[s]=t[s]:(u=1<<n-1,c=0!=(e&u),l=0!=(i&u),a++,c&&(o=this.hashBranch(a,t[s],o)),l?(r[s]=c?t[s]:o,d=!0):r[s]=0);return r}rollUp(e,t,n,r){if(!e.equals(this.peakBagging(t,n)))throw new Error("invalid root hash from the peaks");let i=t,a=this.peaksToPeakMap(t,n);for(let e=0;e<r.length;e++)a=this.peakUpdate(i,a,r[e]),i++;return this.peakBagging(i,this.peakMapToPeaks(i,a))}_getOrCreateNode(e){if(e>this.size)throw new Error("out of range");if(!this.hashes[e]){const[t,n]=this.getChildren(e),r=this._getOrCreateNode(t),i=this._getOrCreateNode(n);this.hashes[e]=this.hashBranch(e,r,i)}return this.hashes[e]}}fS.MerkleMountainRange=gS,"undefined"!=typeof window&&(window.MerkleMountainRange=gS),fS.default=gS;var bS={},vS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(bS,"__esModule",{value:!0}),bS.IncrementalMerkleTree=void 0;const wS=vS(Ek),TS=vS(Ak);class AS extends wS.default{constructor(e,t){if(super(),this.hashFn=e,t.depth&&(this.depth=t.depth),t.arity&&(this.arity=t.arity),this.depth<1)throw new Error("depth must be greater than 0");if(this.arity<1)throw new Error("arity must be greater than 0");const n=[];let r=t.zeroValue;if(this.zeroValue=r,this.zeroes=[],this.depth)for(let e=0;e<this.depth;e++)this.zeroes.push(r),n[e]=[],r=this.hashFn(Array(this.arity).fill(r));this.nodes=n,this.root=r}getRoot(){return this.root}getHexRoot(){return this.bufferToHex(this.bufferify(this.getRoot()))}insert(e){if(this.depth&&this.arity&&this.nodes[0].length>=this.getMaxLeaves())throw new Error("tree is full");let t=e,n=this.nodes[0].length;for(let e=0;e<this.depth;e+=1){const r=n-n%this.arity,i=r+this.arity,a=[];this.nodes[e][n]=t;for(let t=r;t<i;t+=1)t<this.nodes[e].length?a.push(this.nodes[e][t]):a.push(this.zeroes[e]);t=this.hashFn(a),n=Math.floor(n/this.arity)}this.root=t}delete(e){this.update(e,this.zeroValue)}update(e,t){if(e<0||e>=this.nodes[0].length)throw new Error("out of bounds");let n=t;for(let t=0;t<this.depth;t+=1){const r=e-e%this.arity,i=r+this.arity,a=[];this.nodes[t][e]=n;for(let e=r;e<i;e+=1)e<this.nodes[t].length?a.push(this.nodes[t][e]):a.push(this.zeroes[t]);n=this.hashFn(a),e=Math.floor(e/this.arity)}this.root=n}getDepth(){return this.depth}getArity(){return this.arity}getMaxLeaves(){return Math.pow(this.depth,this.arity)}indexOf(e){return this.nodes[0].indexOf(e)}getLeaves(){const e=this.copyList(this.nodes[0]);for(let t=this.nodes[0].length;t<this.getMaxLeaves();t++)e[t]=this.zeroValue;return e}copyList(e){return e.map((e=>BigInt(e)))}getLayers(){const e=[];for(const t of this.nodes)e.push(this.copyList(t));if(e[0].length<this.getMaxLeaves()){let t=e[0].length;for(let n=t;n<this.getMaxLeaves();n++)e[0][n]=this.zeroValue;for(let n=0;n<this.depth;n++){const r=t-t%this.arity,i=r+this.arity;for(let t=r;t<i;t++)t>=e[n].length&&(e[n][t]=this.zeroes[n]);t=Math.floor(t/this.arity)}}return e.push([this.root]),e}getHexLayers(){return this.getLayers().reduce(((e,t)=>(Array.isArray(t)?e.push(t.map((e=>this.bufferToHex(this.bufferify(e))))):e.push(t),e)),[])}getLayersAsObject(){const e=this.getLayers().map((e=>e.map((e=>this.bufferToHex(this.bufferify(e),!1))))),t=[];for(let n=0;n<e.length;n++){const r=[];for(let i=0;i<e[n].length;i++){const a={[e[n][i]]:null};if(t.length){a[e[n][i]]={};const r=t.shift(),o=Object.keys(r)[0];if(a[e[n][i]][o]=r[o],t.length){const r=t.shift(),o=Object.keys(r)[0];a[e[n][i]][o]=r[o]}}r.push(a)}t.push(...r)}return t[0]}computeRoot(){let e,t=this.nodes[0].length;for(let n=0;n<this.depth;n+=1){const r=t-t%this.arity,i=r+this.arity,a=[];for(let e=r;e<i;e+=1)e<this.nodes[n].length?a.push(this.nodes[n][e]):a.push(this.zeroes[n]);e=this.hashFn(a),t=Math.floor(t/this.arity)}return e}getProof(e){if(e<0||e>=this.nodes[0].length)throw new Error("The leaf does not exist in this tree");const t=[],n=[],r=e;for(let r=0;r<this.depth;r+=1){const i=e%this.arity,a=e-i,o=a+this.arity;n[r]=i,t[r]=[];for(let n=a;n<o;n+=1)n!==e&&(n<this.nodes[r].length?t[r].push(this.nodes[r][n]):t[r].push(this.zeroes[r]));e=Math.floor(e/this.arity)}return{root:this.root,leaf:this.nodes[0][r],pathIndices:n,siblings:t}}verify(e){let t=e.leaf;for(let n=0;n<e.siblings.length;n+=1){const r=e.siblings[n].slice();r.splice(e.pathIndices[n],0,t),t=this.hashFn(r)}return e.root===t}toString(){return this.toTreeString()}toTreeString(){const e=this.getLayersAsObject();return TS.default.asTree(e,!0)}}bS.IncrementalMerkleTree=AS,"undefined"!=typeof window&&(window.IncrementalMerkleTree=AS),bS.default=AS;var ES={};Object.defineProperty(ES,"__esModule",{value:!0}),ES.MerkleSumTree=ES.ProofStep=ES.Leaf=ES.Bucket=void 0;const _S=Ek;class IS{constructor(e,t){this.size=BigInt(e),this.hashed=t,this.parent=null,this.left=null,this.right=null}}ES.Bucket=IS;ES.Leaf=class{constructor(e,t,n){this.hashFn=e,this.rng=t.map((e=>BigInt(e))),this.data=n}getBucket(){let e;return e=this.data?this.hashFn(this.data):Buffer.alloc(32),new IS(BigInt(this.rng[1])-BigInt(this.rng[0]),e)}};class RS{constructor(e,t){this.bucket=e,this.right=t}}ES.ProofStep=RS;class CS extends _S.Base{constructor(e,t){super(),this.leaves=e,this.hashFn=t,CS.checkConsecutive(e),this.buckets=[];for(const t of e)this.buckets.push(t.getBucket());let n=[];for(const e of this.buckets)n.push(e);for(;1!==n.length;){const e=[];for(;n.length;)if(n.length>=2){const t=n.shift(),r=n.shift(),i=t.size+r.size,a=this.hashFn(Buffer.concat([this.sizeToBuffer(t.size),this.bufferify(t.hashed),this.sizeToBuffer(r.size),this.bufferify(r.hashed)])),o=new IS(i,a);r.parent=o,t.parent=r.parent,t.right=r,r.left=t,e.push(o)}else e.push(n.shift());n=e}this.root=n[0]}sizeToBuffer(e){const t=Buffer.alloc(8);return new DataView(t.buffer).setBigInt64(0,BigInt(e),!1),t}static checkConsecutive(e){let t=BigInt(0);for(const n of e){if(n.rng[0]!==t)throw new Error("leaf ranges are invalid");t=BigInt(n.rng[1])}}getProof(e){let t=this.buckets[Number(e)];const n=[];for(;t&&t.parent;){const e=!!t.right,r=t.right?t.right:t.left;t=t.parent,n.push(new RS(r,e))}return n}sum(e){let t=BigInt(0);for(const n of e)t+=BigInt(n);return t}verifyProof(e,t,n){const r=[this.sum(n.filter((e=>!e.right)).map((e=>e.bucket.size))),BigInt(e.size)-this.sum(n.filter((e=>e.right)).map((e=>e.bucket.size)))];if(r[0]!==t.rng[0]||r[1]!==t.rng[1])return!1;let i,a=t.getBucket();for(const e of n)i=e.right?this.hashFn(Buffer.concat([this.sizeToBuffer(a.size),this.bufferify(a.hashed),this.sizeToBuffer(e.bucket.size),this.bufferify(e.bucket.hashed)])):this.hashFn(Buffer.concat([this.sizeToBuffer(e.bucket.size),this.bufferify(e.bucket.hashed),this.sizeToBuffer(a.size),this.bufferify(a.hashed)])),a=new IS(BigInt(a.size)+BigInt(e.bucket.size),i);return a.size===e.size&&a.hashed.toString("hex")===e.hashed.toString("hex")}}ES.MerkleSumTree=CS,"undefined"!=typeof window&&(window.MerkleSumTree=CS),ES.default=CS,function(e){var t=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.MerkleTree=void 0;const n=t(pk);e.MerkleTree=n.default;var r=fS;Object.defineProperty(e,"MerkleMountainRange",{enumerable:!0,get:function(){return r.MerkleMountainRange}});var i=bS;Object.defineProperty(e,"IncrementalMerkleTree",{enumerable:!0,get:function(){return i.IncrementalMerkleTree}});var a=ES;Object.defineProperty(e,"MerkleSumTree",{enumerable:!0,get:function(){return a.MerkleSumTree}}),e.default=n.default}(fk);var kS={};Object.defineProperty(kS,"__esModule",{value:!0}),kS.DefaultGetter=void 0;const OS=pC,SS=new AC.Logger("defaults"),NS={integer:0,address:(0,OS.hexZeroPad)("0x",20),bool:!1,bytes:"0x",string:""},xS=e=>void 0!==e&&(null!=e&&(["string","number"].includes(typeof e)&&BigInt(e)===BigInt(0)||Array.isArray(e)&&e.every(xS)||"object"==typeof e&&Object.values(e).every(xS)||"boolean"==typeof e&&!1===e));class PS{constructor(e){this.types=e,this.defaultValues={};for(const t in e){const e=this.getDefaultValue(t);this.defaultValues[t]=e,xS(e)||SS.throwError(`Got non-empty value for type ${t} in default generator: ${e}`)}}static from(e,t){const{defaultValues:n}=new PS(e);return t?n[t]:n}getDefaultValue(e){if(this.defaultValues[e])return this.defaultValues[e];const t=function(e){var t;const[,n]=null!==(t=e.match(/^bytes(\d+)$/))&&void 0!==t?t:[];return n?(0,OS.hexZeroPad)("0x",parseInt(n)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),NS[e])}(e);if(void 0!==t)return t;const n=e.match(/^(.*)(\x5b(\d*)\x5d)$/);if(n){const e=n[1],t=parseInt(n[3]);if(t>0){const n=this.getDefaultValue(e);return Array(t).fill(n)}return[]}const r=this.types[e];return r?r.reduce(((e,{name:t,type:n})=>Object.assign(Object.assign({},e),{[t]:this.getDefaultValue(n)})),{}):SS.throwArgumentError(`unknown type: ${e}`,"type",e)}}kS.DefaultGetter=PS;var MS={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getNextLayer=e.getRoot=e.fillArray=e.hashConcat=e.bufferKeccak=e.hexToBuffer=e.bufferToHex=e.chunk=e.makeArray=void 0;const t=pC;e.makeArray=(e,t)=>Array(e).fill(0).map(((e,n)=>t(n)));e.chunk=(t,n)=>(0,e.makeArray)(Math.ceil(t.length/n),(e=>t.slice(e*n,(e+1)*n)));e.bufferToHex=e=>(0,t.hexlify)(e);e.hexToBuffer=e=>Buffer.from(e.slice(2),"hex");e.bufferKeccak=n=>(0,e.hexToBuffer)((0,t.keccak256)(n));e.hashConcat=n=>(0,e.bufferKeccak)((0,t.hexConcat)(n));e.fillArray=(e,t,n)=>(t>e.length&&e.push(...Array(t-e.length).fill(n)),e);e.getRoot=(t,n=!0)=>{if(0===t.length)throw new Error("empty tree");const r=[t.map((t=>{const r=Buffer.isBuffer(t)?t:(0,e.hexToBuffer)(t);return n?(0,e.bufferKeccak)(r):r}))];for(;r[r.length-1].length>1;)r.push((0,e.getNextLayer)(r[r.length-1]));return r[r.length-1][0]};e.getNextLayer=t=>(0,e.chunk)(t,2).map(e.hashConcat)}(MS),Object.defineProperty(dk,"__esModule",{value:!0}),dk.Eip712MerkleTree=void 0;const BS=bC,DS=pC,FS=fk,LS=kS,US=MS;dk.Eip712MerkleTree=class{get completedSize(){return Math.pow(2,this.depth)}getCompleteElements(){const e=this.elements;return(0,US.fillArray)([...e],this.completedSize,this.defaultNode)}getCompleteLeaves(){const e=this.elements.map(this.leafHasher);return(0,US.fillArray)([...e],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(e){const t=this.getCompleteLeaves()[e];return{leaf:t,proof:this.tree.getHexProof(t,e),root:this.tree.getHexRoot()}}getEncodedProofAndSignature(e,t){const{proof:n}=this.getProof(e);return((e,t,n=`0x${"ff".repeat(64)}`)=>(0,DS.hexConcat)([n,`0x${e.toString(16).padStart(6,"0")}`,DS.defaultAbiCoder.encode([`uint256[${t.length}]`],[t])]))(e,n,t)}getDataToSign(){let e=this.getCompleteElements();for(;e.length>2;)e=(0,US.chunk)(e,2);return e}add(e){this.elements.push(e)}getBulkOrderHash(){const e=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),t=this.getCompleteLeaves().map(US.hexToBuffer),n=(0,US.bufferToHex)((0,US.getRoot)(t,!1)),r=(0,DS.keccak256)((0,DS.toUtf8Bytes)(this.encoder._types.BulkOrder));if((0,DS.keccak256)((0,DS.hexConcat)([r,n]))!==e)throw new Error("expected derived bulk order hash to match");return e}constructor(e,t,n,r,i){this.types=e,this.rootType=t,this.leafType=n,this.elements=r,this.depth=i;const a=BS._TypedDataEncoder.from(e);var o,s;this.encoder=a,this.leafHasher=e=>a.hashStruct(n,e),this.defaultNode=LS.DefaultGetter.from(e,n),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=(o=this.getCompleteLeaves(),s=this.defaultLeaf,new FS.MerkleTree(o.map(US.hexToBuffer),US.bufferKeccak,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:(0,US.hexToBuffer)(s)}))}},Object.defineProperty(lk,"__esModule",{value:!0}),lk.getBulkOrderTypeHashes=lk.getBulkOrderTypeHash=lk.getBulkOrderTree=lk.getBulkOrderTreeHeight=void 0;const qS=pC,jS=dk,GS=kS,HS=MS,zS=BC;function VS(e){const t=Object.assign({},zS.EIP_712_BULK_ORDER_TYPE);return t.BulkOrder=[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}],t}function WS(e){return Math.max(Math.ceil(Math.log2(e)),1)}function KS(e){const t=VS(e),n=qS._TypedDataEncoder.from(t),r=(0,qS.toUtf8Bytes)(n._types.BulkOrder);return(0,qS.keccak256)(r)}lk.getBulkOrderTreeHeight=WS,lk.getBulkOrderTree=function(e,t=0,n=WS(e.length+t)){const r=VS(n),i=GS.DefaultGetter.from(r,"OrderComponents");let a=[...e];return t>0&&(a=[...(0,HS.fillArray)([],t,i),...e]),new jS.Eip712MerkleTree(r,"BulkOrder","OrderComponents",a,n)},lk.getBulkOrderTypeHash=KS,lk.getBulkOrderTypeHashes=function(e){const t=[];for(let n=0;n<e;n++)t.push(KS(n+1));return t};var XS={},JS={},YS={};Object.defineProperty(YS,"__esModule",{value:!0}),YS.MerkleTree=void 0;const QS=fC,ZS=pC,$S=fk,eN=e=>(0,ZS.keccak256)(Buffer.from(QS.BigNumber.from(e).toHexString().slice(2).padStart(64,"0"),"hex"));YS.MerkleTree=class{constructor(e){this.tree=new $S.default(e.map(eN),ZS.keccak256,{sort:!0})}getProof(e){return this.tree.getHexProof(eN(e))}getRoot(){return this.tree.getRoot().toString("hex")?this.tree.getHexRoot():"0"}},Object.defineProperty(JS,"__esModule",{value:!0}),JS.shouldUseMatchForFulfill=JS.generateRandomSalt=JS.mapOrderAmountsFromUnitsToFill=JS.mapOrderAmountsFromFilledStatus=JS.totalItemsAmount=JS.areAllCurrenciesSame=JS.mapInputItemToOfferItem=JS.deductFees=JS.feeToConsiderationItem=void 0;const tN=fC,nN=pC,rN=BC,iN=VC(),aN=YS,oN=(e,t)=>tN.BigNumber.from(e).mul(tN.BigNumber.from(t)).div(rN.ONE_HUNDRED_PERCENT_BP);JS.feeToConsiderationItem=({fee:e,token:t,baseAmount:n,baseEndAmount:r=n})=>({itemType:t===tN.ethers.constants.AddressZero?rN.ItemType.NATIVE:rN.ItemType.ERC20,token:t,identifierOrCriteria:"0",startAmount:oN(n,e.basisPoints).toString(),endAmount:oN(r,e.basisPoints).toString(),recipient:e.recipient});JS.deductFees=(e,t)=>{if(!t)return e;const n=t.reduce(((e,t)=>e+t.basisPoints),0);return e.map((e=>Object.assign(Object.assign({},e),{startAmount:(0,iN.isCurrencyItem)(e)?tN.BigNumber.from(e.startAmount).sub(oN(e.startAmount,n)).toString():e.startAmount,endAmount:(0,iN.isCurrencyItem)(e)?tN.BigNumber.from(e.endAmount).sub(oN(e.endAmount,n)).toString():e.endAmount})))};JS.mapInputItemToOfferItem=e=>{var t,n,r,i,a,o,s,u;if("itemType"in e){if("identifiers"in e||"criteria"in e){const i="criteria"in e?e.criteria:new aN.MerkleTree(e.identifiers).getRoot();return{itemType:e.itemType===rN.ItemType.ERC721?rN.ItemType.ERC721_WITH_CRITERIA:rN.ItemType.ERC1155_WITH_CRITERIA,token:e.token,identifierOrCriteria:i,startAmount:null!==(t=e.amount)&&void 0!==t?t:"1",endAmount:null!==(r=null!==(n=e.endAmount)&&void 0!==n?n:e.amount)&&void 0!==r?r:"1"}}return"amount"in e||"endAmount"in e?{itemType:e.itemType,token:e.token,identifierOrCriteria:null!==(i=e.identifier)&&void 0!==i?i:"0",startAmount:e.amount,endAmount:null!==(o=null!==(a=e.endAmount)&&void 0!==a?a:e.amount)&&void 0!==o?o:"1"}:{itemType:e.itemType,token:e.token,identifierOrCriteria:e.identifier,startAmount:"1",endAmount:"1"}}return{itemType:e.token&&e.token!==tN.ethers.constants.AddressZero?rN.ItemType.ERC20:rN.ItemType.NATIVE,token:null!==(s=e.token)&&void 0!==s?s:tN.ethers.constants.AddressZero,identifierOrCriteria:"0",startAmount:e.amount,endAmount:null!==(u=e.endAmount)&&void 0!==u?u:e.amount}};JS.areAllCurrenciesSame=({offer:e,consideration:t})=>{const n=[...e,...t].filter(iN.isCurrencyItem);return n.every((({itemType:e,token:t})=>e===n[0].itemType&&t.toLowerCase()===n[0].token.toLowerCase()))};JS.totalItemsAmount=e=>(tN.BigNumber.from(0),tN.BigNumber.from(0),e.map((({startAmount:e,endAmount:t})=>({startAmount:e,endAmount:t}))).reduce((({startAmount:e,endAmount:t},{startAmount:n,endAmount:r})=>({startAmount:e.add(n),endAmount:t.add(r)})),{startAmount:tN.BigNumber.from(0),endAmount:tN.BigNumber.from(0)}));JS.mapOrderAmountsFromFilledStatus=(e,{totalFilled:t,totalSize:n})=>{if(t.eq(0)||n.eq(0))return e;const r=n.sub(t).mul(rN.ONE_HUNDRED_PERCENT_BP).div(n);return{parameters:Object.assign(Object.assign({},e.parameters),{offer:e.parameters.offer.map((e=>Object.assign(Object.assign({},e),{startAmount:oN(e.startAmount,r).toString(),endAmount:oN(e.endAmount,r).toString()}))),consideration:e.parameters.consideration.map((e=>Object.assign(Object.assign({},e),{startAmount:oN(e.startAmount,r).toString(),endAmount:oN(e.endAmount,r).toString()})))}),signature:e.signature}};const sN=(e,t,n)=>tN.BigNumber.from(e).mul(tN.BigNumber.from(t)).div(n);JS.mapOrderAmountsFromUnitsToFill=(e,{unitsToFill:t,totalSize:n})=>{const r=tN.BigNumber.from(t);if(r.lte(0))throw new Error("Units to fill must be greater than 1");const i=(0,iN.getMaximumSizeForOrder)(e);return n.eq(0)&&(n=i),{parameters:Object.assign(Object.assign({},e.parameters),{offer:e.parameters.offer.map((e=>Object.assign(Object.assign({},e),{startAmount:sN(e.startAmount,r,n).toString(),endAmount:sN(e.endAmount,r,n).toString()}))),consideration:e.parameters.consideration.map((e=>Object.assign(Object.assign({},e),{startAmount:sN(e.startAmount,r,n).toString(),endAmount:sN(e.endAmount,r,n).toString()})))}),signature:e.signature}};JS.generateRandomSalt=e=>e?`0x${Buffer.from((0,nN.concat)([(0,nN.keccak256)((0,nN.toUtf8Bytes)(e)).slice(0,10),Uint8Array.from(Array(20).fill(0)),(0,nN.randomBytes)(8)])).toString("hex")}`:`0x${Buffer.from((0,nN.randomBytes)(8)).toString("hex").padStart(64,"0")}`;JS.shouldUseMatchForFulfill=()=>!0,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getAdvancedOrderNumeratorDenominator=e.generateFulfillOrdersFulfillments=e.fulfillAvailableOrders=e.validateAndSanitizeFromOrderStatus=e.fulfillStandardOrder=e.fulfillBasicOrder=e.shouldUseBasicFulfill=void 0;const t=fC,n=BC,r=DC,i=ek,a=GC(),o=zC,s=VC(),u=JS,c=WC;e.shouldUseBasicFulfill=({offer:e,consideration:r,offerer:i},a)=>{if(!a.eq(0))return!1;if(e.length>1||0===r.length)return!1;const o=[...e,...r],c=o.filter((({itemType:e})=>[n.ItemType.ERC721,n.ItemType.ERC1155].includes(e))),l=o.filter((({itemType:e})=>(0,s.isCriteriaItem)(e)));if((0,s.isNativeCurrencyItem)(e[0]))return!1;if(1!==c.length||0!==l.length)return!1;if(!(0,u.areAllCurrenciesSame)({offer:e,consideration:r}))return!1;if(o.some((({startAmount:e,endAmount:t})=>e!==t)))return!1;const[d,...f]=r;if(d.recipient.toLowerCase()!==i.toLowerCase())return!1;if(r.length>1&&f.every((t=>t.itemType===e[0].itemType))&&(0,u.totalItemsAmount)(f).endAmount.gt(e[0].endAmount))return!1;const p=o.filter(s.isCurrencyItem),h=p.filter((({itemType:e})=>e===n.ItemType.NATIVE)).every((({token:e})=>e===t.ethers.constants.AddressZero)),m=p.every((({identifierOrCriteria:e})=>t.BigNumber.from(e).eq(0))),y=c.filter((({itemType:e})=>e===n.ItemType.ERC721)).every((({endAmount:e})=>"1"===e));return h&&m&&y};const l={[n.ItemType.ERC20]:{[n.ItemType.ERC721]:n.BasicOrderRouteType.ERC721_TO_ERC20,[n.ItemType.ERC1155]:n.BasicOrderRouteType.ERC1155_TO_ERC20},[n.ItemType.ERC721]:{[n.ItemType.NATIVE]:n.BasicOrderRouteType.ETH_TO_ERC721,[n.ItemType.ERC20]:n.BasicOrderRouteType.ERC20_TO_ERC721},[n.ItemType.ERC1155]:{[n.ItemType.NATIVE]:n.BasicOrderRouteType.ETH_TO_ERC1155,[n.ItemType.ERC20]:n.BasicOrderRouteType.ERC20_TO_ERC1155}};function d(e,t){const{isValidated:n,isCancelled:r,totalFilled:i,totalSize:a}=t;if(a.gt(0)&&i.div(a).eq(1))throw new Error("The order you are trying to fulfill is already filled");if(r)throw new Error("The order you are trying to fulfill is cancelled");return n?{parameters:Object.assign({},e.parameters),signature:"0x"}:e}function f(e){const t=({sourceOrDestination:e,operator:t="",token:n,identifier:r})=>`${e}-${t}-${n}-${r}`,n={},r={};return e.forEach((({order:e,offererOperator:r,offerCriteria:i},o)=>{const u=(0,a.getItemToCriteriaMap)(e.parameters.offer,i);return e.parameters.offer.forEach(((i,a)=>{var c,l,d;const f=`${t({sourceOrDestination:e.parameters.offerer,operator:r,token:i.token,identifier:null!==(l=null===(c=u.get(i))||void 0===c?void 0:c.identifier)&&void 0!==l?l:i.identifierOrCriteria})}${(0,s.isErc721Item)(i.itemType)?a:""}`;n[f]=[...null!==(d=n[f])&&void 0!==d?d:[],{orderIndex:o,itemIndex:a}]}))})),e.forEach((({order:e,considerationCriteria:n,tips:i},o)=>{const u=(0,a.getItemToCriteriaMap)(e.parameters.consideration,n);return[...e.parameters.consideration,...i].forEach(((e,n)=>{var i,a,c;const l=`${t({sourceOrDestination:e.recipient,token:e.token,identifier:null!==(a=null===(i=u.get(e))||void 0===i?void 0:i.identifier)&&void 0!==a?a:e.identifierOrCriteria})}${(0,s.isErc721Item)(e.itemType)?n:""}`;r[l]=[...null!==(c=r[l])&&void 0!==c?c:[],{orderIndex:o,itemIndex:n}]}))})),{offerFulfillments:Object.values(n),considerationFulfillments:Object.values(r)}}e.fulfillBasicOrder=function({order:e,seaportContract:a,offererBalancesAndApprovals:o,fulfillerBalancesAndApprovals:u,timeBasedItemParams:d,offererOperator:f,fulfillerOperator:p,signer:h,tips:m=[],conduitKey:y=n.NO_CONDUIT,domain:g},b){var v,w;const{offer:T,consideration:A}=e.parameters,E=[...A,...m],_=T[0],[I,...R]=E,C=null===(v=l[_.itemType])||void 0===v?void 0:v[I.itemType];if(void 0===C)throw new Error("Order parameters did not result in a valid basic fulfillment");const k=R.map((({startAmount:e,recipient:t})=>({amount:e,recipient:t}))),O=E.filter((e=>e.itemType!==T[0].itemType)),S=null===(w=(0,s.getSummedTokenAndIdentifierAmounts)({items:O,criterias:[],timeBasedItemParams:Object.assign(Object.assign({},d),{isConsiderationItem:!0})})[t.ethers.constants.AddressZero])||void 0===w?void 0:w[0],N=(0,i.validateBasicFulfillBalancesAndApprovals)({offer:T,consideration:E,offererBalancesAndApprovals:o,fulfillerBalancesAndApprovals:u,timeBasedItemParams:d,offererOperator:f,fulfillerOperator:p}),x={offerer:e.parameters.offerer,offererConduitKey:e.parameters.conduitKey,zone:e.parameters.zone,basicOrderType:e.parameters.orderType+4*C,offerToken:_.token,offerIdentifier:_.identifierOrCriteria,offerAmount:_.endAmount,considerationToken:I.token,considerationIdentifier:I.identifierOrCriteria,considerationAmount:I.endAmount,startTime:e.parameters.startTime,endTime:e.parameters.endTime,salt:e.parameters.salt,totalOriginalAdditionalRecipients:e.parameters.consideration.length-1,signature:e.signature,fulfillerConduitKey:y,additionalRecipients:k,zoneHash:e.parameters.zoneHash},P={value:S},M=[...(0,r.getApprovalActions)(N,b,h),{type:"exchange",transactionMethods:(0,c.getTransactionMethods)(a.connect(h),"fulfillBasicOrder",[x,P],g)}];return{actions:M,executeAllActions:()=>(0,c.executeAllActions)(M)}},e.fulfillStandardOrder=function({order:n,unitsToFill:o=0,totalSize:l,totalFilled:d,offerCriteria:f,considerationCriteria:p,tips:h=[],extraData:m,seaportContract:y,offererBalancesAndApprovals:g,fulfillerBalancesAndApprovals:b,offererOperator:v,fulfillerOperator:w,timeBasedItemParams:T,conduitKey:A,recipientAddress:E,signer:_,domain:I},R){var C;const k=o?(0,u.mapOrderAmountsFromUnitsToFill)(n,{unitsToFill:o,totalSize:l}):(0,u.mapOrderAmountsFromFilledStatus)(n,{totalFilled:d,totalSize:l}),{parameters:{offer:O,consideration:S}}=k,N=[...S,...h],x=O.filter((({itemType:e})=>(0,s.isCriteriaItem)(e))),P=N.filter((({itemType:e})=>(0,s.isCriteriaItem)(e))),M=x.length>0||P.length>0;if(x.length!==f.length||P.length!==p.length)throw new Error("You must supply the appropriate criterias for criteria based items");const B=null===(C=(0,s.getSummedTokenAndIdentifierAmounts)({items:N,criterias:p,timeBasedItemParams:Object.assign(Object.assign({},T),{isConsiderationItem:!0})})[t.ethers.constants.AddressZero])||void 0===C?void 0:C[0],D=(0,i.validateStandardFulfillBalancesAndApprovals)({offer:O,consideration:N,offerCriteria:f,considerationCriteria:p,offererBalancesAndApprovals:g,fulfillerBalancesAndApprovals:b,timeBasedItemParams:T,offererOperator:v,fulfillerOperator:w}),F={value:B},L=(0,r.getApprovalActions)(D,R,_),U=E!==t.ethers.constants.AddressZero,q=Boolean(o)||M||U,j=Object.assign(Object.assign({},n),{parameters:Object.assign(Object.assign({},n.parameters),{consideration:[...n.parameters.consideration,...h],totalOriginalConsiderationItems:S.length})}),{numerator:G,denominator:H}=(0,e.getAdvancedOrderNumeratorDenominator)(n,o),z=[...L,{type:"exchange",transactionMethods:q?(0,c.getTransactionMethods)(y.connect(_),"fulfillAdvancedOrder",[Object.assign(Object.assign({},j),{numerator:G,denominator:H,extraData:null!=m?m:"0x"}),M?(0,a.generateCriteriaResolvers)({orders:[n],offerCriterias:[f],considerationCriterias:[p]}):[],A,E,F],I):(0,c.getTransactionMethods)(y.connect(_),"fulfillOrder",[j,A,F],I)}];return{actions:z,executeAllActions:()=>(0,c.executeAllActions)(z)}},e.validateAndSanitizeFromOrderStatus=d,e.fulfillAvailableOrders=function({ordersMetadata:n,seaportContract:o,fulfillerBalancesAndApprovals:l,fulfillerOperator:p,currentBlockTimestamp:h,ascendingAmountTimestampBuffer:m,conduitKey:y,signer:g,recipientAddress:b,exactApproval:v,domain:w}){const T=n.map((e=>Object.assign(Object.assign({},e),{order:d(e.order,e.orderStatus)}))),A=T.map((e=>Object.assign(Object.assign({},e),{order:e.unitsToFill?(0,u.mapOrderAmountsFromUnitsToFill)(e.order,{unitsToFill:e.unitsToFill,totalSize:e.orderStatus.totalSize}):(0,u.mapOrderAmountsFromFilledStatus)(e.order,{totalFilled:e.orderStatus.totalFilled,totalSize:e.orderStatus.totalSize})})));let E=t.BigNumber.from(0);const _=[],I=T.flatMap((e=>[e.order.parameters.offer,e.order.parameters.consideration])).flat().filter((({itemType:e})=>(0,s.isCriteriaItem)(e))).length>0;A.forEach((({order:e,tips:n,offerCriteria:r,considerationCriteria:a,offererBalancesAndApprovals:o,offererOperator:u})=>{var c,d;const f=[...e.parameters.consideration,...n],y={startTime:e.parameters.startTime,endTime:e.parameters.endTime,currentBlockTimestamp:h,ascendingAmountTimestampBuffer:m,isConsiderationItem:!0};E=E.add(null!==(d=null===(c=(0,s.getSummedTokenAndIdentifierAmounts)({items:f,criterias:a,timeBasedItemParams:y})[t.ethers.constants.AddressZero])||void 0===c?void 0:c[0])&&void 0!==d?d:t.BigNumber.from(0));const g=(0,i.validateStandardFulfillBalancesAndApprovals)({offer:e.parameters.offer,consideration:f,offerCriteria:r,considerationCriteria:a,offererBalancesAndApprovals:o,fulfillerBalancesAndApprovals:l,timeBasedItemParams:y,offererOperator:u,fulfillerOperator:p}),b=e.parameters.offer.filter((({itemType:e})=>(0,s.isCriteriaItem)(e))),v=f.filter((({itemType:e})=>(0,s.isCriteriaItem)(e)));if(b.length!==r.length||v.length!==a.length)throw new Error("You must supply the appropriate criterias for criteria based items");g.forEach((e=>{_.find((t=>t.token===e.token))||_.push(e)}))}));const R={value:E},C=(0,r.getApprovalActions)(_,v,g),k=T.map((({order:t,unitsToFill:n=0,tips:r,extraData:i})=>{const{numerator:a,denominator:o}=(0,e.getAdvancedOrderNumeratorDenominator)(t,n),s=[...t.parameters.consideration,...r];return Object.assign(Object.assign({},t),{parameters:Object.assign(Object.assign({},t.parameters),{consideration:s,totalOriginalConsiderationItems:t.parameters.consideration.length}),numerator:a,denominator:o,extraData:i})})),{offerFulfillments:O,considerationFulfillments:S}=f(n),N={type:"exchange",transactionMethods:(0,c.getTransactionMethods)(o.connect(g),"fulfillAvailableAdvancedOrders",[k,I?(0,a.generateCriteriaResolvers)({orders:n.map((({order:e})=>e)),offerCriterias:n.map((({offerCriteria:e})=>e)),considerationCriterias:n.map((({considerationCriteria:e})=>e))}):[],O,S,y,b,k.length,R],w)},x=[...C,N];return{actions:x,executeAllActions:()=>(0,c.executeAllActions)(x)}},e.generateFulfillOrdersFulfillments=f;e.getAdvancedOrderNumeratorDenominator=(e,n)=>{const r=(0,s.getMaximumSizeForOrder)(e),i=t.BigNumber.from(n),a=(0,o.gcd)(i,r);return{numerator:n?i.div(a):t.BigNumber.from(1),denominator:n?r.div(a):t.BigNumber.from(1)}}}(XS);var uN=ct&&ct.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,a){function o(e){try{u(r.next(e))}catch(e){a(e)}}function s(e){try{u(r.throw(e))}catch(e){a(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}u((r=r.apply(e,t||[])).next())}))};Object.defineProperty(jR,"__esModule",{value:!0}),jR.Seaport=void 0;const cN=dC,lN=fC,dN=pC,fN=PC,pN=MC,hN=BC,mN=DC,yN=ek,gN=lk,bN=XS,vN=VC(),wN=JS,TN=WC;jR.Seaport=class{constructor(e,{overrides:t,ascendingAmountFulfillmentBuffer:n=300,balanceAndApprovalChecksOnOrderCreation:r=!0,conduitKeyToConduit:i,seaportVersion:a="1.5"}={}){var o,s,u;this.OPENSEA_CONDUIT_KEY=hN.OPENSEA_CONDUIT_KEY,this.getOrderHash=e=>{const t="OfferItem(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)",n="ConsiderationItem(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)",r=`OrderComponents(address offerer,address zone,OfferItem[] offer,ConsiderationItem[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 counter)${n}${t}`,i=lN.ethers.utils.keccak256(lN.ethers.utils.toUtf8Bytes(t)),a=lN.ethers.utils.keccak256(lN.ethers.utils.toUtf8Bytes(n)),o=lN.ethers.utils.keccak256(lN.ethers.utils.toUtf8Bytes(r)),s=lN.ethers.utils.keccak256("0x"+e.offer.map((e=>lN.ethers.utils.keccak256("0x"+[i.slice(2),e.itemType.toString().padStart(64,"0"),e.token.slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.identifierOrCriteria).toHexString().slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.startAmount).toHexString().slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.endAmount).toHexString().slice(2).padStart(64,"0")].join("")).slice(2))).join("")),u=lN.ethers.utils.keccak256("0x"+e.consideration.map((e=>lN.ethers.utils.keccak256("0x"+[a.slice(2),e.itemType.toString().padStart(64,"0"),e.token.slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.identifierOrCriteria).toHexString().slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.startAmount).toHexString().slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.endAmount).toHexString().slice(2).padStart(64,"0"),e.recipient.slice(2).padStart(64,"0")].join("")).slice(2))).join(""));return lN.ethers.utils.keccak256("0x"+[o.slice(2),e.offerer.slice(2).padStart(64,"0"),e.zone.slice(2).padStart(64,"0"),s.slice(2),u.slice(2),e.orderType.toString().padStart(64,"0"),lN.ethers.BigNumber.from(e.startTime).toHexString().slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.endTime).toHexString().slice(2).padStart(64,"0"),e.zoneHash.slice(2),lN.BigNumber.from(e.salt).toHexString().slice(2).padStart(64,"0"),e.conduitKey.slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.counter).toHexString().slice(2).padStart(64,"0")].join(""))};const c=e instanceof lN.providers.Provider?e:e.provider;if(this.signer=e._isSigner?e:void 0,!c)throw new Error("Either a provider or custom signer with provider must be provided");this.provider=c,this.multicallProvider=new cN.providers.MulticallProvider(this.provider),this.contract=new lN.Contract(null!==(o=null==t?void 0:t.contractAddress)&&void 0!==o?o:"1.5"===a?hN.CROSS_CHAIN_SEAPORT_V1_5_ADDRESS:hN.CROSS_CHAIN_SEAPORT_V1_4_ADDRESS,pN.SeaportABIv14,this.multicallProvider),this.domainRegistry=new lN.Contract(null!==(s=null==t?void 0:t.domainRegistryAddress)&&void 0!==s?s:hN.DOMAIN_REGISTRY_ADDRESS,fN.DomainRegistryABI,this.multicallProvider),this.config={ascendingAmountFulfillmentBuffer:n,balanceAndApprovalChecksOnOrderCreation:r,conduitKeyToConduit:Object.assign(Object.assign(Object.assign({},hN.KNOWN_CONDUIT_KEYS_TO_CONDUIT),{[hN.NO_CONDUIT]:this.contract.address}),i),seaportVersion:a},this.defaultConduitKey=null!==(u=null==t?void 0:t.defaultConduitKey)&&void 0!==u?u:hN.NO_CONDUIT}createOrder(e,t,n){return uN(this,void 0,void 0,(function*(){const r=this._getSigner(t),i=null!=t?t:yield r.getAddress(),{orderComponents:a,approvalActions:o}=yield this._formatOrder(r,i,Boolean(n),e),s={type:"create",getMessageToSign:()=>this._getMessageToSign(a),createOrder:()=>uN(this,void 0,void 0,(function*(){const e=yield this.signOrder(a,i);return{parameters:a,signature:e}}))},u=[...o,s];return{actions:u,executeAllActions:()=>(0,TN.executeAllActions)(u)}}))}createBulkOrders(e,t,n){var r;return uN(this,void 0,void 0,(function*(){const i=this._getSigner(t),a=yield i.getAddress(),o=yield this.getCounter(a),s=[],u=[];for(const t of e){null!==(r=t.counter)&&void 0!==r||(t.counter=o);const{orderComponents:e,approvalActions:c}=yield this._formatOrder(i,a,Boolean(n),t);u.push(e);for(const e of c)void 0===s.find((t=>t.token===e.token))&&s.push(e)}const c={type:"createBulk",getMessageToSign:()=>this._getBulkMessageToSign(u),createBulkOrders:()=>uN(this,void 0,void 0,(function*(){return yield this.signBulkOrder(u,a)}))},l=[...s,c];return{actions:l,executeAllActions:()=>(0,TN.executeAllActions)(l)}}))}_formatOrder(e,t,n,{conduitKey:r=this.defaultConduitKey,zone:i=lN.ethers.constants.AddressZero,zoneHash:a=lN.ethers.constants.HashZero,startTime:o=Math.floor(Date.now()/1e3).toString(),endTime:s=hN.MAX_INT.toString(),offer:u,consideration:c,counter:l,allowPartialFills:d,restrictedByZone:f,fees:p,domain:h,salt:m}){var y;return uN(this,void 0,void 0,(function*(){const g=u.map(wN.mapInputItemToOfferItem),b=[...c.map((e=>{var n;return Object.assign(Object.assign({},(0,wN.mapInputItemToOfferItem)(e)),{recipient:null!==(n=e.recipient)&&void 0!==n?n:t})}))];if((null==p?void 0:p.length)&&!(0,wN.areAllCurrenciesSame)({offer:g,consideration:b}))throw new Error("All currency tokens in the order must be the same token when applying fees");const v=[...g,...b].filter(vN.isCurrencyItem),w=(0,wN.totalItemsAmount)(v),T=this.config.conduitKeyToConduit[r],A=this._getOrderTypeFromOrderOptions({allowPartialFills:d,restrictedByZone:f}),E=[...(0,wN.deductFees)(b,p),...v.length&&null!==(y=null==p?void 0:p.map((e=>(0,wN.feeToConsiderationItem)({fee:e,token:v[0].token,baseAmount:w.startAmount,baseEndAmount:w.endAmount}))))&&void 0!==y?y:[]],_=void 0!==m?`0x${lN.BigNumber.from(m).toHexString().slice(2).padStart(64,"0")}`:(0,wN.generateRandomSalt)(h),I={offerer:t,zone:i,zoneHash:a,startTime:o,endTime:s,orderType:A,offer:g,consideration:E,totalOriginalConsiderationItems:E.length,salt:_,conduitKey:r,counter:(null!=l?l:yield this.getCounter(t)).toString()},R=[];if(this.config.balanceAndApprovalChecksOnOrderCreation){const r=yield(0,yN.getBalancesAndApprovals)({owner:t,items:g,criterias:[],multicallProvider:this.multicallProvider,operator:T}),i=(0,yN.validateOfferBalancesAndApprovals)({offer:g,criterias:[],balancesAndApprovals:r,throwOnInsufficientBalances:!0,operator:T}),a=(0,mN.getApprovalActions)(i,n,e);R.push(...a)}return{orderComponents:I,approvalActions:R}}))}_getSigner(e){if(this.signer)return this.signer;if(!(this.provider instanceof lN.providers.JsonRpcProvider))throw new Error("Either signer or a JsonRpcProvider must be provided");return this.provider.getSigner(e)}_getOrderTypeFromOrderOptions({allowPartialFills:e,restrictedByZone:t}){return e?t?hN.OrderType.PARTIAL_RESTRICTED:hN.OrderType.PARTIAL_OPEN:t?hN.OrderType.FULL_RESTRICTED:hN.OrderType.FULL_OPEN}_getDomainData(){return uN(this,void 0,void 0,(function*(){const{chainId:e}=yield this.provider.getNetwork();return{name:hN.SEAPORT_CONTRACT_NAME,version:"1.5"===this.config.seaportVersion?hN.SEAPORT_CONTRACT_VERSION_V1_5:hN.SEAPORT_CONTRACT_VERSION_V1_4,chainId:e,verifyingContract:this.contract.address}}))}_getMessageToSign(e){return uN(this,void 0,void 0,(function*(){const t=yield this._getDomainData();return JSON.stringify(dN._TypedDataEncoder.getPayload(t,hN.EIP_712_ORDER_TYPE,e))}))}_getBulkMessageToSign(e){return uN(this,void 0,void 0,(function*(){const t=yield this._getDomainData(),n=(0,gN.getBulkOrderTree)(e),r=n.types,i=n.getDataToSign();return JSON.stringify(dN._TypedDataEncoder.getPayload(t,r,{tree:i}))}))}signOrder(e,t){return uN(this,void 0,void 0,(function*(){const n=this._getSigner(t),r=yield this._getDomainData();let i=yield n._signTypedData(r,hN.EIP_712_ORDER_TYPE,e);return 132===i.length&&(i=lN.ethers.utils.splitSignature(i).compact),i}))}signBulkOrder(e,t){return uN(this,void 0,void 0,(function*(){const n=this._getSigner(t),r=yield this._getDomainData(),i=(0,gN.getBulkOrderTree)(e),a=i.types,o={tree:i.getDataToSign()};let s=yield n._signTypedData(r,a,o);132===s.length&&(s=lN.ethers.utils.splitSignature(s).compact);return e.map(((e,t)=>({parameters:e,signature:i.getEncodedProofAndSignature(t,s)})))}))}cancelOrders(e,t,n){const r=this._getSigner(t);return(0,TN.getTransactionMethods)(this.contract.connect(r),"cancel",[e],n)}bulkCancelOrders(e,t){const n=this._getSigner(e);return(0,TN.getTransactionMethods)(this.contract.connect(n),"incrementCounter",[],t)}validate(e,t,n){const r=this._getSigner(t);return(0,TN.getTransactionMethods)(this.contract.connect(r),"validate",[e],n)}getOrderStatus(e){return this.contract.getOrderStatus(e)}getCounter(e){return this.contract.getCounter(e)}fulfillOrder({order:e,unitsToFill:t,offerCriteria:n=[],considerationCriteria:r=[],tips:i=[],extraData:a="0x",accountAddress:o,conduitKey:s=this.defaultConduitKey,recipientAddress:u=lN.ethers.constants.AddressZero,domain:c,exactApproval:l=!1}){return uN(this,void 0,void 0,(function*(){if(!e.signature)throw new Error("Order is missing signature");const{parameters:d}=e,{offerer:f,offer:p,consideration:h}=d,m=this._getSigner(o),y=yield m.getAddress(),g=this.config.conduitKeyToConduit[d.conduitKey],b=this.config.conduitKeyToConduit[s],[v,w,T,A]=yield Promise.all([(0,yN.getBalancesAndApprovals)({owner:f,items:p,criterias:n,multicallProvider:this.multicallProvider,operator:g}),(0,yN.getBalancesAndApprovals)({owner:y,items:[...p,...h],criterias:[...n,...r],multicallProvider:this.multicallProvider,operator:b}),this.multicallProvider.getBlock("latest"),this.getOrderStatus(this.getOrderHash(d))]),E=T.timestamp,{totalFilled:_,totalSize:I}=A,R=(0,bN.validateAndSanitizeFromOrderStatus)(e,A),C={startTime:R.parameters.startTime,endTime:R.parameters.endTime,currentBlockTimestamp:E,ascendingAmountTimestampBuffer:this.config.ascendingAmountFulfillmentBuffer},k=i.map((e=>Object.assign(Object.assign({},(0,wN.mapInputItemToOfferItem)(e)),{recipient:e.recipient}))),O=u===lN.ethers.constants.AddressZero;return!t&&O&&(0,bN.shouldUseBasicFulfill)(R.parameters,_)?(0,bN.fulfillBasicOrder)({order:R,seaportContract:this.contract,offererBalancesAndApprovals:v,fulfillerBalancesAndApprovals:w,timeBasedItemParams:C,conduitKey:s,offererOperator:g,fulfillerOperator:b,signer:m,tips:k,domain:c},l):(0,bN.fulfillStandardOrder)({order:R,unitsToFill:t,totalFilled:_,totalSize:I.eq(0)?(0,vN.getMaximumSizeForOrder)(R):I,offerCriteria:n,considerationCriteria:r,tips:k,extraData:a,seaportContract:this.contract,offererBalancesAndApprovals:v,fulfillerBalancesAndApprovals:w,timeBasedItemParams:C,conduitKey:s,signer:m,offererOperator:g,fulfillerOperator:b,recipientAddress:u,domain:c},l)}))}fulfillOrders({fulfillOrderDetails:e,accountAddress:t,conduitKey:n=this.defaultConduitKey,recipientAddress:r=lN.ethers.constants.AddressZero,domain:i,exactApproval:a=!1}){return uN(this,void 0,void 0,(function*(){if(e.some((e=>!e.order.signature)))throw new Error("All orders must include signatures");const o=this._getSigner(t),s=yield o.getAddress(),u=e.map((({order:e})=>this.config.conduitKeyToConduit[e.parameters.conduitKey])),c=this.config.conduitKeyToConduit[n],l=e.flatMap((({order:e})=>e.parameters.offer)),d=e.flatMap((({order:e})=>e.parameters.consideration)),f=e.flatMap((({offerCriteria:e=[]})=>e)),p=e.flatMap((({considerationCriteria:e=[]})=>e)),[h,m,y,g]=yield Promise.all([Promise.all(e.map((({order:e,offerCriteria:t=[]},n)=>(0,yN.getBalancesAndApprovals)({owner:e.parameters.offerer,items:e.parameters.offer,criterias:t,operator:u[n],multicallProvider:this.multicallProvider})))),(0,yN.getBalancesAndApprovals)({owner:s,items:[...l,...d],criterias:[...f,...p],operator:c,multicallProvider:this.multicallProvider}),this.multicallProvider.getBlock("latest"),Promise.all(e.map((({order:e})=>this.getOrderStatus(this.getOrderHash(e.parameters)))))]),b=e.map(((e,t)=>{var n,r,i,a,o;return{order:e.order,unitsToFill:e.unitsToFill,orderStatus:g[t],offerCriteria:null!==(n=e.offerCriteria)&&void 0!==n?n:[],considerationCriteria:null!==(r=e.considerationCriteria)&&void 0!==r?r:[],tips:null!==(a=null===(i=e.tips)||void 0===i?void 0:i.map((e=>Object.assign(Object.assign({},(0,wN.mapInputItemToOfferItem)(e)),{recipient:e.recipient}))))&&void 0!==a?a:[],extraData:null!==(o=e.extraData)&&void 0!==o?o:"0x",offererBalancesAndApprovals:h[t],offererOperator:u[t]}}));return(0,bN.fulfillAvailableOrders)({ordersMetadata:b,seaportContract:this.contract,fulfillerBalancesAndApprovals:m,currentBlockTimestamp:y.timestamp,ascendingAmountTimestampBuffer:this.config.ascendingAmountFulfillmentBuffer,fulfillerOperator:c,signer:o,conduitKey:n,recipientAddress:r,domain:i,exactApproval:a})}))}matchOrders({orders:e,fulfillments:t,overrides:n,accountAddress:r,domain:i}){const a=this._getSigner(r);return(0,TN.getTransactionMethods)(this.contract.connect(a),"matchOrders",[e,t,n],i)}setDomain(e,t){const n=this._getSigner(t);return(0,TN.getTransactionMethods)(this.domainRegistry.connect(n),"setDomain",[e])}getNumberOfDomains(e){return uN(this,void 0,void 0,(function*(){return this.domainRegistry.getNumberOfDomains(e)}))}getDomain(e,t){return this.domainRegistry.getDomain(e,t)}getDomains(e,t){return uN(this,void 0,void 0,(function*(){try{if(t)throw Error;return this.domainRegistry.getDomains(e)}catch(t){const n=(yield this.domainRegistry.getNumberOfDomains(e)).toNumber();return Promise.all([...Array(n).keys()].map((t=>this.domainRegistry.getDomain(e,t))))}}))}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Seaport=void 0;const t=jR;Object.defineProperty(e,"Seaport",{enumerable:!0,get:function(){return t.Seaport}})}(qR);class AN{config;constructor(e){this.config=e}}class EN extends Error{url;status;statusText;body;request;constructor(e,t,n){super(n),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}}class _N extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}}class IN{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(e){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise(((t,n)=>{this._resolve=t,this._reject=n;const r=e=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(e)};return Object.defineProperty(r,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(r,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(r,"isCancelled",{get:()=>this._isCancelled}),e((e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(e))}),(e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(e))}),r)}))}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(const e of this._cancelHandlers)e()}catch(e){return void console.warn("Cancellation threw an error",e)}this._cancelHandlers.length=0,this._reject?.(new _N("Request aborted"))}}get isCancelled(){return this._isCancelled}}const RN=e=>null!=e,CN=e=>"string"==typeof e,kN=e=>CN(e)&&""!==e,ON=e=>"object"==typeof e&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.arrayBuffer&&"function"==typeof e.constructor&&"string"==typeof e.constructor.name&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),SN=e=>{const t=[],n=(e,r)=>{RN(r)&&(Array.isArray(r)?r.forEach((t=>{n(e,t)})):"object"==typeof r?Object.entries(r).forEach((([t,r])=>{n(`${e}[${t}]`,r)})):((e,n)=>{t.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(n))}`)})(e,r))};return Object.entries(e).forEach((([e,t])=>{n(e,t)})),t.length>0?`?${t.join("&")}`:""},NN=async(e,t)=>"function"==typeof t?t(e):t,xN=async(e,t,n)=>{const r=await NN(t,e.TOKEN),i=await NN(t,e.USERNAME),a=await NN(t,e.PASSWORD),o=await NN(t,e.HEADERS),s="function"==typeof n?.getHeaders&&n?.getHeaders()||{},u=Object.entries({Accept:"application/json",...o,...t.headers,...s}).filter((([e,t])=>RN(t))).reduce(((e,[t,n])=>({...e,[t]:String(n)})),{});if(kN(r)&&(u.Authorization=`Bearer ${r}`),kN(i)&&kN(a)){const e=(e=>{try{return btoa(e)}catch(t){return Buffer.from(e).toString("base64")}})(`${i}:${a}`);u.Authorization=`Basic ${e}`}return t.body&&(t.mediaType?u["Content-Type"]=t.mediaType:ON(t.body)?u["Content-Type"]=t.body.type||"application/octet-stream":CN(t.body)?u["Content-Type"]="text/plain":t.body instanceof UR||(u["Content-Type"]="application/json")),u},PN=(e,t)=>new IN((async(n,r,i)=>{try{const r=((e,t)=>{const n=e.ENCODE_PATH||encodeURI,r=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,((e,r)=>t.path?.hasOwnProperty(r)?n(String(t.path[r])):e)),i=`${e.BASE}${r}`;return t.query?`${i}${SN(t.query)}`:i})(e,t),o=(e=>{if(e.formData){const t=new UR,n=(e,n)=>{CN(n)||ON(n)?t.append(e,n):t.append(e,JSON.stringify(n))};return Object.entries(e.formData).filter((([e,t])=>RN(t))).forEach((([e,t])=>{Array.isArray(t)?t.forEach((t=>n(e,t))):n(e,t)})),t}})(t),s=(e=>{if(e.body)return e.body})(t),u=await xN(e,t,o);if(!i.isCancelled){const c=await(async(e,t,n,r,i,a,o)=>{const s=Ve.CancelToken.source(),u={url:n,headers:a,data:r??i,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:s.token};o((()=>s.cancel("The user aborted a request.")));try{return await Ve.request(u)}catch(e){const t=e;if(t.response)return t.response;throw e}})(e,t,r,s,o,u,i),l=(e=>{if(204!==e.status)return e.data})(c),d=((e,t)=>{if(t){const n=e.headers[t];if(CN(n))return n}})(c,t.responseHeader),f={url:r,ok:(a=c.status,a>=200&&a<300),status:c.status,statusText:c.statusText,body:d??l};((e,t)=>{const n={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(n)throw new EN(e,t,n);if(!t.ok)throw new EN(e,t,"Generic Error")})(t,f),n(f.body)}}catch(e){r(e)}var a}));class MN extends AN{constructor(e){super(e)}request(e){return PN(this.config,e)}}class BN{httpRequest;constructor(e){this.httpRequest=e}cancelOrders({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:e},body:t,mediaType:"application/json",errors:{400:"Bad Request (400)",401:"Unauthorised Request (401)",404:"The specified resource was not found (404)",429:"Too Many Requests (429)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listListings({chainName:e,status:t,sellItemContractAddress:n,buyItemContractAddress:r,sellItemTokenId:i,fromUpdatedAt:a,pageSize:o,sortBy:s,sortDirection:u,pageCursor:c}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:e},query:{status:t,sell_item_contract_address:n,buy_item_contract_address:r,sell_item_token_id:i,from_updated_at:a,page_size:o,sort_by:s,sort_direction:u,page_cursor:c},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:e},body:t,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getListing({chainName:e,listingId:t}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:e,listing_id:t},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:e},body:t,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:e,accountAddress:t,fromIndexedAt:n,pageSize:r,sortBy:i,sortDirection:a,pageCursor:o}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:e},query:{account_address:t,from_indexed_at:n,page_size:r,sort_by:i,sort_direction:a,page_cursor:o},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:e,tradeId:t}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:e,trade_id:t},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}}class DN{orders;request;constructor(e,t=MN){this.request=new t({BASE:e?.BASE??"https://api.sandbox.immutable.com",VERSION:e?.VERSION??"1.0.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.orders=new BN(this.request)}}var FN,LN,UN,qN,jN,GN,HN,zN,VN;function WN(e){const t=e.buy.map((e=>{if("ERC20"===e.item_type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.amount};if("NATIVE"===e.item_type)return{type:"NATIVE",amount:e.amount};throw new Error("Buy items must be either ERC20 or NATIVE")})),n=e.sell.map((e=>{if("ERC721"===e.item_type)return{type:"ERC721",contractAddress:e.contract_address,tokenId:e.token_id};throw new Error("Sell items must ERC721")}));return{id:e.id,accountAddress:e.account_address,buy:t,sell:n,fees:e.fees.map((e=>({amount:e.amount,recipient:e.recipient,type:e.fee_type}))),chain:e.chain,createdAt:e.created_at,endAt:e.end_at,protocolData:{counter:e.protocol_data.counter,orderType:e.protocol_data.order_type,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},salt:e.salt,signature:e.signature,startAt:e.start_at,status:e.status,updatedAt:e.updated_at}}function KN(e){const t=e.buy.map((e=>{if("ERC20"===e.item_type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.amount};if("NATIVE"===e.item_type)return{type:"NATIVE",amount:e.amount};throw new Error("Buy items must be either ERC20 or NATIVE")})),n=e.sell.map((e=>{if("ERC721"===e.item_type)return{type:"ERC721",contractAddress:e.contract_address,tokenId:e.token_id};throw new Error("Sell items must ERC721")}));return{id:e.id,orderId:e.order_id,buy:t,sell:n,buyerFees:e.buyer_fees.map((e=>({amount:e.amount,recipient:e.recipient,type:e.fee_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 XN(e){return{nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}!function(e){var t;(t=e.cancellation_type||(e.cancellation_type={})).ON_CHAIN="ON_CHAIN",t.OFF_CHAIN="OFF_CHAIN"}(FN||(FN={})),function(e){(e.reason_code||(e.reason_code={})).FILLED="FILLED"}(LN||(LN={})),function(e){var t;(t=e.fee_type||(e.fee_type={})).ROYALTY="ROYALTY",t.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",t.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",t.PROTOCOL="PROTOCOL"}(UN||(UN={})),function(e){e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.FILLED="FILLED",e.EXPIRED="EXPIRED",e.CANCELLED="CANCELLED"}(qN||(qN={})),function(e){(e.order_type||(e.order_type={})).FULL_RESTRICTED="FULL_RESTRICTED"}(jN||(jN={})),function(e){e.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",e.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",e.PROTOCOL="PROTOCOL",e.ROYALTY="ROYALTY"}(GN||(GN={})),function(e){e.APPROVAL="APPROVAL",e.FULFILL_ORDER="FULFILL_ORDER",e.CANCEL="CANCEL"}(HN||(HN={})),function(e){e.CREATE_LISTING="CREATE_LISTING",e.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION"}(zN||(zN={})),function(e){e.TRANSACTION="TRANSACTION",e.SIGNABLE="SIGNABLE"}(VN||(VN={}));const JN="1.5",YN={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 QN,ZN,$N,ex;function tx(e,t){return async()=>{const n=await e.buildTransaction();return n.gasLimit=await e.estimateGas(),n.gasLimit=n.gasLimit.add(n.gasLimit.div(5)),n.chainId=t,n}}!function(e){e[e.FULL_OPEN=0]="FULL_OPEN",e[e.PARTIAL_OPEN=1]="PARTIAL_OPEN",e[e.FULL_RESTRICTED=2]="FULL_RESTRICTED",e[e.PARTIAL_RESTRICTED=3]="PARTIAL_RESTRICTED"}(QN||(QN={})),function(e){e[e.NATIVE=0]="NATIVE",e[e.ERC20=1]="ERC20",e[e.ERC721=2]="ERC721",e[e.ERC1155=3]="ERC1155",e[e.ERC721_WITH_CRITERIA=4]="ERC721_WITH_CRITERIA",e[e.ERC1155_WITH_CRITERIA=5]="ERC1155_WITH_CRITERIA"}(ZN||(ZN={})),function(e){e[e.OFFER=0]="OFFER",e[e.CONSIDERATION=1]="CONSIDERATION"}($N||($N={})),function(e){e[e.ETH_TO_ERC721=0]="ETH_TO_ERC721",e[e.ETH_TO_ERC1155=1]="ETH_TO_ERC1155",e[e.ERC20_TO_ERC721=2]="ERC20_TO_ERC721",e[e.ERC20_TO_ERC1155=3]="ERC20_TO_ERC1155",e[e.ERC721_TO_ERC20=4]="ERC721_TO_ERC20",e[e.ERC1155_TO_ERC20=5]="ERC1155_TO_ERC20"}(ex||(ex={}));class nx{seaportLibFactory;provider;seaportContractAddress;zoneContractAddress;constructor(e,t,n,r){this.seaportLibFactory=e,this.provider=t,this.seaportContractAddress=n,this.zoneContractAddress=r}async prepareSeaportOrder(e,t,n,r,i){const{actions:a}=await this.createSeaportOrder(e,t,n,r,i),o=[],s=a.find((e=>"approval"===e.type));s&&o.push({type:VN.TRANSACTION,purpose:HN.APPROVAL,buildTransaction:tx(s.transactionMethods,(await this.provider.getNetwork()).chainId)});const u=a.find((e=>"create"===e.type));if(!u)throw new Error("No create order action found");const c=function(e){const t=JSON.parse(e).message;return t.salt=tr.from(t.salt).toHexString(),t}(await u.getMessageToSign());return o.push({type:VN.SIGNABLE,purpose:zN.CREATE_LISTING,message:await this.getTypedDataFromOrderComponents(c)}),{actions:o,orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}}async fulfillOrder(e,t,n){const{orderComponents:r,tips:i}=this.mapImmutableOrderToSeaportOrderComponents(e),a=this.getSeaportLib(e),{actions:o}=await a.fulfillOrders({accountAddress:t,fulfillOrderDetails:[{order:{parameters:r,signature:e.signature},extraData:n,tips:i}]}),s=[],u=o.find((e=>"approval"===e.type));u&&s.push({type:VN.TRANSACTION,buildTransaction:tx(u.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:HN.APPROVAL});const c=o.find((e=>"exchange"===e.type));if(!c)throw new Error("No exchange action found");return s.push({type:VN.TRANSACTION,buildTransaction:tx(c.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:HN.FULFILL_ORDER}),{actions:s,expiration:nx.getExpirationISOTimeFromExtraData(n),order:WN(e)}}async fulfillBulkOrders(e,t){const n=e.map((e=>{const{orderComponents:t,tips:n}=this.mapImmutableOrderToSeaportOrderComponents(e.order);return{order:{parameters:t,signature:e.order.signature},extraData:e.extra_data,tips:n}})),{actions:r}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:n,accountAddress:t}),i=[],a=r.find((e=>"approval"===e.type));a&&i.push({type:VN.TRANSACTION,buildTransaction:tx(a.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:HN.APPROVAL});const o=r.find((e=>"exchange"===e.type));if(!o)throw new Error("No exchange action found");return i.push({type:VN.TRANSACTION,buildTransaction:tx(o.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:HN.FULFILL_ORDER}),{actions:i,expiration:n.map((e=>nx.getExpirationISOTimeFromExtraData(e.extraData))).reduce(((e,t)=>new Date(e)<new Date(t)?e:t))}}async cancelOrders(e,t){const n=e.map((e=>this.mapImmutableOrderToSeaportOrderComponents(e).orderComponents)),r=this.getSeaportLib(e[0]),i=await r.cancelOrders(n,t);return{type:VN.TRANSACTION,buildTransaction:tx(i,(await this.provider.getNetwork()).chainId),purpose:HN.CANCEL}}mapImmutableOrderToSeaportOrderComponents(e){return function(e,t,n){const r=e.buy.map((t=>{switch(t.item_type){case"NATIVE":return{startAmount:t.amount,endAmount:t.amount,itemType:ZN.NATIVE,recipient:e.account_address,token:ji,identifierOrCriteria:"0"};case"ERC20":return{startAmount:t.amount,endAmount:t.amount,itemType:ZN.ERC20,recipient:e.account_address,token:t.contract_address||ji,identifierOrCriteria:"0"};default:return{startAmount:"1",endAmount:"1",itemType:ZN.ERC721,recipient:e.account_address,token:t.contract_address||ji,identifierOrCriteria:"0"}}})),i=e.fees.map((t=>({amount:t.amount,itemType:"ERC20"===e.buy[0].item_type?ZN.ERC20:ZN.NATIVE,recipient:t.recipient,token:"ERC20"===e.buy[0].item_type?e.buy[0].contract_address:ji,identifierOrCriteria:"0"})));return{orderComponents:{conduitKey:Yi,consideration:[...r],offer:e.sell.map((e=>{const t=e;return{startAmount:"1",endAmount:"1",itemType:ZN.ERC721,token:t.contract_address,identifierOrCriteria:t.token_id}})),counter:t,endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),salt:e.salt,offerer:e.account_address,zone:n,totalOriginalConsiderationItems:r.length,orderType:QN.FULL_RESTRICTED,zoneHash:Yi},tips:i}}(e,e.protocol_data.counter,this.zoneContractAddress)}createSeaportOrder(e,t,n,r,i){return this.getSeaportLib().createOrder({allowPartialFills:!1,offer:[{itemType:ZN.ERC721,token:t.contractAddress,identifier:t.tokenId}],consideration:[{token:"ERC20"===n.type?n.contractAddress:void 0,amount:n.amount,recipient:e}],startTime:(r.getTime()/1e3).toFixed(0),endTime:(i.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},e)}async getTypedDataFromOrderComponents(e){const{chainId:t}=await this.provider.getNetwork();return{domain:{name:"ImmutableSeaport",version:JN,chainId:t,verifyingContract:this.seaportContractAddress},types:YN,value:e}}getSeaportLib(e){const t=e?.protocol_data?.seaport_address??this.seaportContractAddress,n=JN;return this.seaportLibFactory.create(n,t)}static getExpirationISOTimeFromExtraData(e){const t=e.slice(44,60),n=parseInt(t,16);return new Date(1e3*n).toISOString()}}class rx{orderbookService;chainName;seaportAddress;constructor(e,t,n){this.orderbookService=e,this.chainName=t,this.seaportAddress=n}async fulfillmentData(e){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:e})}async getListing(e){return this.orderbookService.getListing({chainName:this.chainName,listingId:e})}async getTrade(e){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:e})}async listListings(e){return this.orderbookService.listListings({chainName:this.chainName,...e})}async listTrades(e){return this.orderbookService.listTrades({chainName:this.chainName,...e})}async cancelOrders(e,t,n){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:t,orders:e,signature:n}})}async createListing({orderHash:e,orderComponents:t,orderSignature:n,makerFees:r}){if(1!==t.offer.length)throw new Error("Only one item can be listed at a time");if(Number(t.offer[0].itemType)!==ZN.ERC721)throw new Error("Only ERC721 tokens can be listed");const i=[...t.consideration.map((e=>e.itemType))];if(!(1===new Set(i).size))throw new Error("All consideration items must be of the same type");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{order_hash:e,account_address:t.offerer,buy:[{item_type:Number(t.consideration[0].itemType)===ZN.NATIVE?"NATIVE":"ERC20",amount:t.consideration[0].startAmount,contract_address:t.consideration[0].token}],fees:r.map((e=>({amount:e.amount,fee_type:GN.MAKER_ECOSYSTEM,recipient:e.recipient}))),end_at:new Date(parseInt(`${t.endTime.toString()}000`,10)).toISOString(),protocol_data:{order_type:jN.order_type.FULL_RESTRICTED,zone_address:t.zone,seaport_address:this.seaportAddress,seaport_version:JN,counter:t.counter.toString()},salt:t.salt,sell:[{contract_address:t.offer[0].token,token_id:t.offer[0].identifierOrCriteria,item_type:"ERC721"}],signature:n,start_at:new Date(parseInt(`${t.startTime.toString()}000`,10)).toISOString()}})}}class ix{chainName;seaportAddress;orderbookClient;constructor(e,t,n){this.chainName=t,this.seaportAddress=n,this.orderbookClient=new DN({BASE:e})}create(){return new rx(this.orderbookClient.orders,this.chainName,this.seaportAddress)}}class ax{defaultSeaportContractAddress;provider;constructor(e,t){this.defaultSeaportContractAddress=e,this.provider=t}create(e,t){const n=e??JN,r=t??this.defaultSeaportContractAddress;return new qR.Seaport(this.provider,{seaportVersion:n,balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}}class ox{apiClient;seaport;orderbookConfig;constructor(e){const t={...function(e){switch(e){case st.SANDBOX:return{seaportContractAddress:"0x2CFA8f64e1B49A2DF28532D1D30Cda45117cF778",zoneContractAddress:"0x1Bb4Fb11Ba021Bd0104F0Ee8E5F5c728Bc83d7F1",apiEndpoint:"https://api.sandbox.immutable.com",chainName:"imtbl-zkevm-testnet",provider:new up("https://rpc.testnet.immutable.com")};case st.PRODUCTION:return{seaportContractAddress:"",zoneContractAddress:"",apiEndpoint:"https://api.immutable.com",chainName:"imtbl-zkevm-mainnet",provider:new up("https://rpc.immutable.com")};default:return null}}(e.baseConfig.environment),...e.overrides};if(!t)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=t;const{apiEndpoint:n,chainName:r}=this.orderbookConfig;if(!n)throw new Error("API endpoint must be provided");this.apiClient=new ix(n,r,this.orderbookConfig.seaportContractAddress).create();const i=new ax(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new nx(i,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress)}config(){return this.orderbookConfig}async getListing(e){return{result:WN((await this.apiClient.getListing(e)).result)}}async getTrade(e){return{result:KN((await this.apiClient.getTrade(e)).result)}}async listListings(e){const t=await this.apiClient.listListings(e);return{page:XN(t.page),result:t.result.map(WN)}}async listTrades(e){const t=await this.apiClient.listTrades(e);return{page:XN(t.page),result:t.result.map(KN)}}async prepareListing({makerAddress:e,sell:t,buy:n,orderExpiry:r}){return this.seaport.prepareSeaportOrder(e,t,n,new Date,r||new Date(Date.now()+63072e6))}async createListing(e){return{result:WN((await this.apiClient.createListing({...e})).result)}}async fulfillOrder(e,t,n){const r=await this.apiClient.fulfillmentData([{order_id:e,fees:n.map((e=>({amount:e.amount,fee_type:GN.TAKER_ECOSYSTEM,recipient:e.recipient})))}]);if(r.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment date: ${r.result.unfulfillable_orders[0].reason}`);if(1!==r.result.fulfillable_orders?.length)throw new Error("unexpected fulfillable order result length");const i=r.result.fulfillable_orders[0].extra_data,a=r.result.fulfillable_orders[0].order;if(a.status.name!==qN.ACTIVE)throw new Error(`Cannot fulfil order that is not active. Current status: ${a.status}`);return this.seaport.fulfillOrder(a,t,i)}async fulfillBulkOrders(e,t){const n=await this.apiClient.fulfillmentData(e.map((e=>({order_id:e.listingId,fees:e.takerFees.map((e=>({amount:e.amount,fee_type:GN.TAKER_ECOSYSTEM,recipient:e.recipient})))}))));try{return{...await this.seaport.fulfillBulkOrders(n.result.fulfillable_orders,t),fulfillableOrders:n.result.fulfillable_orders.map((e=>WN(e.order))),unfulfillableOrders:n.result.unfulfillable_orders.map((e=>({orderId:e.order_id,reason:e.reason}))),sufficientBalance:!0}}catch(e){if(String(e).includes("The fulfiller does not have the balances needed to fulfill."))return{fulfillableOrders:n.result.fulfillable_orders.map((e=>WN(e.order))),unfulfillableOrders:n.result.unfulfillable_orders.map((e=>({orderId:e.order_id,reason:e.reason}))),sufficientBalance:!1};throw e}}async prepareOrderCancellations(e){const t={name:"imtbl-order-book",chainId:(await this.orderbookConfig.provider.getNetwork()).chainId,verifyingContract:this.orderbookConfig.seaportContractAddress},n={orders:e.map((e=>({id:e})))};return{signableAction:{purpose:zN.OFF_CHAIN_CANCELLATION,type:VN.SIGNABLE,message:{domain:t,types:{CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},value:n}}}}async cancelOrders(e,t,n){return this.apiClient.cancelOrders(e,t,n)}async cancelOrdersOnChain(e,t){const n=await Promise.all(e.map((e=>this.apiClient.getListing(e))));for(const e of n){if(e.result.status.name!==qN.ACTIVE&&e.result.status.name!==qN.INACTIVE&&e.result.status.name!==qN.PENDING)throw new Error(`Cannot cancel order with status ${e.result.status}`);if(e.result.account_address!==t.toLowerCase())throw new Error(`Only account ${e.result.account_address} can cancel order ${e.result.id}`)}const r=n.map((e=>e.result)),i=r.map((e=>e.protocol_data.seaport_address));if(1!==new Set(...[i]).size)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return{cancellationAction:await this.seaport.cancelOrders(r,t)}}}const sx=4e5,ux="https://api.sandbox.immutable.com".replace(/\/+$/,"");class cx{basePath;axios;configuration;constructor(e,t=ux,n=Ve){this.basePath=t,this.axios=n,e&&(this.configuration=e,this.basePath=e.basePath||this.basePath)}}class lx extends Error{field;constructor(e,t){super(t),this.field=e,this.name="RequiredError"}}const dx="https://example.com",fx=function(e,t,n){if(null==n)throw new lx(t,`Required parameter ${t} was null or undefined when calling ${e}.`)},px=async function(e,t,n){if(n&&n.apiKey){const r="function"==typeof n.apiKey?await n.apiKey(t):await n.apiKey;e[t]=r}},hx=async function(e,t){if(t&&t.accessToken){const n="function"==typeof t.accessToken?await t.accessToken():await t.accessToken;e.Authorization="Bearer "+n}};function mx(e,t,n=""){null!=t&&("object"==typeof t?Array.isArray(t)?t.forEach((t=>mx(e,t,n))):Object.keys(t).forEach((r=>mx(e,t[r],`${n}${""!==n?".":""}${r}`))):e.has(n)?e.append(n,t):e.set(n,t))}const yx=function(e,...t){const n=new URLSearchParams(e.search);mx(n,t),e.search=n.toString()},gx=function(e,t,n){const r="string"!=typeof e;return(r&&n&&n.isJsonMime?n.isJsonMime(t.headers["Content-Type"]):r)?JSON.stringify(void 0!==e?e:{}):e||""},bx=function(e){return e.pathname+e.search+e.hash},vx=function(e,t,n,r){return(i=t,a=n)=>{const o={...e.options,url:(r?.basePath||i.defaults.baseURL||a)+e.url};return i.request(o)}},wx=function(e){return{getActivity:async(t,n,r={})=>{fx("getActivity","chainName",t),fx("getActivity","activityId",n);const i="/v1/chains/{chain_name}/activities/{activity_id}".replace("{chain_name}",encodeURIComponent(String(t))).replace("{activity_id}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};yx(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:bx(a),options:s}},listActivities:async(t,n,r,i,a,o,s,u,c,l,d={})=>{fx("listActivities","chainName",t);const f="/v1/chains/{chain_name}/activities".replace("{chain_name}",encodeURIComponent(String(t))),p=new URL(f,dx);let h;e&&(h=e.baseOptions);const m={method:"GET",...h,...d},y={};void 0!==n&&(y.contract_address=n),void 0!==r&&(y.token_id=r),void 0!==i&&(y.account_address=i),void 0!==a&&(y.activity_type=a),void 0!==o&&(y.from_indexed_at=o instanceof Date?o.toISOString():o),void 0!==s&&(y.to_indexed_at=s instanceof Date?s.toISOString():s),void 0!==u&&(y.transaction_hash=u),void 0!==c&&(y.page_cursor=c),void 0!==l&&(y.page_size=l),yx(p,y);let g=h&&h.headers?h.headers:{};return m.headers={...g,...d.headers},{url:bx(p),options:m}}}},Tx=function(e){const t=wx(e);return{async getActivity(n,r,i){const a=await t.getActivity(n,r,i);return vx(a,Ve,ux,e)},async listActivities(n,r,i,a,o,s,u,c,l,d,f){const p=await t.listActivities(n,r,i,a,o,s,u,c,l,d,f);return vx(p,Ve,ux,e)}}};const Ax=function(e){return{listChains:async(t,n,r={})=>{const i=new URL("/v1/chains",dx);let a;e&&(a=e.baseOptions);const o={method:"GET",...a,...r},s={};void 0!==t&&(s.page_cursor=t),void 0!==n&&(s.page_size=n),yx(i,s);let u=a&&a.headers?a.headers:{};return o.headers={...u,...r.headers},{url:bx(i),options:o}}}},Ex=function(e){const t=Ax(e);return{async listChains(n,r,i){const a=await t.listChains(n,r,i);return vx(a,Ve,ux,e)}}};const _x=function(e){return{getCollection:async(t,n,r={})=>{fx("getCollection","contractAddress",t),fx("getCollection","chainName",n);const i="/v1/chains/{chain_name}/collections/{contract_address}".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};yx(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:bx(a),options:s}},listCollections:async(t,n,r,i,a,o={})=>{fx("listCollections","chainName",t);const s="/v1/chains/{chain_name}/collections".replace("{chain_name}",encodeURIComponent(String(t))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};n&&(d.contract_address=n),void 0!==r&&(d.from_updated_at=r instanceof Date?r.toISOString():r),void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}},listCollectionsByNFTOwner:async(t,n,r,i,a={})=>{fx("listCollectionsByNFTOwner","accountAddress",t),fx("listCollectionsByNFTOwner","chainName",n);const o="/v1/chains/{chain_name}/accounts/{account_address}/collections".replace("{account_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),s=new URL(o,dx);let u;e&&(u=e.baseOptions);const c={method:"GET",...u,...a},l={};void 0!==r&&(l.page_cursor=r),void 0!==i&&(l.page_size=i),yx(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:bx(s),options:c}},refreshCollectionMetadata:async(t,n,r,i={})=>{fx("refreshCollectionMetadata","contractAddress",t),fx("refreshCollectionMetadata","chainName",n),fx("refreshCollectionMetadata","refreshCollectionMetadataRequest",r);const a="/v1/chains/{chain_name}/collections/{contract_address}/refresh-metadata".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),o=new URL(a,dx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await px(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",yx(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=gx(r,u,e),{url:bx(o),options:u}}}},Ix=function(e){const t=_x(e);return{async getCollection(n,r,i){const a=await t.getCollection(n,r,i);return vx(a,Ve,ux,e)},async listCollections(n,r,i,a,o,s){const u=await t.listCollections(n,r,i,a,o,s);return vx(u,Ve,ux,e)},async listCollectionsByNFTOwner(n,r,i,a,o){const s=await t.listCollectionsByNFTOwner(n,r,i,a,o);return vx(s,Ve,ux,e)},async refreshCollectionMetadata(n,r,i,a){const o=await t.refreshCollectionMetadata(n,r,i,a);return vx(o,Ve,ux,e)}}};const Rx=function(e){return{getMetadata:async(t,n,r,i={})=>{fx("getMetadata","chainName",t),fx("getMetadata","contractAddress",n),fx("getMetadata","metadataId",r);const a="/v1/chains/{chain_name}/collections/{contract_address}/metadata/{metadata_id}".replace("{chain_name}",encodeURIComponent(String(t))).replace("{contract_address}",encodeURIComponent(String(n))).replace("{metadata_id}",encodeURIComponent(String(r))),o=new URL(a,dx);let s;e&&(s=e.baseOptions);const u={method:"GET",...s,...i};yx(o,{});let c=s&&s.headers?s.headers:{};return u.headers={...c,...i.headers},{url:bx(o),options:u}},listMetadata:async(t,n,r,i,a,o={})=>{fx("listMetadata","chainName",t),fx("listMetadata","contractAddress",n);const s="/v1/chains/{chain_name}/collections/{contract_address}/metadata".replace("{chain_name}",encodeURIComponent(String(t))).replace("{contract_address}",encodeURIComponent(String(n))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};void 0!==r&&(d.from_updated_at=r instanceof Date?r.toISOString():r),void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}},refreshMetadataByID:async(t,n,r,i={})=>{fx("refreshMetadataByID","chainName",t),fx("refreshMetadataByID","contractAddress",n),fx("refreshMetadataByID","refreshMetadataByIDRequest",r);const a="/v1/chains/{chain_name}/collections/{contract_address}/metadata/refresh-metadata".replace("{chain_name}",encodeURIComponent(String(t))).replace("{contract_address}",encodeURIComponent(String(n))),o=new URL(a,dx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await px(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",yx(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=gx(r,u,e),{url:bx(o),options:u}},refreshNFTMetadataByTokenID:async(t,n,r,i={})=>{fx("refreshNFTMetadataByTokenID","contractAddress",t),fx("refreshNFTMetadataByTokenID","chainName",n),fx("refreshNFTMetadataByTokenID","refreshNFTMetadataByTokenIDRequest",r);const a="/v1/chains/{chain_name}/collections/{contract_address}/nfts/refresh-metadata".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),o=new URL(a,dx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await px(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",yx(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=gx(r,u,e),{url:bx(o),options:u}}}},Cx=function(e){const t=Rx(e);return{async getMetadata(n,r,i,a){const o=await t.getMetadata(n,r,i,a);return vx(o,Ve,ux,e)},async listMetadata(n,r,i,a,o,s){const u=await t.listMetadata(n,r,i,a,o,s);return vx(u,Ve,ux,e)},async refreshMetadataByID(n,r,i,a){const o=await t.refreshMetadataByID(n,r,i,a);return vx(o,Ve,ux,e)},async refreshNFTMetadataByTokenID(n,r,i,a){const o=await t.refreshNFTMetadataByTokenID(n,r,i,a);return vx(o,Ve,ux,e)}}};const kx=function(e){return{listNFTOwners:async(t,n,r,i,a,o={})=>{fx("listNFTOwners","contractAddress",t),fx("listNFTOwners","tokenId",n),fx("listNFTOwners","chainName",r);const s="/v1/chains/{chain_name}/collections/{contract_address}/nfts/{token_id}/owners".replace("{contract_address}",encodeURIComponent(String(t))).replace("{token_id}",encodeURIComponent(String(n))).replace("{chain_name}",encodeURIComponent(String(r))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}},listOwnersByContractAddress:async(t,n,r,i,a,o={})=>{fx("listOwnersByContractAddress","contractAddress",t),fx("listOwnersByContractAddress","chainName",n);const s="/v1/chains/{chain_name}/collections/{contract_address}/owners".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};void 0!==r&&(d.from_updated_at=r instanceof Date?r.toISOString():r),void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}}}},Ox=function(e){const t=kx(e);return{async listNFTOwners(n,r,i,a,o,s){const u=await t.listNFTOwners(n,r,i,a,o,s);return vx(u,Ve,ux,e)},async listOwnersByContractAddress(n,r,i,a,o,s){const u=await t.listOwnersByContractAddress(n,r,i,a,o,s);return vx(u,Ve,ux,e)}}};const Sx=function(e){return{getNFT:async(t,n,r,i={})=>{fx("getNFT","contractAddress",t),fx("getNFT","tokenId",n),fx("getNFT","chainName",r);const a="/v1/chains/{chain_name}/collections/{contract_address}/nfts/{token_id}".replace("{contract_address}",encodeURIComponent(String(t))).replace("{token_id}",encodeURIComponent(String(n))).replace("{chain_name}",encodeURIComponent(String(r))),o=new URL(a,dx);let s;e&&(s=e.baseOptions);const u={method:"GET",...s,...i};yx(o,{});let c=s&&s.headers?s.headers:{};return u.headers={...c,...i.headers},{url:bx(o),options:u}},listAllNFTOwners:async(t,n,r,i,a={})=>{fx("listAllNFTOwners","chainName",t),fx("listAllNFTOwners","fromUpdatedAt",n);const o="/v1/chains/{chain_name}/nft-owners".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,dx);let u;e&&(u=e.baseOptions);const c={method:"GET",...u,...a},l={};void 0!==n&&(l.from_updated_at=n instanceof Date?n.toISOString():n),void 0!==r&&(l.page_cursor=r),void 0!==i&&(l.page_size=i),yx(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:bx(s),options:c}},listAllNFTs:async(t,n,r,i,a={})=>{fx("listAllNFTs","chainName",t);const o="/v1/chains/{chain_name}/nfts".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,dx);let u;e&&(u=e.baseOptions);const c={method:"GET",...u,...a},l={};void 0!==n&&(l.from_updated_at=n instanceof Date?n.toISOString():n),void 0!==r&&(l.page_cursor=r),void 0!==i&&(l.page_size=i),yx(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:bx(s),options:c}},listNFTs:async(t,n,r,i,a,o={})=>{fx("listNFTs","contractAddress",t),fx("listNFTs","chainName",n);const s="/v1/chains/{chain_name}/collections/{contract_address}/nfts".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};void 0!==r&&(d.from_updated_at=r instanceof Date?r.toISOString():r),void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}},listNFTsByAccountAddress:async(t,n,r,i,a,o={})=>{fx("listNFTsByAccountAddress","accountAddress",t),fx("listNFTsByAccountAddress","chainName",n);const s="/v1/chains/{chain_name}/accounts/{account_address}/nfts".replace("{account_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};void 0!==r&&(d.contract_address=r),void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}}}},Nx=function(e){const t=Sx(e);return{async getNFT(n,r,i,a){const o=await t.getNFT(n,r,i,a);return vx(o,Ve,ux,e)},async listAllNFTOwners(n,r,i,a,o){const s=await t.listAllNFTOwners(n,r,i,a,o);return vx(s,Ve,ux,e)},async listAllNFTs(n,r,i,a,o){const s=await t.listAllNFTs(n,r,i,a,o);return vx(s,Ve,ux,e)},async listNFTs(n,r,i,a,o,s){const u=await t.listNFTs(n,r,i,a,o,s);return vx(u,Ve,ux,e)},async listNFTsByAccountAddress(n,r,i,a,o,s){const u=await t.listNFTsByAccountAddress(n,r,i,a,o,s);return vx(u,Ve,ux,e)}}};const xx=function(e){return{cancelOrders:async(t,n,r={})=>{fx("cancelOrders","chainName",t),fx("cancelOrders","cancelOrdersRequestBody",n);const i="/v1/chains/{chain_name}/orders/cancel".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",yx(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=gx(n,s,e),{url:bx(a),options:s}},createListing:async(t,n,r={})=>{fx("createListing","chainName",t),fx("createListing","createListingRequestBody",n);const i="/v1/chains/{chain_name}/orders/listings".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",yx(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=gx(n,s,e),{url:bx(a),options:s}},fulfillmentData:async(t,n,r={})=>{fx("fulfillmentData","chainName",t),fx("fulfillmentData","fulfillmentDataRequest",n);const i="/v1/chains/{chain_name}/orders/fulfillment-data".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",yx(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=gx(n,s,e),{url:bx(a),options:s}},getListing:async(t,n,r={})=>{fx("getListing","chainName",t),fx("getListing","listingId",n);const i="/v1/chains/{chain_name}/orders/listings/{listing_id}".replace("{chain_name}",encodeURIComponent(String(t))).replace("{listing_id}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};yx(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:bx(a),options:s}},getTrade:async(t,n,r={})=>{fx("getTrade","chainName",t),fx("getTrade","tradeId",n);const i="/v1/chains/{chain_name}/trades/{trade_id}".replace("{chain_name}",encodeURIComponent(String(t))).replace("{trade_id}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};yx(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:bx(a),options:s}},listListings:async(t,n,r,i,a,o,s,u,c,l={})=>{fx("listListings","chainName",t);const d="/v1/chains/{chain_name}/orders/listings".replace("{chain_name}",encodeURIComponent(String(t))),f=new URL(d,dx);let p;e&&(p=e.baseOptions);const h={method:"GET",...p,...l},m={};void 0!==n&&(m.status=n),void 0!==r&&(m.sell_item_contract_address=r),void 0!==i&&(m.buy_item_contract_address=i),void 0!==a&&(m.sell_item_token_id=a),void 0!==o&&(m.page_size=o),void 0!==s&&(m.sort_by=s),void 0!==u&&(m.sort_direction=u),void 0!==c&&(m.page_cursor=c),yx(f,m);let y=p&&p.headers?p.headers:{};return h.headers={...y,...l.headers},{url:bx(f),options:h}},listTrades:async(t,n,r,i,a,o,s={})=>{fx("listTrades","chainName",t);const u="/v1/chains/{chain_name}/trades".replace("{chain_name}",encodeURIComponent(String(t))),c=new URL(u,dx);let l;e&&(l=e.baseOptions);const d={method:"GET",...l,...s},f={};void 0!==n&&(f.account_address=n),void 0!==r&&(f.page_size=r),void 0!==i&&(f.sort_by=i),void 0!==a&&(f.sort_direction=a),void 0!==o&&(f.page_cursor=o),yx(c,f);let p=l&&l.headers?l.headers:{};return d.headers={...p,...s.headers},{url:bx(c),options:d}}}},Px=function(e){const t=xx(e);return{async cancelOrders(n,r,i){const a=await t.cancelOrders(n,r,i);return vx(a,Ve,ux,e)},async createListing(n,r,i){const a=await t.createListing(n,r,i);return vx(a,Ve,ux,e)},async fulfillmentData(n,r,i){const a=await t.fulfillmentData(n,r,i);return vx(a,Ve,ux,e)},async getListing(n,r,i){const a=await t.getListing(n,r,i);return vx(a,Ve,ux,e)},async getTrade(n,r,i){const a=await t.getTrade(n,r,i);return vx(a,Ve,ux,e)},async listListings(n,r,i,a,o,s,u,c,l,d){const f=await t.listListings(n,r,i,a,o,s,u,c,l,d);return vx(f,Ve,ux,e)},async listTrades(n,r,i,a,o,s,u){const c=await t.listTrades(n,r,i,a,o,s,u);return vx(c,Ve,ux,e)}}};const Mx=function(e){return{createCounterfactualAddress:async(t,n,r={})=>{fx("createCounterfactualAddress","chainName",t),fx("createCounterfactualAddress","createCounterfactualAddressRequest",n);const i="/v1/chains/{chain_name}/passport/counterfactual-address".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};await hx(u,e),u["Content-Type"]="application/json",yx(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=gx(n,s,e),{url:bx(a),options:s}},createCounterfactualAddressDeprecated:async(t,n={})=>{fx("createCounterfactualAddressDeprecated","createCounterfactualAddressRequestDeprecated",t);const r=new URL("/passport-mr/v1/counterfactual-address",dx);let i;e&&(i=e.baseOptions);const a={method:"POST",...i,...n},o={};await hx(o,e),o["Content-Type"]="application/json",yx(r,{});let s=i&&i.headers?i.headers:{};return a.headers={...o,...s,...n.headers},a.data=gx(t,a,e),{url:bx(r),options:a}},getLinkedAddresses:async(t,n,r={})=>{fx("getLinkedAddresses","userId",t),fx("getLinkedAddresses","chainName",n);const i="/v1/chains/{chain_name}/passport/users/{user_id}/linked-addresses".replace("{user_id}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r},u={};await hx(u,e),yx(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},{url:bx(a),options:s}},getLinkedAddressesDeprecated:async(t,n={})=>{fx("getLinkedAddressesDeprecated","userId",t);const r="/passport-mr/v1/users/{userId}/linked-addresses".replace("{userId}",encodeURIComponent(String(t))),i=new URL(r,dx);let a;e&&(a=e.baseOptions);const o={method:"GET",...a,...n},s={};await hx(s,e),yx(i,{});let u=a&&a.headers?a.headers:{};return o.headers={...s,...u,...n.headers},{url:bx(i),options:o}}}},Bx=function(e){const t=Mx(e);return{async createCounterfactualAddress(n,r,i){const a=await t.createCounterfactualAddress(n,r,i);return vx(a,Ve,ux,e)},async createCounterfactualAddressDeprecated(n,r){const i=await t.createCounterfactualAddressDeprecated(n,r);return vx(i,Ve,ux,e)},async getLinkedAddresses(n,r,i){const a=await t.getLinkedAddresses(n,r,i);return vx(a,Ve,ux,e)},async getLinkedAddressesDeprecated(n,r){const i=await t.getLinkedAddressesDeprecated(n,r);return vx(i,Ve,ux,e)}}};const Dx=function(e){return{getERC20Token:async(t,n,r={})=>{fx("getERC20Token","contractAddress",t),fx("getERC20Token","chainName",n);const i="/v1/chains/{chain_name}/tokens/{contract_address}".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};yx(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:bx(a),options:s}},listERC20Tokens:async(t,n,r,i,a={})=>{fx("listERC20Tokens","chainName",t);const o="/v1/chains/{chain_name}/tokens".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,dx);let u;e&&(u=e.baseOptions);const c={method:"GET",...u,...a},l={};void 0!==n&&(l.from_updated_at=n instanceof Date?n.toISOString():n),void 0!==r&&(l.page_cursor=r),void 0!==i&&(l.page_size=i),yx(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:bx(s),options:c}}}},Fx=function(e){const t=Dx(e);return{async getERC20Token(n,r,i){const a=await t.getERC20Token(n,r,i);return vx(a,Ve,ux,e)},async listERC20Tokens(n,r,i,a,o){const s=await t.listERC20Tokens(n,r,i,a,o);return vx(s,Ve,ux,e)}}};var Lx=Object.freeze({__proto__:null,ActiveOrderStatusNameEnum:{Active:"ACTIVE"},ActivitiesApi:class extends cx{getActivity(e,t){return Tx(this.configuration).getActivity(e.chainName,e.activityId,t).then((e=>e(this.axios,this.basePath)))}listActivities(e,t){return Tx(this.configuration).listActivities(e.chainName,e.contractAddress,e.tokenId,e.accountAddress,e.activityType,e.fromIndexedAt,e.toIndexedAt,e.transactionHash,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},ActivitiesApiAxiosParamCreator:wx,ActivitiesApiFactory:function(e,t,n){const r=Tx(e);return{getActivity:(e,i)=>r.getActivity(e.chainName,e.activityId,i).then((e=>e(n,t))),listActivities:(e,i)=>r.listActivities(e.chainName,e.contractAddress,e.tokenId,e.accountAddress,e.activityType,e.fromIndexedAt,e.toIndexedAt,e.transactionHash,e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},ActivitiesApiFp:Tx,ActivityType:{Mint:"mint",Burn:"burn",Transfer:"transfer",Sale:"sale",Deposit:"deposit",Withdrawal:"withdrawal"},CancelledOrderStatusCancellationTypeEnum:{OnChain:"ON_CHAIN",OffChain:"OFF_CHAIN"},CancelledOrderStatusNameEnum:{Cancelled:"CANCELLED"},ChainsApi:class extends cx{listChains(e={},t){return Ex(this.configuration).listChains(e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},ChainsApiAxiosParamCreator:Ax,ChainsApiFactory:function(e,t,n){const r=Ex(e);return{listChains:(e={},i)=>r.listChains(e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},ChainsApiFp:Ex,CollectionContractType:{Erc721:"ERC721"},CollectionsApi:class extends cx{getCollection(e,t){return Ix(this.configuration).getCollection(e.contractAddress,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listCollections(e,t){return Ix(this.configuration).listCollections(e.chainName,e.contractAddress,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listCollectionsByNFTOwner(e,t){return Ix(this.configuration).listCollectionsByNFTOwner(e.accountAddress,e.chainName,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}refreshCollectionMetadata(e,t){return Ix(this.configuration).refreshCollectionMetadata(e.contractAddress,e.chainName,e.refreshCollectionMetadataRequest,t).then((e=>e(this.axios,this.basePath)))}},CollectionsApiAxiosParamCreator:_x,CollectionsApiFactory:function(e,t,n){const r=Ix(e);return{getCollection:(e,i)=>r.getCollection(e.contractAddress,e.chainName,i).then((e=>e(n,t))),listCollections:(e,i)=>r.listCollections(e.chainName,e.contractAddress,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),listCollectionsByNFTOwner:(e,i)=>r.listCollectionsByNFTOwner(e.accountAddress,e.chainName,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),refreshCollectionMetadata:(e,i)=>r.refreshCollectionMetadata(e.contractAddress,e.chainName,e.refreshCollectionMetadataRequest,i).then((e=>e(n,t)))}},CollectionsApiFp:Ix,Configuration:class{apiKey;username;password;accessToken;basePath;baseOptions;formDataCtor;constructor(e={}){this.apiKey=e.apiKey,this.username=e.username,this.password=e.password,this.accessToken=e.accessToken,this.basePath=e.basePath,this.baseOptions=e.baseOptions,this.formDataCtor=e.formDataCtor}isJsonMime(e){const t=new RegExp("^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$","i");return null!==e&&(t.test(e)||"application/json-patch+json"===e.toLowerCase())}},ERC20ItemItemTypeEnum:{Erc20:"ERC20"},ERC721ItemItemTypeEnum:{Erc721:"ERC721"},ExpiredOrderStatusNameEnum:{Expired:"EXPIRED"},FailedOrderCancellationReasonCodeEnum:{AlreadyFilled:"ALREADY_FILLED"},FeeFeeTypeEnum:{Royalty:"ROYALTY",MakerEcosystem:"MAKER_ECOSYSTEM",TakerEcosystem:"TAKER_ECOSYSTEM",Protocol:"PROTOCOL"},FilledOrderStatusNameEnum:{Filled:"FILLED"},InactiveOrderStatusNameEnum:{Inactive:"INACTIVE"},ListListingsSortByEnum:{CreatedAt:"created_at",UpdatedAt:"updated_at",BuyItemAmount:"buy_item_amount"},ListListingsSortDirectionEnum:{Asc:"asc",Desc:"desc"},ListTradesSortByEnum:{IndexedAt:"indexed_at"},ListTradesSortDirectionEnum:{Asc:"asc",Desc:"desc"},MetadataApi:class extends cx{getMetadata(e,t){return Cx(this.configuration).getMetadata(e.chainName,e.contractAddress,e.metadataId,t).then((e=>e(this.axios,this.basePath)))}listMetadata(e,t){return Cx(this.configuration).listMetadata(e.chainName,e.contractAddress,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}refreshMetadataByID(e,t){return Cx(this.configuration).refreshMetadataByID(e.chainName,e.contractAddress,e.refreshMetadataByIDRequest,t).then((e=>e(this.axios,this.basePath)))}refreshNFTMetadataByTokenID(e,t){return Cx(this.configuration).refreshNFTMetadataByTokenID(e.contractAddress,e.chainName,e.refreshNFTMetadataByTokenIDRequest,t).then((e=>e(this.axios,this.basePath)))}},MetadataApiAxiosParamCreator:Rx,MetadataApiFactory:function(e,t,n){const r=Cx(e);return{getMetadata:(e,i)=>r.getMetadata(e.chainName,e.contractAddress,e.metadataId,i).then((e=>e(n,t))),listMetadata:(e,i)=>r.listMetadata(e.chainName,e.contractAddress,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),refreshMetadataByID:(e,i)=>r.refreshMetadataByID(e.chainName,e.contractAddress,e.refreshMetadataByIDRequest,i).then((e=>e(n,t))),refreshNFTMetadataByTokenID:(e,i)=>r.refreshNFTMetadataByTokenID(e.contractAddress,e.chainName,e.refreshNFTMetadataByTokenIDRequest,i).then((e=>e(n,t)))}},MetadataApiFp:Cx,NFTContractType:{Erc721:"ERC721"},NativeItemItemTypeEnum:{Native:"NATIVE"},NftOwnersApi:class extends cx{listNFTOwners(e,t){return Ox(this.configuration).listNFTOwners(e.contractAddress,e.tokenId,e.chainName,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listOwnersByContractAddress(e,t){return Ox(this.configuration).listOwnersByContractAddress(e.contractAddress,e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},NftOwnersApiAxiosParamCreator:kx,NftOwnersApiFactory:function(e,t,n){const r=Ox(e);return{listNFTOwners:(e,i)=>r.listNFTOwners(e.contractAddress,e.tokenId,e.chainName,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),listOwnersByContractAddress:(e,i)=>r.listOwnersByContractAddress(e.contractAddress,e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},NftOwnersApiFp:Ox,NftsApi:class extends cx{getNFT(e,t){return Nx(this.configuration).getNFT(e.contractAddress,e.tokenId,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listAllNFTOwners(e,t){return Nx(this.configuration).listAllNFTOwners(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listAllNFTs(e,t){return Nx(this.configuration).listAllNFTs(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listNFTs(e,t){return Nx(this.configuration).listNFTs(e.contractAddress,e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listNFTsByAccountAddress(e,t){return Nx(this.configuration).listNFTsByAccountAddress(e.accountAddress,e.chainName,e.contractAddress,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},NftsApiAxiosParamCreator:Sx,NftsApiFactory:function(e,t,n){const r=Nx(e);return{getNFT:(e,i)=>r.getNFT(e.contractAddress,e.tokenId,e.chainName,i).then((e=>e(n,t))),listAllNFTOwners:(e,i)=>r.listAllNFTOwners(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),listAllNFTs:(e,i)=>r.listAllNFTs(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),listNFTs:(e,i)=>r.listNFTs(e.contractAddress,e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),listNFTsByAccountAddress:(e,i)=>r.listNFTsByAccountAddress(e.accountAddress,e.chainName,e.contractAddress,e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},NftsApiFp:Nx,OrderStatusName:{Pending:"PENDING",Active:"ACTIVE",Inactive:"INACTIVE",Filled:"FILLED",Expired:"EXPIRED",Cancelled:"CANCELLED"},OrdersApi:class extends cx{cancelOrders(e,t){return Px(this.configuration).cancelOrders(e.chainName,e.cancelOrdersRequestBody,t).then((e=>e(this.axios,this.basePath)))}createListing(e,t){return Px(this.configuration).createListing(e.chainName,e.createListingRequestBody,t).then((e=>e(this.axios,this.basePath)))}fulfillmentData(e,t){return Px(this.configuration).fulfillmentData(e.chainName,e.fulfillmentDataRequest,t).then((e=>e(this.axios,this.basePath)))}getListing(e,t){return Px(this.configuration).getListing(e.chainName,e.listingId,t).then((e=>e(this.axios,this.basePath)))}getTrade(e,t){return Px(this.configuration).getTrade(e.chainName,e.tradeId,t).then((e=>e(this.axios,this.basePath)))}listListings(e,t){return Px(this.configuration).listListings(e.chainName,e.status,e.sellItemContractAddress,e.buyItemContractAddress,e.sellItemTokenId,e.pageSize,e.sortBy,e.sortDirection,e.pageCursor,t).then((e=>e(this.axios,this.basePath)))}listTrades(e,t){return Px(this.configuration).listTrades(e.chainName,e.accountAddress,e.pageSize,e.sortBy,e.sortDirection,e.pageCursor,t).then((e=>e(this.axios,this.basePath)))}},OrdersApiAxiosParamCreator:xx,OrdersApiFactory:function(e,t,n){const r=Px(e);return{cancelOrders:(e,i)=>r.cancelOrders(e.chainName,e.cancelOrdersRequestBody,i).then((e=>e(n,t))),createListing:(e,i)=>r.createListing(e.chainName,e.createListingRequestBody,i).then((e=>e(n,t))),fulfillmentData:(e,i)=>r.fulfillmentData(e.chainName,e.fulfillmentDataRequest,i).then((e=>e(n,t))),getListing:(e,i)=>r.getListing(e.chainName,e.listingId,i).then((e=>e(n,t))),getTrade:(e,i)=>r.getTrade(e.chainName,e.tradeId,i).then((e=>e(n,t))),listListings:(e,i)=>r.listListings(e.chainName,e.status,e.sellItemContractAddress,e.buyItemContractAddress,e.sellItemTokenId,e.pageSize,e.sortBy,e.sortDirection,e.pageCursor,i).then((e=>e(n,t))),listTrades:(e,i)=>r.listTrades(e.chainName,e.accountAddress,e.pageSize,e.sortBy,e.sortDirection,e.pageCursor,i).then((e=>e(n,t)))}},OrdersApiFp:Px,PassportApi:class extends cx{createCounterfactualAddress(e,t){return Bx(this.configuration).createCounterfactualAddress(e.chainName,e.createCounterfactualAddressRequest,t).then((e=>e(this.axios,this.basePath)))}createCounterfactualAddressDeprecated(e,t){return Bx(this.configuration).createCounterfactualAddressDeprecated(e.createCounterfactualAddressRequestDeprecated,t).then((e=>e(this.axios,this.basePath)))}getLinkedAddresses(e,t){return Bx(this.configuration).getLinkedAddresses(e.userId,e.chainName,t).then((e=>e(this.axios,this.basePath)))}getLinkedAddressesDeprecated(e,t){return Bx(this.configuration).getLinkedAddressesDeprecated(e.userId,t).then((e=>e(this.axios,this.basePath)))}},PassportApiAxiosParamCreator:Mx,PassportApiFactory:function(e,t,n){const r=Bx(e);return{createCounterfactualAddress:(e,i)=>r.createCounterfactualAddress(e.chainName,e.createCounterfactualAddressRequest,i).then((e=>e(n,t))),createCounterfactualAddressDeprecated:(e,i)=>r.createCounterfactualAddressDeprecated(e.createCounterfactualAddressRequestDeprecated,i).then((e=>e(n,t))),getLinkedAddresses:(e,i)=>r.getLinkedAddresses(e.userId,e.chainName,i).then((e=>e(n,t))),getLinkedAddressesDeprecated:(e,i)=>r.getLinkedAddressesDeprecated(e.userId,i).then((e=>e(n,t)))}},PassportApiFp:Bx,PendingOrderStatusNameEnum:{Pending:"PENDING"},ProtocolDataOrderTypeEnum:{FullRestricted:"FULL_RESTRICTED"},SaleFeeTypeEnum:{Royalty:"ROYALTY"},TokenContractType:{Erc20:"ERC20"},TokensApi:class extends cx{getERC20Token(e,t){return Fx(this.configuration).getERC20Token(e.contractAddress,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listERC20Tokens(e,t){return Fx(this.configuration).listERC20Tokens(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},TokensApiAxiosParamCreator:Dx,TokensApiFactory:function(e,t,n){const r=Fx(e);return{getERC20Token:(e,i)=>r.getERC20Token(e.contractAddress,e.chainName,i).then((e=>e(n,t))),listERC20Tokens:(e,i)=>r.listERC20Tokens(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},TokensApiFp:Fx});class Ux extends Error{code;details;link;traceId;constructor({message:e,code:t,details:n,link:r,trace_id:i}){super(e),this.code=t,this.details=n,this.link=r,this.traceId=i}}const qx={sdkVersion:"ts-immutable-sdk-multi-rollup-api-client-0.31.0"},jx=({baseConfig:e,basePath:t,headers:n})=>{if(!t.trim())throw Error("basePath can not be empty");const r={...e,basePath:t,baseOptions:{headers:{...n||{},...qx}}};return new Lx.Configuration(r)};class Gx{apiConfig;baseConfig;constructor({baseConfig:e,overrides:t}){if(this.baseConfig=e,t)this.apiConfig=jx(t);else switch(e.environment){case st.SANDBOX:this.apiConfig=jx({basePath:"https://api.sandbox.immutable.com",baseConfig:e});break;case st.PRODUCTION:this.apiConfig=jx({basePath:"https://api.immutable.com",baseConfig:e});break;default:this.apiConfig=jx({basePath:"https://api.sandbox.immutable.com",baseConfig:e})}}}function Hx(e){if(Ve.isAxiosError(e)&&e.response){const t=e.response.data;return t.code&&t.message?new Ux({code:t.code,message:t.message,details:t.details||null,link:t.link||"",trace_id:t.trace_id||""}):new Ux({code:e.code??e.response?.status.toString()??"unknown_error_code",message:String(e),details:null,link:"",trace_id:""})}return new Ux({code:"unknown_error_code",message:String(e),details:null,link:"",trace_id:""})}class zx{config;activities;chains;collections;nfts;nftOwners;tokens;metadata;constructor(e){this.config=new Gx(e),this.activities=new Lx.ActivitiesApi(this.config.apiConfig),this.chains=new Lx.ChainsApi(this.config.apiConfig),this.collections=new Lx.CollectionsApi(this.config.apiConfig),this.nfts=new Lx.NftsApi(this.config.apiConfig),this.nftOwners=new Lx.NftOwnersApi(this.config.apiConfig),this.tokens=new Lx.TokensApi(this.config.apiConfig),this.metadata=new Lx.MetadataApi(this.config.apiConfig)}async listActivities(e){return await this.activities.listActivities(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async getActivity(e){return await this.activities.getActivity(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listChains(e){return await this.chains.listChains(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listCollections(e){return await this.collections.listCollections(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listCollectionsByNFTOwner(e){return await this.collections.listCollectionsByNFTOwner(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async getCollection(e){return await this.collections.getCollection(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async getNFT(e){return await this.nfts.getNFT(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listNFTs(e){return await this.nfts.listNFTs(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listNFTsByAccountAddress(e){return await this.nfts.listNFTsByAccountAddress(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listAllNFTs(e){return await this.nfts.listAllNFTs(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listNFTOwners(e){return await this.nftOwners.listNFTOwners(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listNFTOwnersByContractAddress(e){return await this.nftOwners.listOwnersByContractAddress(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listAllNFTOwners(e){return await this.nfts.listAllNFTOwners(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listTokens(e){return await this.tokens.listERC20Tokens(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async getToken(e){return await this.tokens.getERC20Token(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async getMetadata(e){return await this.metadata.getMetadata(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listNFTMetadataByContractAddress(e){return await this.metadata.listMetadata(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async refreshCollectionMetadata(e){return await this.collections.refreshCollectionMetadata(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async refreshNFTMetadata(e){return await this.metadata.refreshNFTMetadataByTokenID(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async refreshStackedMetadata(e){return await this.metadata.refreshMetadataByID(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}}async function Vx(t,n,r,i){const a=r.get(t),o=r.get(n);if(!a)throw new lm(`Chain:${t} is not a supported chain`,e.CheckoutErrorType.CHAIN_NOT_SUPPORTED_ERROR);if(!o)throw new lm(`Chain:${n} is not a supported chain`,e.CheckoutErrorType.CHAIN_NOT_SUPPORTED_ERROR);let s=jm;i.isDevelopment&&(s=qm),i.isProduction&&(s=Gm);const u=new nv({baseConfig:new ut({environment:i.environment}),bridgeInstance:s,rootProvider:a,childProvider:o});return new Qb(u)}async function Wx(e,t){const n=await t.remote.getConfig("dex");return new LR({chainId:e,baseConfig:new ut({environment:t.environment}),overrides:n?.overrides})}function Kx(e){return new ox({baseConfig:{environment:e.environment}})}function Xx(e){return new zx({baseConfig:{environment:e.environment}})}const Jx="0x0000000000000000000000000000000000000001",Yx=18;async function Qx(t,n,r){const i=bm(n),a=vm(n),o=await n.remote.getConfig("gasEstimateTokens"),{fromAddress:s}=o[i].bridgeToL2Addresses,u=t.get(i);if(!u)throw new Error(`Missing JsonRpcProvider for chain id: ${i}`);try{let o={};const c=async()=>{o=await async function(e,t){const n=await Dm(e);return n&&t?{estimatedAmount:n.add(n)}:{estimatedAmount:n}}(u,r),o.token=n.networkMap.get(i)?.nativeCurrency};let l={bridgeFee:{},bridgeable:!1};const d=async()=>{const e=await Vx(i,a,t,n);l=await async function(e,t){const n=await e.getFee({token:t});return{bridgeFee:{estimatedAmount:n.feeAmount},bridgeable:n.bridgeable}}(e,s)};return await Promise.all([c(),d()]),{gasEstimateType:e.GasEstimateType.BRIDGE_TO_L2,gasFee:o,bridgeFee:{estimatedAmount:l.bridgeFee?.estimatedAmount,token:l.bridgeFee?.token},bridgeable:l.bridgeable}}catch{return{gasEstimateType:e.GasEstimateType.BRIDGE_TO_L2,gasFee:{},bridgeFee:{},bridgeable:!1}}}async function Zx(t,n,r){switch(t.gasEstimateType){case e.GasEstimateType.BRIDGE_TO_L2:return await Qx(n,r,t.isSpendingCapApprovalRequired);case e.GasEstimateType.SWAP:return await async function(t){const n=vm(t),r=await t.remote.getConfig("gasEstimateTokens"),{inAddress:i,outAddress:a}=r[n].swapAddresses;try{const r=await Wx(n,t),{swap:o}=await r.getUnsignedSwapTxFromAmountIn(Jx,i,a,tr.from(kh("1",Yx)));if(null===o.gasFeeEstimate)return{gasEstimateType:e.GasEstimateType.SWAP,gasFee:{}};let s;return o.gasFeeEstimate.value&&(s=tr.from(o.gasFeeEstimate.value)),{gasEstimateType:e.GasEstimateType.SWAP,gasFee:{estimatedAmount:s,token:{address:o.gasFeeEstimate?.token.address,symbol:o.gasFeeEstimate?.token.symbol??"",name:o.gasFeeEstimate?.token.name??"",decimals:o.gasFeeEstimate?.token.decimals??Yx}}}}catch{return{gasEstimateType:e.GasEstimateType.SWAP,gasFee:{}}}}(r);default:throw new lm("Invalid type provided for gasEstimateType",e.CheckoutErrorType.INVALID_GAS_ESTIMATE_TYPE)}}const $x=t=>(t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.ERC721)return void r.push(t);const{contractAddress:a,spenderAddress:o,id:s}=t,u=`${a}${o}${s}`;n.get(u)||n.set(u,{...t})})),r.concat(Array.from(n.values()))})((t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.ERC20)return void r.push(t);const{contractAddress:a,spenderAddress:o,amount:s}=t,u=`${a}${o}`,c=n.get(u);c&&c.type===e.ItemType.ERC20?c.amount=tr.from(c.amount).add(s):n.set(u,{...t})})),r.concat(Array.from(n.values()))})((t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.NATIVE)return void r.push(t);const{amount:a}=t,o=n.get(i);o&&o.type===e.ItemType.NATIVE?o.amount=tr.from(o.amount).add(a):n.set(i,{...t})})),r.concat(Array.from(n.values()))})(t))),eP=async(t,n,r,i)=>{try{const e=new vl(r,JSON.stringify(tm),t);return await e.allowance(n,i)}catch(t){throw new lm("Failed to get the allowance for ERC20",e.CheckoutErrorType.GET_ERC20_ALLOWANCE_ERROR,{contractAddress:r})}},tP=async(t,n,r,i,a)=>{try{const e=new vl(r,JSON.stringify(tm),t),o=await e.populateTransaction.approve(i,a);return o&&(o.from=n),o}catch{throw new lm("Failed to get the approval transaction for ERC20",e.CheckoutErrorType.GET_ERC20_ALLOWANCE_ERROR,{contractAddress:r})}},nP=async(t,n,r,i)=>{try{const e=new vl(r,JSON.stringify(nm),t);return await e.isApprovedForAll(n,i)}catch(t){throw new lm("Failed to check approval for all ERC721s of collection",e.CheckoutErrorType.GET_ERC721_ALLOWANCE_ERROR,{ownerAddress:n,contractAddress:r,spenderAddress:i})}},rP=async(t,n,r,i,a)=>{try{const e=new vl(r,JSON.stringify(nm),t),o=await e.populateTransaction.approve(i,a);return o&&(o.from=n),o}catch(t){throw new lm("Failed to get the approval transaction for ERC721",e.CheckoutErrorType.GET_ERC721_ALLOWANCE_ERROR,{id:a.toString(),contractAddress:r,spenderAddress:i,ownerAddress:n})}},iP=async(t,n,r)=>{try{const e=new vl(n,JSON.stringify(nm),t);return await e.getApproved(r)}catch(t){throw new lm("Failed to get approved address for ERC721",e.CheckoutErrorType.GET_ERC721_ALLOWANCE_ERROR,{id:r.toString(),contractAddress:n})}},aP=(t,n)=>{const r=parseInt(t,10);if(Number.isNaN(r))throw new lm("Invalid ERC721 ID",e.CheckoutErrorType.GET_ERC721_ALLOWANCE_ERROR,{id:t,contractAddress:n});return r},oP=async(t,n,r)=>{let i=!0;const a=[],o=new Map,s=new Map,u=new Map,c=new Map,l=await(async(t,n,r)=>{const i=new Map,a=new Map;for(const o of n){if(o.type!==e.ItemType.ERC721)continue;const{contractAddress:n,spenderAddress:s}=o,u=`${n}-${s}`;i.set(u,!1),a.has(u)||a.set(u,nP(t,r,n,s))}const o=await Promise.all(a.values()),s=Array.from(a.keys());return o.forEach(((e,t)=>{i.set(s[t],e)})),i})(t,r,n);for(const n of r){if(n.type!==e.ItemType.ERC721)continue;const{contractAddress:r,id:i,spenderAddress:u}=n,c=`${r}-${u}`;if(l.get(c)){a.push({sufficient:!0,itemRequirement:n});continue}const d=`${r}-${i}`,f=aP(i,r);o.set(d,n),s.set(d,iP(t,r,f))}const d=await Promise.all(s.values()),f=Array.from(s.keys());for(let r=0;r<d.length;r++){const s=o.get(f[r]);if(!s||s.type!==e.ItemType.ERC721)continue;if(d[r]===s.spenderAddress){a.push({sufficient:!0,itemRequirement:s});continue}i=!1;const{contractAddress:l,id:p,spenderAddress:h}=s,m=`${l}-${p}`,y=aP(p,l);u.set(m,{type:e.ItemType.ERC721,sufficient:!1,itemRequirement:s,approvalTransaction:void 0}),c.set(m,rP(t,n,l,h,y))}const p=await Promise.all(c.values()),h=Array.from(c.keys());return p.forEach(((e,t)=>{const n=u.get(h[t]);n&&(n.sufficient||(n.approvalTransaction=e))})),{sufficient:i,allowances:a.concat(Array.from(u.values()))}},sP=t=>(t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.ERC721)return void r.push(t);const{contractAddress:a,id:o}=t,s=`${a}${o}`;n.get(s)||n.set(s,{...t})})),r.concat(Array.from(n.values()))})((t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.ERC20)return void r.push(t);const{contractAddress:a,amount:o}=t,s=`${a}`,u=n.get(s);u&&u.type===e.ItemType.ERC20?u.amount=tr.from(u.amount).add(o):n.set(s,{...t})})),r.concat(Array.from(n.values()))})((t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.NATIVE)return void r.push(t);const{amount:a}=t,o=n.get(i);o&&o.type===e.ItemType.NATIVE?o.amount=tr.from(o.amount).add(a):n.set(i,{...t})})),r.concat(Array.from(n.values()))})(t))),uP=async(t,n,r,i)=>{try{const a=new Map;(t=>t.map((t=>t.type===e.ItemType.NATIVE?{address:Vh}:{address:t.contractAddress})))(i).forEach((e=>a.set((e.address||"").toLocaleLowerCase(),e)));const{balances:o}=await Om(t,n,r);return o.filter((e=>a.get((e.token.address||"").toLocaleLowerCase())))}catch(t){throw new lm("Failed to get balances",e.CheckoutErrorType.GET_BALANCE_ERROR)}},cP=async(t,n,r,i)=>{const a=sP(i),o=[],s=[];if(a.forEach((t=>{switch(t.type){case e.ItemType.ERC20:case e.ItemType.NATIVE:o.push(t);break;case e.ItemType.ERC721:s.push(t)}})),0===s.length&&0===o.length)throw new lm("Unsupported item requirement balance check",e.CheckoutErrorType.UNSUPPORTED_BALANCE_REQUIREMENT_ERROR);const u=[];o.length>0&&u.push(uP(t,n,r,a)),s.length>0&&u.push((async(t,n,r)=>{const i=[],a=new Map,o=new Map;r.forEach((n=>{if(n.type!==e.ItemType.ERC721)return;const r=new vl(n.contractAddress,JSON.stringify(nm),t);a.set(n.contractAddress,n),o.set(n.contractAddress,r.ownerOf(n.id))}));try{const t=await Promise.all(o.values()),r=Array.from(o.keys());t.forEach(((t,o)=>{const s=a.get(r[o]);let u=0;s&&n===t&&(u=1),i.push({type:e.ItemType.ERC721,balance:tr.from(u),formattedBalance:u.toString(),contractAddress:s.contractAddress,id:s.id})}))}catch(t){throw new lm("Failed to get ERC721 balances",e.CheckoutErrorType.GET_ERC721_BALANCE_ERROR)}return i})(n,r,a));const c=await Promise.all(u),l=[];if(o.length>0&&c.length>0){const t=c.shift();t&&o.forEach((n=>{l.push(((t,n)=>{let r;t.type===e.ItemType.ERC20?r=n.find((e=>e.token?.address===t.contractAddress)):t.type===e.ItemType.NATIVE&&(r=n.find((e=>""===e.token?.address||e.token?.address===Vh)));const i=t.amount,a=i.isNegative()||i.isZero()||(r?.balance.gte(i)??!1),o=i.sub(r?.balance??tr.from(0));let s="",u="",c=Wh;r&&(c=r.token?.decimals??Wh,s=r.token.name,u=r.token.symbol);let l=r;return t.type===e.ItemType.NATIVE?(l||(l={type:e.ItemType.NATIVE,balance:tr.from(0),formattedBalance:"0",token:{name:s,symbol:u,decimals:Wh,address:Vh}}),{sufficient:a,type:e.ItemType.NATIVE,delta:{balance:o,formattedBalance:Ch(o,c)},current:{...l,type:e.ItemType.NATIVE},required:{...l,type:e.ItemType.NATIVE,balance:tr.from(t.amount),formattedBalance:Ch(t.amount,c)}}):(l||(l={type:t.type,balance:tr.from(0),formattedBalance:"0",token:{name:s,symbol:u,address:t.contractAddress,decimals:c}}),{sufficient:a,type:e.ItemType.ERC20,delta:{balance:o,formattedBalance:Ch(o,c)},current:l,required:{...l,balance:tr.from(t.amount),formattedBalance:Ch(t.amount,c)}})})(n,t))}))}if(s.length>0&&c.length>0){const t=c.shift();t&&s.forEach((n=>{l.push(((t,n)=>{const r=tr.from(1),i=n.find((e=>{const n=e;return n.contractAddress===t.contractAddress&&n.id===t.id})),a=r.isNegative()||r.isZero()||(i?.balance.gte(r)??!1),o=r.sub(i?.balance??tr.from(0));let s=i;return s||(s={type:e.ItemType.ERC721,balance:tr.from(0),formattedBalance:"0",contractAddress:t.contractAddress,id:t.id}),{sufficient:a,type:e.ItemType.ERC721,delta:{balance:o,formattedBalance:o.toString()},current:s,required:{...s,balance:tr.from(1),formattedBalance:"1"}}})(n,t))}))}return{sufficient:void 0===l.find((e=>!1===e.sufficient)),balanceRequirements:l}},lP=async(t,n)=>{try{return await t.estimateGas(n)}catch(t){throw new lm("Failed to estimate gas for transaction",e.CheckoutErrorType.UNPREDICTABLE_GAS_LIMIT)}},dP=async(t,n,r)=>{const i=[];let a=tr.from(0);for(const e of n)void 0!==e.approvalTransaction&&i.push(lP(t,e.approvalTransaction));if(r.type===e.TransactionOrGasType.TRANSACTION)i.push(lP(t,r.transaction));else{const e=await t.getFeeData(),n=Bm(e);if(null!==n){const e=n?.mul(r.gasToken.limit);e&&(a=a.add(e))}}return(await Promise.all(i)).forEach((e=>{a=a.add(e)})),a.eq(0)?null:((t,n)=>n.type===e.TransactionOrGasType.TRANSACTION||n.gasToken.type===e.GasTokenType.NATIVE?{type:e.ItemType.NATIVE,amount:t}:{type:e.ItemType.ERC20,amount:t,contractAddress:n.gasToken.contractAddress,spenderAddress:""})(a,r)},fP=(t,n)=>({checkDexAvailability:async()=>{let r;try{r=await Ve.post(`${t?Xh[zh]:n?Xh[st.PRODUCTION]:Xh[st.SANDBOX]}/v1/availability/checkout/swap`)}catch(e){r=e.response}if(403===r.status)return!1;if(204===r.status)return!0;throw new lm(`Error fetching from api: ${r.status} ${r.statusText}`,e.CheckoutErrorType.API_ERROR)}}),pP=async()=>!0,hP=async e=>{const t=fP(e.isDevelopment,e.isProduction);try{return await t.checkDexAvailability()}catch{return!1}};async function mP(t,n){if(t.isProduction&&n?.has(e.ChainId.ETHEREUM))return n;if(n?.has(e.ChainId.SEPOLIA))return n;const r=new Map;return(await pm(t,{type:e.NetworkFilterTypes.ALL})).networks.forEach((e=>{const n=t.networkMap.get(e.chainId)?.rpcUrls[0],i=new up(n);r.set(e.chainId,i)})),r}const yP=async(e,t,n,r,i)=>{const a=new Map;try{const o=await Wx(t,e),s=[],u=[];for(const e of i)e!==r.address&&(s.push(o.getUnsignedSwapTxFromAmountOut(n,e,r.address,r.amount,1)),u.push(e));return(await Im(e,"Time to resolve swap quotes from the dex",Promise.allSettled(s))).forEach(((e,t)=>{if("rejected"===e.status)return;const n=u[t];a.set(n,{quote:e.value.quote,approval:e.value.approval?.gasFeeEstimate??null,swap:e.value.swap.gasFeeEstimate})})),a}catch{return a}},gP=(e,t,n)=>{let r,i=tr.from(0),a="0";e&&(i=e.value,a=Ch(e.value,e.token.decimals),r={name:e.token.name??"",symbol:e.token.symbol??"",address:e.token.address,decimals:e.token.decimals});let o,s=tr.from(0),u="0";t&&(s=t.value,u=Ch(t.value,t.token.decimals),o={name:t.token.name??"",symbol:t.token.symbol??"",address:t.token.address,decimals:t.token.decimals});const c=[];for(const e of n)c.push({amount:e.amount.value,formattedAmount:Ch(e.amount.value,e.amount.token.decimals),token:{name:e.amount.token.name??"",symbol:e.amount.token.symbol??"",address:e.amount.token.address,decimals:e.amount.token.decimals}});return{approvalGasFees:{amount:i,formattedAmount:a,token:r},swapGasFees:{amount:s,formattedAmount:u,token:o},swapFees:c}},bP=(t,n,r,i)=>{const a=r.token.address;let o=e.ItemType.ERC20;return a===Vh&&(o=e.ItemType.NATIVE),{type:e.FundingStepType.SWAP,chainId:t,fundingItem:{type:o,fundsRequired:{amount:n,formattedAmount:Ch(n,r.token.decimals)},userBalance:{balance:r.balance,formattedBalance:r.formattedBalance},token:r.token},fees:i}},vP=(e,t)=>{if(!t)return{sufficient:!0,approvalGasFee:tr.from(0),approvalGasTokenAddress:""};const n=t.value,r=t.token.address;if(0===e.length)return{sufficient:!1,approvalGasFee:n,approvalGasTokenAddress:r};const i=e.find((e=>e.token.address===r));return i?i.balance.lt(n)?{sufficient:!1,approvalGasFee:n,approvalGasTokenAddress:r}:{sufficient:!0,approvalGasFee:n,approvalGasTokenAddress:r}:{sufficient:!1,approvalGasFee:n,approvalGasTokenAddress:r}},wP=(e,t,n,r,i)=>{const a=new Map;if(""!==t.approvalGasTokenAddress&&a.set(t.approvalGasTokenAddress,t.approvalGasFee),n){const e=a.get(n.token.address);e?a.set(n.token.address,e.add(n.value)):a.set(n.token.address,n.value)}if(i){const e=a.get(i.address);e?a.set(i.address,e.add(i.amount)):a.set(i.address,i.amount)}for(const e of r){const t=a.get(e.amount.token.address);t?a.set(e.amount.token.address,t.add(e.amount.value)):a.set(e.amount.token.address,e.amount.value)}for(const[t,n]of a.entries()){if(n===tr.from(0))continue;const r=e.find((e=>e.token.address===t));if(!r)return!1;if(r.balance.lt(n))return!1}return!0},TP=(t,n,r,i,a,o)=>{let s=tr.from(0),u="",c=!1;if(n.balanceRequirements.forEach((n=>{n.type!==e.ItemType.NATIVE&&n.type!==e.ItemType.ERC20||n.required.token.address===r&&(u=n.required.token.address,c=!0,s=t.sub(n.required.balance))})),!c)return!0;a.approvalGasTokenAddress===u&&(s=s.sub(a.approvalGasFee));for(const e of o)e.amount.token.address===u&&(s=s.sub(e.amount.value));return s.gte(i)},AP=async(t,n,r,i,a,o,s)=>{const u=[];if(!n.swap)return u;if(0===o.length)return u;const c=(t=>{let n="",r=tr.from(0);switch(t.type){case e.ItemType.ERC20:n=t.required.token.address??"",r=t.delta.balance;break;case e.ItemType.NATIVE:n=Vh,r=t.delta.balance}return{address:n,amount:r}})(i);if(""===c.address)return u;const l=vm(t),d=a.get(l);if(!d)return u;const f=d.balances;if(0===f.length)return u;const p=await yP(t,vm(t),r,c,o),h=Array.from(p.keys());for(const e of h){const t=p.get(e);if(!t)continue;const n=f.find((t=>t.token.address===e));if(!n)continue;const r=t.quote.amount;if(n.balance.lt(r.value))continue;const i=vP(f,t.approval);if(!i.sufficient)continue;if(!wP(f,i,t.swap,t.quote.fees,{amount:r.value,address:e}))continue;if(!TP(n.balance,s,e,r.value,i,t.quote.fees))continue;const a=gP(t.approval,t.swap,t.quote.fees);u.push(bP(l,r.value,n,a))}return u},EP=(e,t)=>t&&t.success?e.filter((e=>"address"in e?t.balances.find((t=>t.token.address===e.address&&t.balance.gt(0))):t.balances.find((e=>!("address"in e.token)&&e.balance.gt(0))))):[],_P=async(e,t)=>{if(t.onRamp){const t=await e.remote.getConfig("onramp"),n={};return Object.entries(t).forEach((([e,t])=>{n[e]=t.tokens??[]})),n}return{}},IP=async(e,t,n)=>{if(n.bridge){const n=(await e.remote.getConfig("bridge"))?.tokens??[],r=t.get(bm(e));return EP(n,r)}return[]},RP=async(e,t,n)=>{const r={};return r.swap=await(async(e,t,n)=>{if(n.swap){const n=(await e.remote.getConfig("dex"))?.tokens??[],r=t.get(vm(e));return EP(n,r)}return[]})(e,t,n),r.bridge=await IP(e,t,n),r.onRamp=await _P(e,n),r},CP="0x0000000000000000000000000000000000000001",kP=async(e,t)=>(await t.remote.getConfig("imxAddressMapping"))[e]??"",OP=async(t,n)=>{if(""===n)return{l1address:"",l2address:n};if(n===Vh)return{l1address:await kP(bm(t),t),l2address:Vh};const r=(i=vm(t))===e.ChainId.IMTBL_ZKEVM_MAINNET?"imtbl-zkevm-mainnet":i===e.ChainId.IMTBL_ZKEVM_TESTNET?"imtbl-zkevm-testnet":i===e.ChainId.IMTBL_ZKEVM_DEVNET?"imtbl-zkevm-devent":"";var i;if(""===r)return{l1address:"",l2address:n};const a=Xx(t),o=(await a.getToken({chainName:r,contractAddress:n})).result.root_contract_address;return null===o?{l1address:"",l2address:n}:{l1address:o,l2address:n}},SP=async(t,n,r,i,a,o)=>{if(a===CP)return tr.from(0);const s=bm(t),u=vm(t);return await(async(t,n,r,i,a,o,s,u)=>{try{const e=await Vx(a,o,n,t),{unsignedTx:c}=await e.getUnsignedApproveDepositBridgeTx({depositorAddress:i,token:s,depositAmount:u});return null===c?tr.from(0):await r.estimateGas(c)}catch(t){throw new lm("Error occurred while attempting ot estimate gas for approval transaction",e.CheckoutErrorType.BRIDGE_GAS_ESTIMATE_ERROR,{message:t.message})}})(t,n,r,i,s,u,a,o)},NP=(e,t)=>(e=>{for(const t of e.balances)if(!t.token.address||""===t.token.address)return t.balance;return tr.from(0)})(e).gte(t),xP=async(t,n,r)=>{let i=r.get(e.FundingStepType.BRIDGE);return i||(i=await(async(t,n)=>{try{const r=await Zx({gasEstimateType:e.GasEstimateType.BRIDGE_TO_L2,isSpendingCapApprovalRequired:!1},n,t),i=r.gasFee.estimatedAmount,a=r.bridgeFee.estimatedAmount;let o=tr.from(0);return i&&(o=o.add(i)),a&&(o=o.add(a)),{type:e.FundingStepType.BRIDGE,gasFee:{estimatedAmount:i??tr.from(0),token:r.gasFee.token},bridgeFee:{estimatedAmount:a??tr.from(0),token:r.bridgeFee.token},totalFees:o}}catch(t){throw new lm("Error estimating gas for bridge",e.CheckoutErrorType.BRIDGE_GAS_ESTIMATE_ERROR,{message:t.message})}})(t,n),r.set(e.FundingStepType.BRIDGE,i),i)},PP=(e,t,n)=>{const r=n.token?.decimals??Wh;return{approvalGasFees:{amount:e,formattedAmount:Ch(e,Wh),token:t.token},bridgeGasFees:{amount:t.estimatedAmount,formattedAmount:Ch(t.estimatedAmount,Wh),token:t.token},bridgeFees:[{amount:n.estimatedAmount,formattedAmount:Ch(n.estimatedAmount,r),token:n.token}]}},MP=(t,n,r,i,a)=>({type:e.FundingStepType.BRIDGE,chainId:t,fundingItem:{type:i,fundsRequired:{amount:r.amount,formattedAmount:r.formattedAmount},userBalance:{balance:n.balance,formattedBalance:n.formattedBalance},token:{name:n.token.name,symbol:n.token.symbol,address:n.token.address,decimals:n.token.decimals}},fees:a}),BP=async(t,n,r,i,a,o,s)=>{if(!i.bridge)return;if(void 0===a.l2address||""===a.l2address)return;const u=bm(t),c=o.get(u),l=n.get(u);if(!l)throw new lm("No L1 provider available",e.CheckoutErrorType.PROVIDER_ERROR,{chainId:u.toString()});if(void 0===c||!1===c.success)return;const d=await IP(t,o,i);if(0===d.length)return;const f=await xP(t,n,s);if(!NP(c,f.totalFees))return;const p=await OP(t,a.l2address),{l1address:h}=p;if(""===h)return;if(h===CP){if(!d.find((e=>!("address"in e))))return}else if(!d.find((e=>e.address===h)))return;const m=await SP(t,n,l,r,h,a.amount);let y=f.bridgeFee.estimatedAmount;if(h===CP){const t=c.balances.find((e=>{return!(t=e.token.address)||""===t;var t}));if(f.gasFee.estimatedAmount&&(y=y.add(f.gasFee.estimatedAmount)),!NP(c,y))return;if(t&&t.balance.gte(a.amount.add(y))){const n=PP(m,f.gasFee,f.bridgeFee);return MP(u,t,a,e.ItemType.NATIVE,n)}return}if(y.add(m).add(f.gasFee.estimatedAmount),!NP(c,y))return;const g=c.balances.find((e=>e.token.address===h));if(g&&g.balance.gte(a.amount)){const t=PP(m,f.gasFee,f.bridgeFee);return MP(u,g,a,e.ItemType.ERC20,t)}},DP=(e,t)=>{let n=tr.from(0);return e.quote.fees.forEach((e=>{e.amount.token.address===t&&(n=n.add(e.amount.value))})),e.approval&&e.approval.token.address===t&&(n=n.add(e.approval.value)),n},FP=(t,n)=>{for(const r of t.balanceRequirements)if((r.type===e.ItemType.NATIVE||r.type===e.ItemType.ERC20)&&r.required.token.address===n)return r.required.balance;return tr.from(0)},LP=(e,t,n)=>{const r=n?.balance??tr.from(0);if(r.gte(e.add(t)))return tr.from(0);if(r.lte(0))return e.add(t);const i=r.sub(t);return i.gte(0)?e.sub(i):e.add(t).sub(r)},UP=async(e,t,n,r,i,a,o,s,u,c)=>{const{l1balances:l,l2balances:d}=((e,t)=>{const n={l1balances:[],l2balances:[]},r=t.get(bm(e)),i=t.get(vm(e));return r?void 0!==r.error?n:r.success&&i?void 0!==i.error?n:i.success?{l1balances:r.balances,l2balances:i.balances}:n:n:n})(e,o),f=r.required.token.address;if(((e,t,n,r,i,a)=>0===e.length||0===t.length||0===n.length||0===r.length||!i.bridge||!i.swap||void 0===a||""===a)(s,u,l,d,n,f))return[];const p=await(async(e,t)=>{const n=t.map((t=>OP(e,t.address??"")));return await Promise.all(n)})(e,u),h=((e,t,n,r)=>{const i=[];for(const a of r){if(""===a.l1address)continue;if(""===a.l2address)continue;if(!t.includes(a.l1address))continue;if(a.l2address===e)continue;const r=n.find((e=>e.address===a.l2address));r&&i.push(r)}return i})(f,s,u,p);if(0===h.length)return[];const m=await(async(e,t,n,r,i)=>{const a=[];for(const e of i)e.address&&a.push(e.address);return await yP(e,vm(e),t,{address:n,amount:r.delta.balance},a)})(e,i,f,r,h),y=((e,t,n,r,i)=>{const a=[];for(const[o,s]of e){const e=n.find((e=>e.token.address===o)),u=r.find((e=>e.l2address===o));if(!u)continue;const{l1address:c,l2address:l}=u;if(!c)continue;const d=t.find((e=>void 0===e.token.address&&c===CP||e.token.address===c));if(!d)continue;const f=s.quote.amountWithMaxSlippage.value,p=DP(s,o),h=f.add(p),m=FP(i,o),y=LP(h,m,e);y.lte(0)||y.gte(d.balance)||a.push({amount:y,formattedAmount:Ch(y,d.token.decimals),l2address:l})}return a})(m,l,d,p,c);if(0===y.length)return[];const g=new Map,b=new Map,v=[];for(const r of y)r.l2address&&(g.set(r.l2address,BP(e,t,i,n,r,o,a)),b.set(r.l2address,{amount:r.amount,formattedAmount:r.formattedAmount,l2address:r.l2address}));const w=await Promise.all(g.values()),T=Array.from(g.keys()),A=[];if(w.forEach(((e,t)=>{const n=T[t];if(void 0===e)return;A.push(n);const r=b.get(n);r&&v.push({amount:r.amount,formattedAmount:r.formattedAmount,l2address:r.l2address})})),0===A.length)return[];if(0===v.length)return[];const E=((e,t,n,r,i)=>{const a=new Map;for(const[e,n]of t)a.set(e,{success:n.success,balances:n.balances});const o=new Map;for(const e of n)e.token.address&&o.set(e.token.address,e);for(const e of r){const{amount:t,l2address:n}=e;if(""===n)continue;let r=tr.from(0);const a=o.get(n);a&&(r=a.balance);const s=r.add(t),u=i.find((e=>e.address===n));o.set(n,{balance:s,formattedBalance:Ch(s,u.decimals),token:u})}const s=Array.from(o.values());return a.set(vm(e),{success:!0,balances:s}),a})(e,o,d,v,u),_=await AP(e,n,i,r,E,A,c);if(!_)return[];const I=((e,t)=>{const n=[];for(const r of t){const{chainId:t,fundingItem:i}=r,{userBalance:a}=r.fundingItem,o=e.get(t);if(!o)continue;let s=tr.from(0),u="0";const c=o.balances.find((e=>e.token.address===i.token.address));c&&(s=c.balance,u=c.formattedBalance),a.balance=s,a.formattedBalance=u,n.push(r)}return n})(o,_);return((e,t,n)=>{const r=[];for(const i of e){if(!i)continue;const e=n.find((e=>void 0===i.fundingItem.token.address?e.l1address===CP&&e.l2address:e.l1address===i.fundingItem.token.address&&e.l2address));if(!e)continue;const a=t.find((t=>t.fundingItem.token.address===e.l2address));a&&r.push({bridgeFundingStep:i,swapFundingStep:a})}return r})(w,I,p)},qP=async(t,n,r)=>{if(!n.onRamp)return;if(void 0===r)return;const i=await(async(t,n,r)=>{if(r.type!==e.ItemType.ERC20&&r.type!==e.ItemType.NATIVE)return;const{required:i,current:a,delta:o}=r;let s=!1;const u=await _P(t,n);return Object.values(u).forEach((e=>{e.length>0&&!s&&(s=!!e.find((e=>e.address===i.token?.address)))})),s?{type:e.FundingStepType.ONRAMP,chainId:vm(t),fundingItem:{type:i.token.address===Vh?e.ItemType.NATIVE:e.ItemType.ERC20,fundsRequired:{amount:o.balance,formattedAmount:o.formattedBalance},userBalance:{balance:a.balance,formattedBalance:a.formattedBalance},token:i.token}}:void 0})(t,n,r);return i},jP=async(t,n,r,i)=>{if(!(e=>e.bridge||e.swap||e.onRamp)(i))return{type:e.RoutingOutcomeType.NO_ROUTE_OPTIONS,message:"No routing options are available"};let a;try{a=await mP(t)}catch(t){throw new lm("Error occurred while creating read only providers",e.CheckoutErrorType.PROVIDER_ERROR,{message:t.message})}const o=await Im(t,"Time to get token balances inside router",(async(t,n,r,i)=>{const a=new Map,o=new Map;if(0===n.size){const n={success:!1,error:new lm("No L1 or L2 provider available",e.CheckoutErrorType.PROVIDER_ERROR),balances:[]};return a.set(bm(t),n),a.set(vm(t),n),a}if(i.bridge){const i=bm(t);n.has(i)?o.set(i,Om(t,n.get(i),r,i)):a.set(bm(t),{success:!1,error:new lm(`No L1 provider available for ${i}`,e.CheckoutErrorType.PROVIDER_ERROR),balances:[]})}const s=vm(t);if(n.has(s)?o.set(s,Om(t,n.get(s),r,s)):a.set(vm(t),{success:!1,error:new lm(`No L2 provider available for ${s}`,e.CheckoutErrorType.PROVIDER_ERROR),balances:[]}),o.size>0){const t=Array.from(o.keys());(await Promise.allSettled(o.values())).forEach(((n,r)=>{const i=t[r];"fulfilled"===n.status?a.set(i,{success:!0,balances:n.value.balances}):a.set(i,{success:!1,error:new lm(`Error getting ${s} balances`,e.CheckoutErrorType.GET_BALANCE_ERROR),balances:[]})}))}return a})(t,a,n,i)),s=await Im(t,"Time to get routing allowlist",RP(t,o,i)),u=new Map,c=(e=>{let t,n=0;for(const r of e.balanceRequirements)r.sufficient||(n++,t=r);if(1===n)return t})(r),l=[];l.push((async(t,n,r,i,a,o,s)=>{let u;if(void 0===i)return;if(i.type!==e.ItemType.NATIVE&&i.type!==e.ItemType.ERC20)return;const c={amount:i.delta.balance,formattedAmount:i.delta.formattedBalance,l2address:i.required.token.address??""};return r.bridge&&i&&(u=await BP(t,n,a,r,c,o,s)),u})(t,a,i,c,n,o,u)),l.push((async(e,t,n,r,i,a,o)=>{const s=[];if(!t.swap)return s;if(void 0===n)return s;if(void 0===a)return s;const u=i.get(vm(e));if(!u)return s;if(void 0!==u.error||!u.success)return s;if(0===a.length)return s;const c=a.filter((e=>e.address)).map((e=>e.address));return 0===c.length?s:await AP(e,t,r,n,i,c,o)})(t,i,c,n,o,s.swap,r)),l.push(qP(t,i,c)),l.push((async(t,n,r,i,a,o,s,u,c)=>{if(!i)return[];const l=o.get(bm(t)),d=o.get(vm(t));if(!l)return[];if(void 0!==l.error||!l.success)return[];if(!d)return[];if(void 0!==d.error||!d.success)return[];const f=(s?.bridge??[]).map((e=>void 0===e.address?CP:e.address)),p=s?.swap??[];return i.type!==e.ItemType.NATIVE&&i.type!==e.ItemType.ERC20?[]:await UP(t,n,r,i,a,u,o,f,p,c)})(t,a,i,c,n,o,s,u,r));const d=await Im(t,"Time to resolve all routes",Promise.all(l));let f,p,h=[],m=[];if(d.forEach(((e,t)=>{0===t&&(f=e),1===t&&(h=e),2===t&&(p=e),3===t&&(m=e)})),!f&&0===h.length&&!p&&0===m.length)return{type:e.RoutingOutcomeType.NO_ROUTES_FOUND,message:"Smart Checkout did not find any funding routes to fulfill the transaction"};const y={type:e.RoutingOutcomeType.ROUTES_FOUND,fundingRoutes:[]};let g=0;return h.length>0&&(g++,h.forEach((e=>{y.fundingRoutes.push({priority:g,steps:[e]})}))),f&&(g++,y.fundingRoutes.push({priority:g,steps:[f]})),p&&(g++,y.fundingRoutes.push({priority:g,steps:[p]})),m&&(g++,m.forEach((e=>{const t=e.bridgeFundingStep,n=e.swapFundingStep;y.fundingRoutes.push({priority:g,steps:[t,n]})}))),y},GP=async(t,n,r,i)=>{const a=await n.getSigner().getAddress();let o=$x(r);const s=(async(t,n,r)=>{let i=!0;const a=[],o=new Map,s=new Map,u=new Map,c=new Map;for(const i of r){if(i.type!==e.ItemType.ERC20)continue;const{contractAddress:r,spenderAddress:a}=i,u=`${r}${a}`;o.set(u,i),s.set(u,eP(t,n,r,a))}const l=await Promise.all(s.values()),d=Array.from(s.keys());for(let r=0;r<l.length;r++){const s=o.get(d[r]);if(!s||s.type!==e.ItemType.ERC20)continue;if(l[r].gte(s.amount)){a.push({sufficient:!0,itemRequirement:s});continue}i=!1;const{contractAddress:f,spenderAddress:p}=s,h=`${f}${p}`,m=s.amount.sub(l[r]);u.set(h,{type:e.ItemType.ERC20,sufficient:!1,delta:m,itemRequirement:s,approvalTransaction:void 0}),c.set(h,tP(t,n,f,p,m))}const f=await Promise.all(c.values()),p=Array.from(c.keys());return f.forEach(((e,t)=>{const n=u.get(p[t]);n&&(n.sufficient||(n.approvalTransaction=e))})),{sufficient:i,allowances:a.concat(Array.from(u.values()))}})(n,a,o),u=oP(n,a,o),c=await Im(t,"Time to calculate token allowances",Promise.all([s,u])),l=((e,t)=>{const n=[];if(!e.sufficient)for(const t of e.allowances)t.sufficient||n.push(t);if(!t.sufficient)for(const e of t.allowances)e.sufficient||n.push(e);return n})(c[0],c[1]),d=await Im(t,"Time to run gas calculator",dP(n,l,i));null!==d&&(o.push(d),o=$x(o));const f=await Im(t,"Time to run balance checks",cP(t,n,a,o)),{sufficient:p}=f,h=f.balanceRequirements;if(p)return{sufficient:p,transactionRequirements:h};const m=await Im(t,"Time to fetch available routing options",(async(e,t)=>{const n={onRamp:e.isOnRampEnabled,swap:e.isSwapEnabled,bridge:e.isBridgeEnabled},r=[];if(n.onRamp&&r.push({id:"onRamp",promise:pP()}),n.swap&&r.push({id:"swap",promise:hP(e)}),r.length>0){const e=r.map((e=>e.promise));(await Promise.allSettled(e)).forEach(((e,t)=>{const i=r[t].id;n[i]=n[i]&&"fulfilled"===e.status&&e.value}))}return n.bridge=n.bridge&&!(e=>!0===e.provider?.isPassport??!1)(t),n})(t,n));return{sufficient:p,transactionRequirements:h,router:{availableRoutingOptions:m,routingOutcome:await Im(t,"Total time to run the routing calculator",jP(t,a,f,m))}}};var HP;!function(e){e.SUCCESS="SUCCESS",e.FAILED="FAILED"}(HP||(HP={}));const zP=async(t,n)=>{let r=[];try{const e=await Promise.all(n.map((e=>t.getSigner().sendTransaction(e))));r=await Promise.all(e.map((e=>e.wait())))}catch(t){throw new lm("An error occurred while executing the approval transaction",e.CheckoutErrorType.EXECUTE_APPROVAL_TRANSACTION_ERROR,{message:t.message})}for(const e of r)if(0===e.status)return{type:HP.FAILED,transactionHash:e.transactionHash,reason:"Approval transaction failed and was reverted"};return{type:HP.SUCCESS}},VP=async(t,n)=>{let r=[];try{const e=await Promise.all(n.map((e=>t.getSigner().sendTransaction(e))));r=await Promise.all(e.map((e=>e.wait())))}catch(t){throw new lm("An error occurred while executing the fulfillment transaction",e.CheckoutErrorType.EXECUTE_FULFILLMENT_TRANSACTION_ERROR,{message:t.message})}for(const e of r)if(0===e.status)return{type:HP.FAILED,transactionHash:e.transactionHash,reason:"Fulfillment transaction failed and was reverted"};return{type:HP.SUCCESS}},WP=async e=>{let t=[];const n=[];for(const t of e)t.type===VN.TRANSACTION&&t.purpose===HN.FULFILL_ORDER&&n.push(t.buildTransaction());return t=await Promise.all(n),t},KP=(e,t)=>{const n=e.amount,r=Math.round(n.percentageDecimal*10**6);return t.mul(tr.from(r)).div(10**6)},XP=(e,t)=>kh(e.amount.token,t),JP=(t,n,r=18)=>{let i=tr.from(0);const a=tr.from(n),o=a.mul(1e6).div(10**6),s=[];for(const n of t){let t=tr.from(0);if(Object.hasOwn(n.amount,"percentageDecimal"))t=KP(n,a),i=i.add(t);else{if(!Object.hasOwn(n.amount,"token"))throw new lm("Unknown fee type parsed, must be percentageDecimal or token",e.CheckoutErrorType.ORDER_FEE_ERROR);t=XP(n,r),i=i.add(t)}if(i.gt(o))throw new lm("The combined fees are above the allowed maximum of 100%",e.CheckoutErrorType.ORDER_FEE_ERROR);t.gt(0)&&s.push({amount:t.toString(),recipient:n.recipient})}return s},YP=(t,n,r,i)=>{switch(t){case e.ItemType.ERC20:return{type:t,amount:r,contractAddress:n,spenderAddress:i};case e.ItemType.NATIVE:default:return{type:e.ItemType.NATIVE,amount:r}}},QP=async(t,n,r)=>{if(0===r.length)throw new lm("No orders were provided to the orders array. Please provide at least one order.",e.CheckoutErrorType.FULFILL_ORDER_LISTING_ERROR);let i,a="",o=18;const s=sx,u=Kx(t),c=Xx(t),l=await Im(t,"Time to get the address from the provider",n.getSigner().getAddress());km.clear(),Om(t,n,l,bm(t)),Om(t,n,l,vm(t));const{id:d,takerFees:f}=r[0];let p;try{i=await Im(t,"Time to fetch the listing from the orderbook",u.getListing(d));const{seaportContractAddress:e,chainName:n}=u.config();p=n,a=e}catch(t){throw new lm("An error occurred while getting the order listing",e.CheckoutErrorType.GET_ORDER_LISTING_ERROR,{orderId:d,message:t.message})}if(0===i.result.buy.length)throw new lm("An error occurred with the get order listing",e.CheckoutErrorType.GET_ORDER_LISTING_ERROR,{orderId:d,message:"No buy side tokens found on order"});const h=i.result.buy[0];if("ERC20"===h.type){const e=await Im(t,"Time to get decimals of token contract for the buy token",c.getToken({contractAddress:h.contractAddress,chainName:p}));e.result.decimals&&(o=e.result.decimals)}let m=[];f&&f.length>0&&(m=JP(f,h.amount,o));let y=[],g=[],b=[];const v=performance.now();try{const{actions:e}=await Im(t,"Time to call fulfillOrder from the orderbook",u.fulfillOrder(d,l,m));b=e,y=await Im(t,"Time to construct the unsigned approval transactions",(async e=>{let t=[];const n=[];for(const t of e)t.type===VN.TRANSACTION&&t.purpose===HN.APPROVAL&&n.push(t.buildTransaction());return t=await Promise.all(n),t})(e))}catch(n){const r=(performance.now()-v)/1e3;if(_m(t,"Time to call fulfillOrder from the orderbook",r),n.message.includes(qN.EXPIRED))throw new lm("Order is expired",e.CheckoutErrorType.ORDER_EXPIRED_ERROR,{orderId:d});if(!n.message.includes("The fulfiller does not have the balances needed to fulfill"))throw new lm("Error occurred while trying to fulfill the order",e.CheckoutErrorType.FULFILL_ORDER_LISTING_ERROR,{orderId:d,message:n.message})}try{g=await Im(t,"Time to construct the unsigned fulfillment transactions",WP(b))}catch{}let w=tr.from("0"),T=e.ItemType.NATIVE,A="";const E=i.result.buy;if(E.length>0)switch(E[0].type){case"NATIVE":T=e.ItemType.NATIVE;break;case"ERC20":T=e.ItemType.ERC20,A=E[0].contractAddress;break;default:throw new lm("Purchasing token type is unsupported",e.CheckoutErrorType.UNSUPPORTED_TOKEN_TYPE_ERROR,{orderId:d})}E.forEach((t=>{t.type!==e.ItemType.ERC721&&(w=w.add(tr.from(t.amount)))}));i.result.fees.forEach((e=>{w=w.add(tr.from(e.amount))}));const _=[YP(T,A,w,a)],I=await Im(t,"Total time running smart checkout",GP(t,n,_,((t,n)=>n.length>0?{type:e.TransactionOrGasType.TRANSACTION,transaction:n[0]}:{type:e.TransactionOrGasType.GAS,gasToken:{type:e.GasTokenType.NATIVE,limit:tr.from(t)}})(s,g)));if(I.sufficient){const t=await zP(n,y);if(t.type===HP.FAILED)return{status:e.CheckoutStatus.FAILED,transactionHash:t.transactionHash,reason:t.reason,smartCheckoutResult:I};try{0===g.length&&(g=await WP(b))}catch(t){throw new lm("Error fetching fulfillment transaction",e.CheckoutErrorType.FULFILL_ORDER_LISTING_ERROR,{message:t.message})}const r=await VP(n,g);return r.type===HP.FAILED?{status:e.CheckoutStatus.FAILED,transactionHash:r.transactionHash,reason:r.reason,smartCheckoutResult:I}:{status:e.CheckoutStatus.SUCCESS,smartCheckoutResult:I}}return{status:e.CheckoutStatus.INSUFFICIENT_FUNDS,smartCheckoutResult:I}},ZP=(t,n,r)=>({type:e.ItemType.ERC721,id:t,contractAddress:n,spenderAddress:r}),$P=async(t,n,r)=>{let i,a,o="";if(0===r.length)throw new lm("No orders were provided to the orders array. Please provide at least one order.",e.CheckoutErrorType.PREPARE_ORDER_LISTING_ERROR);const{buyToken:s,sellToken:u,makerFees:c}=r[0];let l=18;if(s.type===e.ItemType.ERC20){const e=new vl(s.contractAddress,JSON.stringify(tm),n);l=await Im(t,"Time to get decimals of token contract for the buy token",e.decimals())}const d=((t,n=18)=>{const r=kh(t.amount,n);return t.type===e.ItemType.NATIVE?{type:e.ItemType.NATIVE,amount:r.toString()}:{type:e.ItemType.ERC20,amount:r.toString(),contractAddress:t.contractAddress}})(s,l);try{const r=await Im(t,"Time to get the address from the provider",n.getSigner().getAddress());i=Kx(t);const{seaportContractAddress:s}=i.config();o=s,a=await Im(t,"Time to prepare the listing from the orderbook",i.prepareListing({makerAddress:r,buy:d,sell:{type:e.ItemType.ERC721,contractAddress:u.collectionAddress,tokenId:u.id}}))}catch(t){throw new lm("An error occurred while preparing the listing",e.CheckoutErrorType.PREPARE_ORDER_LISTING_ERROR,{message:t.message,id:u.id,collectionAddress:u.collectionAddress})}const f=[ZP(u.id,u.collectionAddress,o)],p=await Im(t,"Total time running smart checkout",GP(t,n,f,{type:e.TransactionOrGasType.GAS,gasToken:{type:e.GasTokenType.NATIVE,limit:tr.from(sx)}}));if(p.sufficient){const t=await(async e=>{let t=[],n=[];const r=[],i=[];for(const t of e)t.type===VN.TRANSACTION&&(t.purpose===HN.APPROVAL&&r.push(t.buildTransaction()),t.purpose===HN.FULFILL_ORDER&&i.push(t.buildTransaction()));return t=await Promise.all(r),n=await Promise.all(i),{approvalTransactions:t,fulfillmentTransactions:n}})(a.actions),r=await zP(n,t.approvalTransactions);if(r.type===HP.FAILED)return{status:e.CheckoutStatus.FAILED,transactionHash:r.transactionHash,reason:r.reason,smartCheckoutResult:p};const o=((e,t,n)=>{let r;for(const e of n)e.type===VN.SIGNABLE&&e.purpose===zN.CREATE_LISTING&&(r={domain:e.message.domain,types:e.message.types,value:e.message.value});if(r)return{orderHash:e,orderComponents:t,unsignedMessage:r}})(a.orderHash,a.orderComponents,a.actions);if(!o)throw new lm("The unsigned message is missing after preparing the listing",e.CheckoutErrorType.SIGN_MESSAGE_ERROR,{id:u.id,collectionAddress:u.collectionAddress});const s=await(async(t,n)=>{try{const e=await t.getSigner()._signTypedData(n.unsignedMessage.domain,n.unsignedMessage.types,n.unsignedMessage.value);return{orderComponents:n.orderComponents,orderHash:n.orderHash,signedMessage:e}}catch(t){throw new lm("An error occurred while signing the message",e.CheckoutErrorType.SIGN_MESSAGE_ERROR,{message:t.message})}})(n,o);let f="";const h={orderComponents:s.orderComponents,orderHash:s.orderHash,orderSignature:s.signedMessage,makerFees:[]};if(void 0!==c){const t=JP(c,d.amount,l);if(t.length!==c.length)throw new lm("One of the fees is too small, must be greater than 0.000001",e.CheckoutErrorType.CREATE_ORDER_LISTING_ERROR);h.makerFees=t}try{f=(await i.createListing(h)).result.id}catch(t){throw new lm("An error occurred while creating the listing",e.CheckoutErrorType.CREATE_ORDER_LISTING_ERROR,{message:t.message,collectionId:u.id,collectionAddress:u.collectionAddress})}return{status:e.CheckoutStatus.SUCCESS,orderIds:[f],smartCheckoutResult:p}}return{status:e.CheckoutStatus.INSUFFICIENT_FUNDS,smartCheckoutResult:p}};class eM{config;constructor(e){this.config=e}async feeEstimate(){const e=await this.config.remote.getConfig("onramp");return e[Fh.TRANSAK]?.fees}async createWidgetUrl(e){return await this.getTransakWidgetUrl(e)}async getTransakWidgetUrl(e){let t=`${Yh[this.config.environment]}?`;if(t+=`${`apiKey=${(await this.config.remote.getConfig("onramp"))[Fh.TRANSAK].publishableApiKey}`}&network=immutablezkevm&defaultPaymentMethod=credit_debit_card&disablePaymentMethods=sepa_bank_transfer,gbp_bank_transfer,pm_cash_app,pm_jwire,pm_paymaya,pm_bpi,pm_ubp,pm_grabpay,pm_shopeepay,pm_gcash,pm_pix,pm_astropay,pm_pse,inr_bank_transfer&productsAvailed=buy&exchangeScreenTitle=Buy&themeColor=0D0D0D`,e.isPassport&&e.email){t+=`&email=${encodeURIComponent(e.email)}&isAutoFillUserData=true&disableWalletAddressForm=true`}return e.tokenAmount&&e.tokenSymbol?t+=`&defaultCryptoAmount=${e.tokenAmount}&cryptoCurrencyCode=${e.tokenSymbol}`:t+="&defaultCryptoCurrency=IMX",e.walletAddress&&(t+=`&walletAddress=${e.walletAddress}`),t}}async function tM(t,n){const r=[];n.forEach((n=>{if(n.type===e.ItemType.ERC20){const{contractAddress:e}=n;r.push((i=e,a=tm,o=t,new vl(i,a,o)).decimals())}var i,a,o}));const i=await Promise.all(r),a=n.map(((t,n)=>t.type===e.ItemType.NATIVE?{...t,amount:kh(t.amount,18)}:t.type===e.ItemType.ERC20?{...t,amount:kh(t.amount,i[n])}:t));return a}const nM=()=>"0.31.0";function rM(e){if(void 0===window)throw new Error("missing window object: please run Checkout client side");if(void 0===document)throw new Error("missing document object: please run Checkout client side");const t="immutable-checkout-widgets-bundle",n=function(e){const t=nM();if(void 0===e||void 0===e.major)return t;if(!Number.isInteger(e.major)||e.major<0)return t;if(void 0!==e.minor&&e.minor<0)return t;if(void 0!==e.patch&&e.patch<0)return t;if(0===e.major&&void 0===e.minor)return t;if(0===e.major&&0===e.minor&&void 0===e.patch)return t;if(0===e.major&&void 0===e.minor&&void 0===e.patch)return t;if(0===e.major&&0===e.minor&&0===e.patch)return t;let n=e.major.toString();return void 0===e.minor||(Number.isInteger(e.minor)&&(n+=`.${e.minor.toString()}`),void 0===e.patch||(Number.isInteger(e.patch)&&(n+=`.${e.patch.toString()}`),void 0===e.prerelease||"alpha"!==e.prerelease||("alpha"===e.prerelease&&(n+=`-${e.prerelease}`),void 0===e.build||Number.isInteger(e.build)&&e.build>=0&&(n+=`.${e.build.toString()}`)))),n}(e),r=document.getElementById(t);if(r)return{loaded:!0,element:r};const i=document.createElement("script");let a=`https://cdn.jsdelivr.net/npm/@imtbl/sdk@${n}/dist/browser/checkout/widgets.js`;return i.setAttribute("id",t),i.setAttribute("data-version",n),i.setAttribute("src",a),document.head.appendChild(i),{loaded:!1,element:i}}const iM={baseConfig:{environment:st.SANDBOX},passport:void 0};e.CHECKOUT_API_BASE_URL=Jh,e.Checkout=class{readOnlyProviders;config;fiatRampService;availability;passport;constructor(e=iM){this.config=new wm(e),this.fiatRampService=new eM(this.config),this.readOnlyProviders=new Map,this.availability=fP(this.config.isDevelopment,this.config.isProduction),this.passport=e.passport}async widgets(t){const n=this,r=new Promise(((r,i)=>{try{rM(t.version).loaded&&"undefined"!=typeof ImmutableCheckoutWidgets?(console.warn("Checkout widgets script is already loaded"),r(new ImmutableCheckoutWidgets.WidgetsFactory(n,t.config))):function e(){"undefined"!=typeof ImmutableCheckoutWidgets?r(new ImmutableCheckoutWidgets.WidgetsFactory(n,t.config)):setTimeout(e,100)}()}catch(t){i(new lm("Failed to load widgets script",e.CheckoutErrorType.WIDGETS_SCRIPT_LOAD_ERROR,{message:t.message}))}}));return r}async createProvider(e){return await xm(e.walletProviderName,this.passport)}async checkIsWalletConnected(t){return async function(t){if(!t?.provider?.request)throw new lm("Check wallet connection request failed",e.CheckoutErrorType.PROVIDER_REQUEST_FAILED_ERROR,{rpcMethod:qh.CHECK_CONNECTION});let n=[];try{n=await t.provider.request({method:qh.CHECK_CONNECTION,params:[]})}catch(t){throw new lm("Check wallet connection request failed",e.CheckoutErrorType.PROVIDER_REQUEST_FAILED_ERROR,{rpcMethod:qh.CHECK_CONNECTION})}return{isConnected:n&&n.length>0,walletAddress:n[0]??""}}(await Mm(this.config,t.provider,{allowUnsupportedProvider:!0}))}async connect(t){const n=await Mm(this.config,t.provider,{allowUnsupportedProvider:!0});return await async function(t){if(!t||!t.provider?.request)throw new lm("Incompatible provider",e.CheckoutErrorType.PROVIDER_REQUEST_MISSING_ERROR,{details:"Attempting to connect with an incompatible provider"});return await dm((async()=>{t.provider.request&&await t.provider.request({method:qh.CONNECT,params:[]})}),{type:e.CheckoutErrorType.USER_REJECTED_REQUEST_ERROR}),t}(n),{provider:n}}async switchNetwork(e){const t=await Mm(this.config,e.provider,{allowUnsupportedProvider:!0,allowMistmatchedChainId:!0});return await mm(this.config,t,e.chainId)}async getBalance(e){const t=await Mm(this.config,e.provider);return e.contractAddress&&""!==e.contractAddress?await Cm(t,e.walletAddress,e.contractAddress):await Rm(this.config,t,e.walletAddress)}async getAllBalances(e){const t=await Mm(this.config,e.provider);return Om(this.config,t,e.walletAddress,e.chainId)}async getNetworkAllowList(e){return await pm(this.config,e)}async getTokenAllowList(e){return await Tm(this.config,e)}async getWalletAllowList(t){return await async function(t){const n=[],r=t.exclude?.map((e=>e.walletProviderName))??[];let i=Object.values(e.WalletProviderName);0!==r.length&&(i=i.filter((e=>!r.includes(e))));for(const e of i)n.push({walletProviderName:e});return{wallets:n}}(t)}async sendTransaction(t){const n=await Mm(this.config,t.provider);return await(async(t,n)=>{try{return{transactionResponse:await t.getSigner().sendTransaction(n)}}catch(t){if(t.code===En.INSUFFICIENT_FUNDS)throw new lm(t.message,e.CheckoutErrorType.INSUFFICIENT_FUNDS);if(t.code===En.ACTION_REJECTED)throw new lm(t.message,e.CheckoutErrorType.USER_REJECTED_REQUEST_ERROR);if(t.code===En.UNPREDICTABLE_GAS_LIMIT)throw new lm(t.message,e.CheckoutErrorType.UNPREDICTABLE_GAS_LIMIT);throw new lm(t.message,e.CheckoutErrorType.TRANSACTION_FAILED)}})(n,t.transaction)}async getNetworkInfo(e){const t=await Mm(this.config,e.provider,{allowUnsupportedProvider:!0,allowMistmatchedChainId:!0});return await hm(this.config,t)}async buy(e){e.orders.length>1&&console.warn("This endpoint currently only processes the first order in the array.");const t=await Mm(this.config,e.provider);return await QP(this.config,t,e.orders)}async sell(e){e.orders.length>1&&console.warn("This endpoint currently only processes the first order in the array.");const t=await Mm(this.config,e.provider);return await $P(this.config,t,e.orders)}async cancel(t){console.warn("This endpoint currently only processes the first order in the array.");const n=await Mm(this.config,t.provider);return await(async(t,n,r)=>{let i;if(0===r.length)throw new lm("No orderIds were provided to the orderIds array. Please provide at least one orderId.",e.CheckoutErrorType.CANCEL_ORDER_LISTING_ERROR);const a=r[0];try{const e=await Im(t,"Time to get the address from the provider",n.getSigner().getAddress()),r=Kx(t),o=await Im(t,"Time to get the cancel order from the orderbook",r.cancelOrdersOnChain([a],e));i=await o.cancellationAction.buildTransaction()}catch(t){throw new lm("An error occurred while cancelling the order listing",e.CheckoutErrorType.CANCEL_ORDER_LISTING_ERROR,{orderId:a,message:t.message})}const o=await VP(n,[i]);return o.type===HP.FAILED?{status:e.CheckoutStatus.FAILED,transactionHash:o.transactionHash,reason:o.reason}:{status:e.CheckoutStatus.SUCCESS}})(this.config,n,t.orderIds)}async smartCheckout(t){const n=await Mm(this.config,t.provider);let r=[];try{r=await tM(n,t.itemRequirements)}catch{throw new lm("Failed to map item requirements",e.CheckoutErrorType.ITEM_REQUIREMENTS_ERROR)}return await GP(this.config,n,r,t.transactionOrGasAmount)}static isWeb3Provider(e){return Pm(e)}async gasEstimate(e){return this.readOnlyProviders=await mP(this.config,this.readOnlyProviders),await Zx(e,this.readOnlyProviders,this.config)}async createFiatRampUrl(t){let n,r,i="IMX";const a=await t.web3Provider.getSigner().getAddress(),o=t.web3Provider.provider?.isPassport||!1;if(o&&t.passport){const e=await t.passport.getUserInfo();r=e?.email}const s=await Tm(this.config,{type:e.TokenFilterTypes.ONRAMP}),u=s.tokens?.find((e=>e.address?.toLowerCase()===t.tokenAddress?.toLowerCase()));return u&&(n=t.tokenAmount,i=u.symbol),await this.fiatRampService.createWidgetUrl({exchangeType:t.exchangeType,isPassport:o,walletAddress:a,tokenAmount:n,tokenSymbol:i,email:r})}async getExchangeFeeEstimate(){return await this.fiatRampService.feeEstimate()}async isSwapAvailable(){return this.availability.checkDexAvailability()}},e.CheckoutConfiguration=wm}));
|
|
35
|
+
function(e){var t=n,r=t.lib,i=r.WordArray,a=r.Hasher,o=t.algo,s=i.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),u=i.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),c=i.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),l=i.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),d=i.create([0,1518500249,1859775393,2400959708,2840853838]),f=i.create([1352829926,1548603684,1836072691,2053994217,0]),p=o.RIPEMD160=a.extend({_doReset:function(){this._hash=i.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var n=0;n<16;n++){var r=t+n,i=e[r];e[r]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var a,o,p,w,T,A,E,_,I,R,C,k=this._hash.words,O=d.words,S=f.words,N=s.words,x=u.words,P=c.words,M=l.words;for(A=a=k[0],E=o=k[1],_=p=k[2],I=w=k[3],R=T=k[4],n=0;n<80;n+=1)C=a+e[t+N[n]]|0,C+=n<16?h(o,p,w)+O[0]:n<32?m(o,p,w)+O[1]:n<48?y(o,p,w)+O[2]:n<64?g(o,p,w)+O[3]:b(o,p,w)+O[4],C=(C=v(C|=0,P[n]))+T|0,a=T,T=w,w=v(p,10),p=o,o=C,C=A+e[t+x[n]]|0,C+=n<16?b(E,_,I)+S[0]:n<32?g(E,_,I)+S[1]:n<48?y(E,_,I)+S[2]:n<64?m(E,_,I)+S[3]:h(E,_,I)+S[4],C=(C=v(C|=0,M[n]))+R|0,A=R,R=I,I=v(_,10),_=E,E=C;C=k[1]+p+I|0,k[1]=k[2]+w+R|0,k[2]=k[3]+T+A|0,k[3]=k[4]+a+E|0,k[4]=k[0]+o+_|0,k[0]=C},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),e.sigBytes=4*(t.length+1),this._process();for(var i=this._hash,a=i.words,o=0;o<5;o++){var s=a[o];a[o]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8)}return i},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}});function h(e,t,n){return e^t^n}function m(e,t,n){return e&t|~e&n}function y(e,t,n){return(e|~t)^n}function g(e,t,n){return e&n|t&~n}function b(e,t,n){return e^(t|~n)}function v(e,t){return e<<t|e>>>32-t}t.RIPEMD160=a._createHelper(p),t.HmacRIPEMD160=a._createHmacHelper(p)}(),n.RIPEMD160)}(nO)),aO(),oO||(oO=1,function(e,t){var n;e.exports=(n=bk(),aO(),function(){var e=n,t=e.lib,r=t.Base,i=t.WordArray,a=e.algo,o=a.SHA256,s=a.HMAC,u=a.PBKDF2=r.extend({cfg:r.extend({keySize:4,hasher:o,iterations:25e4}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=this.cfg,r=s.create(n.hasher,e),a=i.create(),o=i.create([1]),u=a.words,c=o.words,l=n.keySize,d=n.iterations;u.length<l;){var f=r.update(t).finalize(o);r.reset();for(var p=f.words,h=p.length,m=f,y=1;y<d;y++){m=r.finalize(m),r.reset();for(var g=m.words,b=0;b<h;b++)p[b]^=g[b]}a.concat(f),c[0]++}return a.sigBytes=4*l,a}});e.PBKDF2=function(e,t,n){return u.create(n).compute(e,t)}}(),n.PBKDF2)}(sO)),lO(),pO(),yO(),vO(),AO(),IO(),RO||(RO=1,function(e,t){var n,r;e.exports=(r=bk(),pO(),r.mode.ECB=((n=r.lib.BlockCipherMode.extend()).Encryptor=n.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),n.Decryptor=n.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),n),r.mode.ECB)}(CO)),kO||(kO=1,function(e,t){var n;e.exports=(n=bk(),pO(),n.pad.AnsiX923={pad:function(e,t){var n=e.sigBytes,r=4*t,i=r-n%r,a=n+i-1;e.clamp(),e.words[a>>>2]|=i<<24-a%4*8,e.sigBytes+=i},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},n.pad.Ansix923)}(OO)),SO||(SO=1,function(e,t){var n;e.exports=(n=bk(),pO(),n.pad.Iso10126={pad:function(e,t){var r=4*t,i=r-e.sigBytes%r;e.concat(n.lib.WordArray.random(i-1)).concat(n.lib.WordArray.create([i<<24],1))},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},n.pad.Iso10126)}(NO)),xO||(xO=1,function(e,t){var n;e.exports=(n=bk(),pO(),n.pad.Iso97971={pad:function(e,t){e.concat(n.lib.WordArray.create([2147483648],1)),n.pad.ZeroPadding.pad(e,t)},unpad:function(e){n.pad.ZeroPadding.unpad(e),e.sigBytes--}},n.pad.Iso97971)}(PO)),MO||(MO=1,function(e,t){var n;e.exports=(n=bk(),pO(),n.pad.ZeroPadding={pad:function(e,t){var n=4*t;e.clamp(),e.sigBytes+=n-(e.sigBytes%n||n)},unpad:function(e){var t=e.words,n=e.sigBytes-1;for(n=e.sigBytes-1;n>=0;n--)if(t[n>>>2]>>>24-n%4*8&255){e.sigBytes=n+1;break}}},n.pad.ZeroPadding)}(BO)),DO||(DO=1,function(e,t){var n;e.exports=(n=bk(),pO(),n.pad.NoPadding={pad:function(){},unpad:function(){}},n.pad.NoPadding)}(FO)),LO||(LO=1,function(e,t){var n,r,i,a;e.exports=(a=bk(),pO(),r=(n=a).lib.CipherParams,i=n.enc.Hex,n.format.Hex={stringify:function(e){return e.ciphertext.toString(i)},parse:function(e){var t=i.parse(e);return r.create({ciphertext:t})}},a.format.Hex)}(UO)),qO||(qO=1,function(e,t){var n;e.exports=(n=bk(),Bk(),jk(),lO(),pO(),function(){var e=n,t=e.lib.BlockCipher,r=e.algo,i=[],a=[],o=[],s=[],u=[],c=[],l=[],d=[],f=[],p=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var n=0,r=0;for(t=0;t<256;t++){var h=r^r<<1^r<<2^r<<3^r<<4;h=h>>>8^255&h^99,i[n]=h,a[h]=n;var m=e[n],y=e[m],g=e[y],b=257*e[h]^16843008*h;o[n]=b<<24|b>>>8,s[n]=b<<16|b>>>16,u[n]=b<<8|b>>>24,c[n]=b,b=16843009*g^65537*y^257*m^16843008*n,l[h]=b<<24|b>>>8,d[h]=b<<16|b>>>16,f[h]=b<<8|b>>>24,p[h]=b,n?(n=m^e[e[e[g^m]]],r^=e[e[r]]):n=r=1}}();var h=[0,1,2,4,8,16,32,64,128,27,54],m=r.AES=t.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,n=e.sigBytes/4,r=4*((this._nRounds=n+6)+1),a=this._keySchedule=[],o=0;o<r;o++)o<n?a[o]=t[o]:(c=a[o-1],o%n?n>6&&o%n==4&&(c=i[c>>>24]<<24|i[c>>>16&255]<<16|i[c>>>8&255]<<8|i[255&c]):(c=i[(c=c<<8|c>>>24)>>>24]<<24|i[c>>>16&255]<<16|i[c>>>8&255]<<8|i[255&c],c^=h[o/n|0]<<24),a[o]=a[o-n]^c);for(var s=this._invKeySchedule=[],u=0;u<r;u++){if(o=r-u,u%4)var c=a[o];else c=a[o-4];s[u]=u<4||o<=4?c:l[i[c>>>24]]^d[i[c>>>16&255]]^f[i[c>>>8&255]]^p[i[255&c]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,o,s,u,c,i)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,l,d,f,p,a),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,r,i,a,o,s){for(var u=this._nRounds,c=e[t]^n[0],l=e[t+1]^n[1],d=e[t+2]^n[2],f=e[t+3]^n[3],p=4,h=1;h<u;h++){var m=r[c>>>24]^i[l>>>16&255]^a[d>>>8&255]^o[255&f]^n[p++],y=r[l>>>24]^i[d>>>16&255]^a[f>>>8&255]^o[255&c]^n[p++],g=r[d>>>24]^i[f>>>16&255]^a[c>>>8&255]^o[255&l]^n[p++],b=r[f>>>24]^i[c>>>16&255]^a[l>>>8&255]^o[255&d]^n[p++];c=m,l=y,d=g,f=b}m=(s[c>>>24]<<24|s[l>>>16&255]<<16|s[d>>>8&255]<<8|s[255&f])^n[p++],y=(s[l>>>24]<<24|s[d>>>16&255]<<16|s[f>>>8&255]<<8|s[255&c])^n[p++],g=(s[d>>>24]<<24|s[f>>>16&255]<<16|s[c>>>8&255]<<8|s[255&l])^n[p++],b=(s[f>>>24]<<24|s[c>>>16&255]<<16|s[l>>>8&255]<<8|s[255&d])^n[p++],e[t]=m,e[t+1]=y,e[t+2]=g,e[t+3]=b},keySize:8});e.AES=t._createHelper(m)}(),n.AES)}(jO)),zO(),VO||(VO=1,function(e,t){var n;e.exports=(n=bk(),Bk(),jk(),lO(),pO(),function(){var e=n,t=e.lib.StreamCipher,r=e.algo,i=r.RC4=t.extend({_doReset:function(){for(var e=this._key,t=e.words,n=e.sigBytes,r=this._S=[],i=0;i<256;i++)r[i]=i;i=0;for(var a=0;i<256;i++){var o=i%n,s=t[o>>>2]>>>24-o%4*8&255;a=(a+r[i]+s)%256;var u=r[i];r[i]=r[a],r[a]=u}this._i=this._j=0},_doProcessBlock:function(e,t){e[t]^=a.call(this)},keySize:8,ivSize:0});function a(){for(var e=this._S,t=this._i,n=this._j,r=0,i=0;i<4;i++){n=(n+e[t=(t+1)%256])%256;var a=e[t];e[t]=e[n],e[n]=a,r|=e[(e[t]+e[n])%256]<<24-8*i}return this._i=t,this._j=n,r}e.RC4=t._createHelper(i);var o=r.RC4Drop=i.extend({cfg:i.cfg.extend({drop:192}),_doReset:function(){i._doReset.call(this);for(var e=this.cfg.drop;e>0;e--)a.call(this)}});e.RC4Drop=t._createHelper(o)}(),n.RC4)}(WO)),KO||(KO=1,function(e,t){var n;e.exports=(n=bk(),Bk(),jk(),lO(),pO(),function(){var e=n,t=e.lib.StreamCipher,r=e.algo,i=[],a=[],o=[],s=r.Rabbit=t.extend({_doReset:function(){for(var e=this._key.words,t=this.cfg.iv,n=0;n<4;n++)e[n]=16711935&(e[n]<<8|e[n]>>>24)|4278255360&(e[n]<<24|e[n]>>>8);var r=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],i=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];for(this._b=0,n=0;n<4;n++)u.call(this);for(n=0;n<8;n++)i[n]^=r[n+4&7];if(t){var a=t.words,o=a[0],s=a[1],c=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),l=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=c>>>16|4294901760&l,f=l<<16|65535&c;for(i[0]^=c,i[1]^=d,i[2]^=l,i[3]^=f,i[4]^=c,i[5]^=d,i[6]^=l,i[7]^=f,n=0;n<4;n++)u.call(this)}},_doProcessBlock:function(e,t){var n=this._X;u.call(this),i[0]=n[0]^n[5]>>>16^n[3]<<16,i[1]=n[2]^n[7]>>>16^n[5]<<16,i[2]=n[4]^n[1]>>>16^n[7]<<16,i[3]=n[6]^n[3]>>>16^n[1]<<16;for(var r=0;r<4;r++)i[r]=16711935&(i[r]<<8|i[r]>>>24)|4278255360&(i[r]<<24|i[r]>>>8),e[t+r]^=i[r]},blockSize:4,ivSize:2});function u(){for(var e=this._X,t=this._C,n=0;n<8;n++)a[n]=t[n];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0<a[0]>>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0<a[1]>>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0<a[2]>>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0<a[3]>>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0<a[4]>>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0<a[5]>>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0<a[6]>>>0?1:0)|0,this._b=t[7]>>>0<a[7]>>>0?1:0,n=0;n<8;n++){var r=e[n]+t[n],i=65535&r,s=r>>>16,u=((i*i>>>17)+i*s>>>15)+s*s,c=((4294901760&r)*r|0)+((65535&r)*r|0);o[n]=u^c}e[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,e[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,e[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,e[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,e[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,e[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,e[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,e[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.Rabbit=t._createHelper(s)}(),n.Rabbit)}(XO)),JO||(JO=1,function(e,t){var n;e.exports=(n=bk(),Bk(),jk(),lO(),pO(),function(){var e=n,t=e.lib.StreamCipher,r=e.algo,i=[],a=[],o=[],s=r.RabbitLegacy=t.extend({_doReset:function(){var e=this._key.words,t=this.cfg.iv,n=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],r=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];this._b=0;for(var i=0;i<4;i++)u.call(this);for(i=0;i<8;i++)r[i]^=n[i+4&7];if(t){var a=t.words,o=a[0],s=a[1],c=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),l=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),d=c>>>16|4294901760&l,f=l<<16|65535&c;for(r[0]^=c,r[1]^=d,r[2]^=l,r[3]^=f,r[4]^=c,r[5]^=d,r[6]^=l,r[7]^=f,i=0;i<4;i++)u.call(this)}},_doProcessBlock:function(e,t){var n=this._X;u.call(this),i[0]=n[0]^n[5]>>>16^n[3]<<16,i[1]=n[2]^n[7]>>>16^n[5]<<16,i[2]=n[4]^n[1]>>>16^n[7]<<16,i[3]=n[6]^n[3]>>>16^n[1]<<16;for(var r=0;r<4;r++)i[r]=16711935&(i[r]<<8|i[r]>>>24)|4278255360&(i[r]<<24|i[r]>>>8),e[t+r]^=i[r]},blockSize:4,ivSize:2});function u(){for(var e=this._X,t=this._C,n=0;n<8;n++)a[n]=t[n];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0<a[0]>>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0<a[1]>>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0<a[2]>>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0<a[3]>>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0<a[4]>>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0<a[5]>>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0<a[6]>>>0?1:0)|0,this._b=t[7]>>>0<a[7]>>>0?1:0,n=0;n<8;n++){var r=e[n]+t[n],i=65535&r,s=r>>>16,u=((i*i>>>17)+i*s>>>15)+s*s,c=((4294901760&r)*r|0)+((65535&r)*r|0);o[n]=u^c}e[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,e[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,e[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,e[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,e[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,e[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,e[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,e[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.RabbitLegacy=t._createHelper(s)}(),n.RabbitLegacy)}(YO)),$O(),n)}(_k);var eS=_k.exports,tS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ek,"__esModule",{value:!0}),Ek.Base=void 0;const nS=hn,rS=tS(eS);class iS{print(){iS.print(this)}bufferIndexOf(e,t,n=!1){if(n)return this.binarySearch(e,t,nS.Buffer.compare);return this.linearSearch(e,t,((e,t)=>e.equals(t)))}static binarySearch(e,t,n){let r=0,i=e.length-1;for(;r<=i;){const a=Math.floor((r+i)/2),o=n(e[a],t);if(0===o){for(let r=a-1;r>=0;r--)if(0!==n(e[r],t))return r+1;return 0}o<0?r=a+1:i=a-1}return-1}binarySearch(e,t,n){return iS.binarySearch(e,t,n)}static linearSearch(e,t,n){for(let r=0;r<e.length;r++)if(n(e[r],t))return r;return-1}linearSearch(e,t,n){return iS.linearSearch(e,t,n)}static bufferify(e){if(!nS.Buffer.isBuffer(e)){if("object"==typeof e&&e.words)return nS.Buffer.from(e.toString(rS.default.enc.Hex),"hex");if(iS.isHexString(e))return nS.Buffer.from(e.replace(/^0x/,""),"hex");if("string"==typeof e)return nS.Buffer.from(e);if("bigint"==typeof e)return nS.Buffer.from(e.toString(16),"hex");if(e instanceof Uint8Array)return nS.Buffer.from(e.buffer);if("number"==typeof e){let t=e.toString();return t.length%2&&(t=`0${t}`),nS.Buffer.from(t,"hex")}if(ArrayBuffer.isView(e))return nS.Buffer.from(e.buffer,e.byteOffset,e.byteLength)}return e}bigNumberify(e){return iS.bigNumberify(e)}static bigNumberify(e){if("bigint"==typeof e)return e;if("string"==typeof e)return e.startsWith("0x")&&iS.isHexString(e)?BigInt("0x"+e.replace("0x","").toString()):BigInt(e);if(nS.Buffer.isBuffer(e))return BigInt("0x"+e.toString("hex"));if(e instanceof Uint8Array)return BigInt(e);if("number"==typeof e)return BigInt(e);throw new Error("cannot bigNumberify")}static isHexString(e){return"string"==typeof e&&/^(0x)?[0-9A-Fa-f]*$/.test(e)}static print(e){console.log(e.toString())}bufferToHex(e,t=!0){return iS.bufferToHex(e,t)}static bufferToHex(e,t=!0){return`${t?"0x":""}${(e||nS.Buffer.alloc(0)).toString("hex")}`}bufferify(e){return iS.bufferify(e)}bufferifyFn(e){return t=>{const n=e(t);return nS.Buffer.isBuffer(n)?n:this.isHexString(n)?nS.Buffer.from(n.replace("0x",""),"hex"):"string"==typeof n?nS.Buffer.from(n):"bigint"==typeof n?nS.Buffer.from(t.toString(16),"hex"):ArrayBuffer.isView(n)?nS.Buffer.from(n.buffer,n.byteOffset,n.byteLength):nS.Buffer.from(e(rS.default.enc.Hex.parse(t.toString("hex"))).toString(rS.default.enc.Hex),"hex")}}isHexString(e){return iS.isHexString(e)}log2(e){return 1===e?0:1+this.log2(e/2|0)}zip(e,t){return e.map(((e,n)=>[e,t[n]]))}static hexZeroPad(e,t){return"0x"+e.replace("0x","").padStart(t,"0")}}Ek.Base=iS,Ek.default=iS;var aS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(pk,"__esModule",{value:!0}),pk.MerkleTree=void 0;const oS=hn,sS=aS((function(e){for(var t=new Buffer(e.length),n=0,r=e.length-1;n<=r;++n,--r)t[n]=e[r],t[r]=e[n];return t})),uS=aS(vk),cS=aS(Ak),lS=aS(Ek);let dS=class e extends lS.default{constructor(e,t=uS.default,n={}){if(super(),this.duplicateOdd=!1,this.concatenator=oS.Buffer.concat,this.hashLeaves=!1,this.isBitcoinTree=!1,this.leaves=[],this.layers=[],this.sortLeaves=!1,this.sortPairs=!1,this.sort=!1,this.fillDefaultHash=null,this.complete=!1,n.complete){if(n.isBitcoinTree)throw new Error('option "complete" is incompatible with "isBitcoinTree"');if(n.duplicateOdd)throw new Error('option "complete" is incompatible with "duplicateOdd"')}if(this.isBitcoinTree=!!n.isBitcoinTree,this.hashLeaves=!!n.hashLeaves,this.sortLeaves=!!n.sortLeaves,this.sortPairs=!!n.sortPairs,this.complete=!!n.complete,n.fillDefaultHash)if("function"==typeof n.fillDefaultHash)this.fillDefaultHash=n.fillDefaultHash;else{if(!oS.Buffer.isBuffer(n.fillDefaultHash)&&"string"!=typeof n.fillDefaultHash)throw new Error('method "fillDefaultHash" must be a function, Buffer, or string');this.fillDefaultHash=(e,t)=>n.fillDefaultHash}this.sort=!!n.sort,this.sort&&(this.sortLeaves=!0,this.sortPairs=!0),this.duplicateOdd=!!n.duplicateOdd,n.concatenator&&(this.concatenator=n.concatenator),this.hashFn=this.bufferifyFn(t),this.processLeaves(e)}getOptions(){var e,t;return{complete:this.complete,isBitcoinTree:this.isBitcoinTree,hashLeaves:this.hashLeaves,sortLeaves:this.sortLeaves,sortPairs:this.sortPairs,sort:this.sort,fillDefaultHash:null!==(t=null===(e=this.fillDefaultHash)||void 0===e?void 0:e.toString())&&void 0!==t?t:null,duplicateOdd:this.duplicateOdd}}processLeaves(e){if(this.hashLeaves&&(e=e.map(this.hashFn)),this.leaves=e.map(this.bufferify),this.sortLeaves&&(this.leaves=this.leaves.sort(oS.Buffer.compare)),this.fillDefaultHash)for(let e=this.leaves.length;e<Math.pow(2,Math.ceil(Math.log2(this.leaves.length)));e++)this.leaves.push(this.bufferify(this.fillDefaultHash(e,this.hashFn)));this.createHashes(this.leaves)}createHashes(e){for(this.layers=[e];e.length>1;){const t=this.layers.length;this.layers.push([]);const n=this.complete&&1===t&&!Number.isInteger(Math.log2(e.length))?2*e.length-Math.pow(2,Math.ceil(Math.log2(e.length))):e.length;for(let r=0;r<e.length;r+=2){if(r>=n){this.layers[t].push(...e.slice(n));break}if(r+1===e.length&&e.length%2==1){const n=e[e.length-1];let i=n;if(this.isBitcoinTree){i=this.hashFn(this.concatenator([sS.default(n),sS.default(n)])),i=sS.default(this.hashFn(i)),this.layers[t].push(i);continue}if(!this.duplicateOdd){this.layers[t].push(e[r]);continue}}const i=e[r],a=r+1===e.length?i:e[r+1];let o=null;o=this.isBitcoinTree?[sS.default(i),sS.default(a)]:[i,a],this.sortPairs&&o.sort(oS.Buffer.compare);let s=this.hashFn(this.concatenator(o));this.isBitcoinTree&&(s=sS.default(this.hashFn(s))),this.layers[t].push(s)}e=this.layers[t]}}addLeaf(e,t=!1){t&&(e=this.hashFn(e)),this.processLeaves(this.leaves.concat(e))}addLeaves(e,t=!1){t&&(e=e.map(this.hashFn)),this.processLeaves(this.leaves.concat(e))}getLeaves(e){return Array.isArray(e)?(this.hashLeaves&&(e=e.map(this.hashFn),this.sortLeaves&&(e=e.sort(oS.Buffer.compare))),this.leaves.filter((t=>-1!==this.bufferIndexOf(e,t,this.sortLeaves)))):this.leaves}getLeaf(e){return e<0||e>this.leaves.length-1?oS.Buffer.from([]):this.leaves[e]}getLeafIndex(e){e=this.bufferify(e);const t=this.getLeaves();for(let n=0;n<t.length;n++){if(t[n].equals(e))return n}return-1}getLeafCount(){return this.leaves.length}getHexLeaves(){return this.leaves.map((e=>this.bufferToHex(e)))}static marshalLeaves(t){return JSON.stringify(t.map((t=>e.bufferToHex(t))),null,2)}static unmarshalLeaves(t){let n=null;if("string"==typeof t)n=JSON.parse(t);else{if(!(t instanceof Object))throw new Error("Expected type of string or object");n=t}if(!n)return[];if(!Array.isArray(n))throw new Error("Expected JSON string to be array");return n.map(e.bufferify)}getLayers(){return this.layers}getHexLayers(){return this.layers.reduce(((e,t)=>(Array.isArray(t)?e.push(t.map((e=>this.bufferToHex(e)))):e.push(t),e)),[])}getLayersFlat(){const e=this.layers.reduce(((e,t)=>(Array.isArray(t)?e.unshift(...t):e.unshift(t),e)),[]);return e.unshift(oS.Buffer.from([0])),e}getHexLayersFlat(){return this.getLayersFlat().map((e=>this.bufferToHex(e)))}getLayerCount(){return this.getLayers().length}getRoot(){return 0===this.layers.length?oS.Buffer.from([]):this.layers[this.layers.length-1][0]||oS.Buffer.from([])}getHexRoot(){return this.bufferToHex(this.getRoot())}getProof(e,t){if(void 0===e)throw new Error("leaf is required");e=this.bufferify(e);const n=[];if(!Number.isInteger(t)){t=-1;for(let n=0;n<this.leaves.length;n++)0===oS.Buffer.compare(e,this.leaves[n])&&(t=n)}if(t<=-1)return[];for(let e=0;e<this.layers.length;e++){const r=this.layers[e],i=t%2,a=i?t-1:this.isBitcoinTree&&t===r.length-1&&e<this.layers.length-1?t:t+1;a<r.length&&n.push({position:i?"left":"right",data:r[a]}),t=t/2|0}return n}getHexProof(e,t){return this.getProof(e,t).map((e=>this.bufferToHex(e.data)))}getProofs(){const e=[];return this.getProofsDFS(this.layers.length-1,0,[],e),e}getProofsDFS(e,t,n,r){const i=t%2;if(-1===e)return void(i||r.push([...n].reverse()));if(t>=this.layers[e].length)return;const a=this.layers[e],o=i?t-1:t+1;let s=!1;o<a.length&&(s=!0,n.push({position:i?"left":"right",data:a[o]}));const u=2*t,c=2*t+1;this.getProofsDFS(e-1,u,n,r),this.getProofsDFS(e-1,c,n,r),s&&n.splice(n.length-1,1)}getHexProofs(){return this.getProofs().map((e=>this.bufferToHex(e.data)))}getPositionalHexProof(e,t){return this.getProof(e,t).map((e=>["left"===e.position?0:1,this.bufferToHex(e.data)]))}static marshalProof(t){const n=t.map((t=>"string"==typeof t?t:oS.Buffer.isBuffer(t)?e.bufferToHex(t):{position:t.position,data:e.bufferToHex(t.data)}));return JSON.stringify(n,null,2)}static unmarshalProof(t){let n=null;if("string"==typeof t)n=JSON.parse(t);else{if(!(t instanceof Object))throw new Error("Expected type of string or object");n=t}if(!n)return[];if(!Array.isArray(n))throw new Error("Expected JSON string to be array");return n.map((t=>{if("string"==typeof t)return e.bufferify(t);if(t instanceof Object)return{position:t.position,data:e.bufferify(t.data)};throw new Error("Expected item to be of type string or object")}))}static marshalTree(t){const n=t.getHexRoot(),r=t.leaves.map((t=>e.bufferToHex(t))),i=t.getHexLayers(),a=t.getOptions();return JSON.stringify({options:a,root:n,layers:i,leaves:r},null,2)}static unmarshalTree(t,n=uS.default,r={}){let i=null;if("string"==typeof t)i=JSON.parse(t);else{if(!(t instanceof Object))throw new Error("Expected type of string or object");i=t}if(!i)throw new Error("could not parse json");return r=Object.assign({},i.options||{},r),new e(i.leaves,n,r)}getProofIndices(e,t){const n=Math.pow(2,t);let r=new Set;for(const t of e){let e=n+t;for(;e>1;)r.add(1^e),e=e/2|0}const i=e.map((e=>n+e)),a=Array.from(r).sort(((e,t)=>e-t)).reverse();r=i.concat(a);const o=new Set,s=[];for(let e of r)if(!o.has(e))for(s.push(e);e>1&&(o.add(e),o.has(1^e));)e=e/2|0;return s.filter((t=>!e.includes(t-n)))}getProofIndicesForUnevenTree(e,t){const n=Math.ceil(Math.log2(t)),r=[];for(let e=0;e<n;e++){t%2!=0&&r.push({index:e,leavesCount:t}),t=Math.ceil(t/2)}const i=[];let a=e;for(let e=0;e<n;e++){const t=a.map((e=>e%2==0?e+1:e-1));let n=t.filter((e=>!a.includes(e)));const o=r.find((({index:t})=>t===e));o&&a.includes(o.leavesCount-1)&&(n=n.slice(0,-1)),i.push(n),a=[...new Set(a.map((e=>e%2==0?e/2:e%2==0?(e+1)/2:(e-1)/2)))]}return i}getMultiProof(e,t){this.complete||console.warn("Warning: For correct multiProofs it's strongly recommended to set complete: true"),t||(t=e,e=this.getLayersFlat());if(this.isUnevenTree()&&t.every(Number.isInteger))return this.getMultiProofForUnevenTree(t);if(!t.every(Number.isInteger)){let e=t;this.sortPairs&&(e=e.sort(oS.Buffer.compare));let n=e.map((e=>this.bufferIndexOf(this.leaves,e,this.sortLeaves))).sort(((e,t)=>e===t?0:e>t?1:-1));if(!n.every((e=>-1!==e)))throw new Error("Element does not exist in Merkle tree");const r=[],i=[];let a=[];for(let e=0;e<this.layers.length;e++){const t=this.layers[e];for(let e=0;e<n.length;e++){const o=n[e],s=this.getPairNode(t,o);r.push(t[o]),s&&i.push(s),a.push(o/2|0)}n=a.filter(((e,t,n)=>n.indexOf(e)===t)),a=[]}return i.filter((e=>!r.includes(e)))}return this.getProofIndices(t,Math.log2(e.length/2|0)).map((t=>e[t]))}getMultiProofForUnevenTree(e,t){t||(t=e,e=this.getLayers());let n=[],r=t;for(const t of e){const e=[];for(const n of r){if(n%2==0){const i=n+1;if(!r.includes(i)&&t[i]){e.push(t[i]);continue}}const i=n-1;r.includes(i)||!t[i]||e.push(t[i])}n=n.concat(e);const i=new Set;for(const e of r)e%2!=0?e%2!=0?i.add((e-1)/2):i.add((e+1)/2):i.add(e/2);r=Array.from(i)}return n}getHexMultiProof(e,t){return this.getMultiProof(e,t).map((e=>this.bufferToHex(e)))}getProofFlags(e,t){if(!Array.isArray(e)||e.length<=0)throw new Error("Invalid Inputs!");let n;if(n=e.every(Number.isInteger)?[...e].sort(((e,t)=>e===t?0:e>t?1:-1)):e.map((e=>this.bufferIndexOf(this.leaves,e,this.sortLeaves))).sort(((e,t)=>e===t?0:e>t?1:-1)),!n.every((e=>-1!==e)))throw new Error("Element does not exist in Merkle tree");const r=t.map((e=>this.bufferify(e))),i=[],a=[];for(let e=0;e<this.layers.length;e++){const t=this.layers[e];n=n.reduce(((e,n)=>{if(!i.includes(t[n])){const e=this.getPairNode(t,n),o=r.includes(t[n])||r.includes(e);e&&a.push(!o),i.push(t[n]),i.push(e)}return e.push(n/2|0),e}),[])}return a}verify(e,t,n){let r=this.bufferify(t);if(n=this.bufferify(n),!Array.isArray(e)||!t||!n)return!1;for(let t=0;t<e.length;t++){const n=e[t];let i=null,a=null;if("string"==typeof n)i=this.bufferify(n),a=!0;else if(Array.isArray(n))a=0===n[0],i=this.bufferify(n[1]);else if(oS.Buffer.isBuffer(n))i=n,a=!0;else{if(!(n instanceof Object))throw new Error("Expected node to be of type string or object");i=this.bufferify(n.data),a="left"===n.position}const o=[];this.isBitcoinTree?(o.push(sS.default(r)),o[a?"unshift":"push"](sS.default(i)),r=this.hashFn(this.concatenator(o)),r=sS.default(this.hashFn(r))):this.sortPairs?-1===oS.Buffer.compare(r,i)?(o.push(r,i),r=this.hashFn(this.concatenator(o))):(o.push(i,r),r=this.hashFn(this.concatenator(o))):(o.push(r),o[a?"unshift":"push"](i),r=this.hashFn(this.concatenator(o)))}return 0===oS.Buffer.compare(r,n)}verifyMultiProof(e,t,n,r,i){if(this.isUnevenTree())return this.verifyMultiProofForUnevenTree(e,t,n,r,i);const a=Math.ceil(Math.log2(r));e=this.bufferify(e),n=n.map((e=>this.bufferify(e))),i=i.map((e=>this.bufferify(e)));const o={};for(const[e,r]of this.zip(t,n))o[Math.pow(2,a)+e]=r;for(const[e,n]of this.zip(this.getProofIndices(t,a),i))o[e]=n;let s=Object.keys(o).map((e=>+e)).sort(((e,t)=>e-t));s=s.slice(0,s.length-1);let u=0;for(;u<s.length;){const e=s[u];if(e>=2&&{}.hasOwnProperty.call(o,1^e)){let t=[o[e-e%2],o[e-e%2+1]];this.sortPairs&&(t=t.sort(oS.Buffer.compare));const n=t[1]?this.hashFn(this.concatenator(t)):t[0];o[e/2|0]=n,s.push(e/2|0)}u+=1}return!t.length||{}.hasOwnProperty.call(o,1)&&o[1].equals(e)}verifyMultiProofWithFlags(e,t,n,r){e=this.bufferify(e),t=t.map(this.bufferify),n=n.map(this.bufferify);const i=t.length,a=r.length,o=[];let s=0,u=0,c=0;for(let e=0;e<a;e++){const a=[r[e]?s<i?t[s++]:o[u++]:n[c++],s<i?t[s++]:o[u++]].sort(oS.Buffer.compare);o[e]=this.hashFn(this.concatenator(a))}return 0===oS.Buffer.compare(o[a-1],e)}verifyMultiProofForUnevenTree(e,t,n,r,i){e=this.bufferify(e),n=n.map((e=>this.bufferify(e))),i=i.map((e=>this.bufferify(e)));const a=this.calculateRootForUnevenTree(t,n,r,i);return e.equals(a)}getDepth(){return this.getLayers().length-1}getLayersAsObject(){const e=this.getLayers().map((e=>e.map((e=>this.bufferToHex(e,!1))))),t=[];for(let n=0;n<e.length;n++){const r=[];for(let i=0;i<e[n].length;i++){const a={[e[n][i]]:null};if(t.length){a[e[n][i]]={};const r=t.shift(),o=Object.keys(r)[0];if(a[e[n][i]][o]=r[o],t.length){const r=t.shift(),o=Object.keys(r)[0];a[e[n][i]][o]=r[o]}}r.push(a)}t.push(...r)}return t[0]}static verify(t,n,r,i=uS.default,a={}){return new e([],i,a).verify(t,n,r)}static getMultiProof(t,n){return new e([]).getMultiProof(t,n)}resetTree(){this.leaves=[],this.layers=[]}getPairNode(e,t){const n=t%2==0?t+1:t-1;return n<e.length?e[n]:null}toTreeString(){const e=this.getLayersAsObject();return cS.default.asTree(e,!0)}toString(){return this.toTreeString()}isUnevenTree(e){const t=(null==e?void 0:e.length)||this.getDepth();return!this.isPowOf2(t)}isPowOf2(e){return e&&!(e&e-1)}calculateRootForUnevenTree(e,t,n,r){const i=this.zip(e,t).sort((([e],[t])=>e-t)),a=i.map((([e])=>e)),o=this.getProofIndicesForUnevenTree(a,n);let s=0;const u=[];for(let e=0;e<o.length;e++){const t=o[e],n=s;s+=t.length,u[e]=this.zip(t,r.slice(n,s))}const c=[i];for(let e=0;e<u.length;e++){const t=u[e].concat(c[e]).sort((([e],[t])=>e-t)).map((([,e])=>e)),n=c[e].map((([e])=>e)),r=[...new Set(n.map((e=>e%2==0?e/2:e%2==0?(e+1)/2:(e-1)/2)))],i=[];for(let e=0;e<r.length;e++){const n=r[e],a=t[2*e],o=t[2*e+1],s=o?this.hashFn(this.concatenator([a,o])):a;i.push([n,s])}c.push(i)}return c[c.length-1][0][1]}};pk.MerkleTree=dS,"undefined"!=typeof window&&(window.MerkleTree=dS),pk.default=dS;var fS={},pS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(fS,"__esModule",{value:!0}),fS.MerkleMountainRange=void 0;const hS=hn,mS=pS(vk),yS=pS(Ek);class gS extends yS.default{constructor(e=mS.default,t=[],n,r,i){super(),this.root=hS.Buffer.alloc(0),this.size=0,this.width=0,this.hashes={},this.data={},t=t.map(this.bufferify),this.hashFn=this.bufferifyFn(e),this.hashLeafFn=n,this.peakBaggingFn=r,this.hashBranchFn=i;for(const e of t)this.append(e)}append(e){e=this.bufferify(e);const t=this.hashFn(e),n=this.bufferToHex(t);this.data[n]&&this.bufferToHex(this.hashFn(this.data[n]))===n||(this.data[n]=e);const r=this.hashLeaf(this.size+1,t);this.hashes[this.size+1]=r,this.width+=1;const i=this.getPeakIndexes(this.width);this.size=this.getSize(this.width);const a=[];for(let e=0;e<i.length;e++)a[e]=this._getOrCreateNode(i[e]);this.root=this.peakBagging(this.width,a)}hashLeaf(e,t){return t=this.bufferify(t),this.hashLeafFn?this.bufferify(this.hashLeafFn(e,t)):this.hashFn(hS.Buffer.concat([this.bufferify(e),t]))}hashBranch(e,t,n){return this.hashBranchFn?this.bufferify(this.hashBranchFn(e,t,n)):this.hashFn(hS.Buffer.concat([this.bufferify(e),this.bufferify(t),this.bufferify(n)]))}getPeaks(){const e=this.getPeakIndexes(this.width),t=[];for(let n=0;n<e.length;n++)t[n]=this.hashes[e[n]];return t}getLeafIndex(e){return e%2==1?this.getSize(e):this.getSize(e-1)+1}getPeakIndexes(e){const t=this.numOfPeaks(e),n=[];let r=0,i=0;for(let a=255;a>0&&!(0!=(e&1<<a-1)&&(i=i+(1<<a)-1,n[r++]=i,n.length>=t));a--);if(r!==n.length)throw new Error("invalid bit calculation");return n}numOfPeaks(e){let t=e,n=0;for(;t>0;)t%2==1&&n++,t>>=1;return n}peakBagging(e,t){const n=this.getSize(e);if(this.numOfPeaks(e)!==t.length)throw new Error("received invalid number of peaks");return 0!==e||t.length?this.peakBaggingFn?this.bufferify(this.peakBaggingFn(n,t)):this.hashFn(hS.Buffer.concat([this.bufferify(n),...t.map(this.bufferify)])):hS.Buffer.alloc(0)}getSize(e){return(e<<1)-this.numOfPeaks(e)}getRoot(){return this.root}getHexRoot(){return this.bufferToHex(this.getRoot())}getNode(e){return this.hashes[e]}mountainHeight(e){let t=1;for(;1<<t<=e+t;)t++;return t-1}heightAt(e){let t=e,n=0,r=0;for(;t>n;)t-=(1<<r)-1,r=this.mountainHeight(t),n=(1<<r)-1;return r-(n-t)}isLeaf(e){return 1===this.heightAt(e)}getChildren(e){const t=e-(1<<this.heightAt(e)-1),n=e-1;if(t===n)throw new Error("not a parent");return[t,n]}getMerkleProof(e){if(e>this.size)throw new Error("out of range");if(!this.isLeaf(e))throw new Error("not a leaf");const t=this.root,n=this.width,r=this.getPeakIndexes(this.width),i=[];let a=0;for(let t=0;t<r.length;t++)i[t]=this.hashes[r[t]],r[t]>=e&&0===a&&(a=r[t]);let o=0,s=0,u=this.heightAt(a);const c=[];for(;a!==e;)u--,[o,s]=this.getChildren(a),a=e<=o?o:s,c[u-1]=this.hashes[e<=o?s:o];return{root:t,width:n,peakBagging:i,siblings:c}}verify(e,t,n,r,i,a){r=this.bufferify(r);if(this.getSize(t)<n)throw new Error("index is out of range");if(!e.equals(this.peakBagging(t,i)))throw new Error("invalid root hash from the peaks");let o,s=0;const u=this.getPeakIndexes(t);for(let e=0;e<u.length;e++)if(u[e]>=n){o=i[e],s=u[e];break}if(!o)throw new Error("target not found");let c=a.length+1;const l=new Array(c);let d,f=0,p=0;for(;c>0&&(l[--c]=s,s!==n);)[f,p]=this.getChildren(s),s=n>f?p:f;for(;c<l.length;)s=l[c],d=0===c?this.hashLeaf(s,this.hashFn(r)):s-1===l[c-1]?this.hashBranch(s,a[c-1],d):this.hashBranch(s,d,a[c-1]),c++;if(!d.equals(o))throw new Error("hashed peak is invalid");return!0}peaksToPeakMap(e,t){const n={};let r=0,i=0,a=t.length;for(let o=1;o<=32;o++)r=32-o,i=1<<o-1,n[r]=0!=(e&i)?t[--a]:0;if(0!==a)throw new Error("invalid number of peaks");return n}peakMapToPeaks(e,t){const n=this.numOfPeaks(e),r=new Array(n);let i=0;for(let e=0;e<32;e++)0!==t[e]&&(r[i++]=t[e]);if(i!==n)throw new Error("invalid number of peaks");return r}peakUpdate(e,t,n){const r={},i=e+1;let a=this.getLeafIndex(i),o=this.hashLeaf(a,n),s=0,u=0,c=!1,l=!1,d=!1;for(let n=1;n<=32;n++)s=32-n,d?r[s]=t[s]:(u=1<<n-1,c=0!=(e&u),l=0!=(i&u),a++,c&&(o=this.hashBranch(a,t[s],o)),l?(r[s]=c?t[s]:o,d=!0):r[s]=0);return r}rollUp(e,t,n,r){if(!e.equals(this.peakBagging(t,n)))throw new Error("invalid root hash from the peaks");let i=t,a=this.peaksToPeakMap(t,n);for(let e=0;e<r.length;e++)a=this.peakUpdate(i,a,r[e]),i++;return this.peakBagging(i,this.peakMapToPeaks(i,a))}_getOrCreateNode(e){if(e>this.size)throw new Error("out of range");if(!this.hashes[e]){const[t,n]=this.getChildren(e),r=this._getOrCreateNode(t),i=this._getOrCreateNode(n);this.hashes[e]=this.hashBranch(e,r,i)}return this.hashes[e]}}fS.MerkleMountainRange=gS,"undefined"!=typeof window&&(window.MerkleMountainRange=gS),fS.default=gS;var bS={},vS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(bS,"__esModule",{value:!0}),bS.IncrementalMerkleTree=void 0;const wS=vS(Ek),TS=vS(Ak);class AS extends wS.default{constructor(e,t){if(super(),this.hashFn=e,t.depth&&(this.depth=t.depth),t.arity&&(this.arity=t.arity),this.depth<1)throw new Error("depth must be greater than 0");if(this.arity<1)throw new Error("arity must be greater than 0");const n=[];let r=t.zeroValue;if(this.zeroValue=r,this.zeroes=[],this.depth)for(let e=0;e<this.depth;e++)this.zeroes.push(r),n[e]=[],r=this.hashFn(Array(this.arity).fill(r));this.nodes=n,this.root=r}getRoot(){return this.root}getHexRoot(){return this.bufferToHex(this.bufferify(this.getRoot()))}insert(e){if(this.depth&&this.arity&&this.nodes[0].length>=this.getMaxLeaves())throw new Error("tree is full");let t=e,n=this.nodes[0].length;for(let e=0;e<this.depth;e+=1){const r=n-n%this.arity,i=r+this.arity,a=[];this.nodes[e][n]=t;for(let t=r;t<i;t+=1)t<this.nodes[e].length?a.push(this.nodes[e][t]):a.push(this.zeroes[e]);t=this.hashFn(a),n=Math.floor(n/this.arity)}this.root=t}delete(e){this.update(e,this.zeroValue)}update(e,t){if(e<0||e>=this.nodes[0].length)throw new Error("out of bounds");let n=t;for(let t=0;t<this.depth;t+=1){const r=e-e%this.arity,i=r+this.arity,a=[];this.nodes[t][e]=n;for(let e=r;e<i;e+=1)e<this.nodes[t].length?a.push(this.nodes[t][e]):a.push(this.zeroes[t]);n=this.hashFn(a),e=Math.floor(e/this.arity)}this.root=n}getDepth(){return this.depth}getArity(){return this.arity}getMaxLeaves(){return Math.pow(this.depth,this.arity)}indexOf(e){return this.nodes[0].indexOf(e)}getLeaves(){const e=this.copyList(this.nodes[0]);for(let t=this.nodes[0].length;t<this.getMaxLeaves();t++)e[t]=this.zeroValue;return e}copyList(e){return e.map((e=>BigInt(e)))}getLayers(){const e=[];for(const t of this.nodes)e.push(this.copyList(t));if(e[0].length<this.getMaxLeaves()){let t=e[0].length;for(let n=t;n<this.getMaxLeaves();n++)e[0][n]=this.zeroValue;for(let n=0;n<this.depth;n++){const r=t-t%this.arity,i=r+this.arity;for(let t=r;t<i;t++)t>=e[n].length&&(e[n][t]=this.zeroes[n]);t=Math.floor(t/this.arity)}}return e.push([this.root]),e}getHexLayers(){return this.getLayers().reduce(((e,t)=>(Array.isArray(t)?e.push(t.map((e=>this.bufferToHex(this.bufferify(e))))):e.push(t),e)),[])}getLayersAsObject(){const e=this.getLayers().map((e=>e.map((e=>this.bufferToHex(this.bufferify(e),!1))))),t=[];for(let n=0;n<e.length;n++){const r=[];for(let i=0;i<e[n].length;i++){const a={[e[n][i]]:null};if(t.length){a[e[n][i]]={};const r=t.shift(),o=Object.keys(r)[0];if(a[e[n][i]][o]=r[o],t.length){const r=t.shift(),o=Object.keys(r)[0];a[e[n][i]][o]=r[o]}}r.push(a)}t.push(...r)}return t[0]}computeRoot(){let e,t=this.nodes[0].length;for(let n=0;n<this.depth;n+=1){const r=t-t%this.arity,i=r+this.arity,a=[];for(let e=r;e<i;e+=1)e<this.nodes[n].length?a.push(this.nodes[n][e]):a.push(this.zeroes[n]);e=this.hashFn(a),t=Math.floor(t/this.arity)}return e}getProof(e){if(e<0||e>=this.nodes[0].length)throw new Error("The leaf does not exist in this tree");const t=[],n=[],r=e;for(let r=0;r<this.depth;r+=1){const i=e%this.arity,a=e-i,o=a+this.arity;n[r]=i,t[r]=[];for(let n=a;n<o;n+=1)n!==e&&(n<this.nodes[r].length?t[r].push(this.nodes[r][n]):t[r].push(this.zeroes[r]));e=Math.floor(e/this.arity)}return{root:this.root,leaf:this.nodes[0][r],pathIndices:n,siblings:t}}verify(e){let t=e.leaf;for(let n=0;n<e.siblings.length;n+=1){const r=e.siblings[n].slice();r.splice(e.pathIndices[n],0,t),t=this.hashFn(r)}return e.root===t}toString(){return this.toTreeString()}toTreeString(){const e=this.getLayersAsObject();return TS.default.asTree(e,!0)}}bS.IncrementalMerkleTree=AS,"undefined"!=typeof window&&(window.IncrementalMerkleTree=AS),bS.default=AS;var ES={};Object.defineProperty(ES,"__esModule",{value:!0}),ES.MerkleSumTree=ES.ProofStep=ES.Leaf=ES.Bucket=void 0;const _S=Ek;class IS{constructor(e,t){this.size=BigInt(e),this.hashed=t,this.parent=null,this.left=null,this.right=null}}ES.Bucket=IS;ES.Leaf=class{constructor(e,t,n){this.hashFn=e,this.rng=t.map((e=>BigInt(e))),this.data=n}getBucket(){let e;return e=this.data?this.hashFn(this.data):Buffer.alloc(32),new IS(BigInt(this.rng[1])-BigInt(this.rng[0]),e)}};class RS{constructor(e,t){this.bucket=e,this.right=t}}ES.ProofStep=RS;class CS extends _S.Base{constructor(e,t){super(),this.leaves=e,this.hashFn=t,CS.checkConsecutive(e),this.buckets=[];for(const t of e)this.buckets.push(t.getBucket());let n=[];for(const e of this.buckets)n.push(e);for(;1!==n.length;){const e=[];for(;n.length;)if(n.length>=2){const t=n.shift(),r=n.shift(),i=t.size+r.size,a=this.hashFn(Buffer.concat([this.sizeToBuffer(t.size),this.bufferify(t.hashed),this.sizeToBuffer(r.size),this.bufferify(r.hashed)])),o=new IS(i,a);r.parent=o,t.parent=r.parent,t.right=r,r.left=t,e.push(o)}else e.push(n.shift());n=e}this.root=n[0]}sizeToBuffer(e){const t=Buffer.alloc(8);return new DataView(t.buffer).setBigInt64(0,BigInt(e),!1),t}static checkConsecutive(e){let t=BigInt(0);for(const n of e){if(n.rng[0]!==t)throw new Error("leaf ranges are invalid");t=BigInt(n.rng[1])}}getProof(e){let t=this.buckets[Number(e)];const n=[];for(;t&&t.parent;){const e=!!t.right,r=t.right?t.right:t.left;t=t.parent,n.push(new RS(r,e))}return n}sum(e){let t=BigInt(0);for(const n of e)t+=BigInt(n);return t}verifyProof(e,t,n){const r=[this.sum(n.filter((e=>!e.right)).map((e=>e.bucket.size))),BigInt(e.size)-this.sum(n.filter((e=>e.right)).map((e=>e.bucket.size)))];if(r[0]!==t.rng[0]||r[1]!==t.rng[1])return!1;let i,a=t.getBucket();for(const e of n)i=e.right?this.hashFn(Buffer.concat([this.sizeToBuffer(a.size),this.bufferify(a.hashed),this.sizeToBuffer(e.bucket.size),this.bufferify(e.bucket.hashed)])):this.hashFn(Buffer.concat([this.sizeToBuffer(e.bucket.size),this.bufferify(e.bucket.hashed),this.sizeToBuffer(a.size),this.bufferify(a.hashed)])),a=new IS(BigInt(a.size)+BigInt(e.bucket.size),i);return a.size===e.size&&a.hashed.toString("hex")===e.hashed.toString("hex")}}ES.MerkleSumTree=CS,"undefined"!=typeof window&&(window.MerkleSumTree=CS),ES.default=CS,function(e){var t=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.MerkleTree=void 0;const n=t(pk);e.MerkleTree=n.default;var r=fS;Object.defineProperty(e,"MerkleMountainRange",{enumerable:!0,get:function(){return r.MerkleMountainRange}});var i=bS;Object.defineProperty(e,"IncrementalMerkleTree",{enumerable:!0,get:function(){return i.IncrementalMerkleTree}});var a=ES;Object.defineProperty(e,"MerkleSumTree",{enumerable:!0,get:function(){return a.MerkleSumTree}}),e.default=n.default}(fk);var kS={};Object.defineProperty(kS,"__esModule",{value:!0}),kS.DefaultGetter=void 0;const OS=pC,SS=new AC.Logger("defaults"),NS={integer:0,address:(0,OS.hexZeroPad)("0x",20),bool:!1,bytes:"0x",string:""},xS=e=>void 0!==e&&(null!=e&&(["string","number"].includes(typeof e)&&BigInt(e)===BigInt(0)||Array.isArray(e)&&e.every(xS)||"object"==typeof e&&Object.values(e).every(xS)||"boolean"==typeof e&&!1===e));class PS{constructor(e){this.types=e,this.defaultValues={};for(const t in e){const e=this.getDefaultValue(t);this.defaultValues[t]=e,xS(e)||SS.throwError(`Got non-empty value for type ${t} in default generator: ${e}`)}}static from(e,t){const{defaultValues:n}=new PS(e);return t?n[t]:n}getDefaultValue(e){if(this.defaultValues[e])return this.defaultValues[e];const t=function(e){var t;const[,n]=null!==(t=e.match(/^bytes(\d+)$/))&&void 0!==t?t:[];return n?(0,OS.hexZeroPad)("0x",parseInt(n)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),NS[e])}(e);if(void 0!==t)return t;const n=e.match(/^(.*)(\x5b(\d*)\x5d)$/);if(n){const e=n[1],t=parseInt(n[3]);if(t>0){const n=this.getDefaultValue(e);return Array(t).fill(n)}return[]}const r=this.types[e];return r?r.reduce(((e,{name:t,type:n})=>Object.assign(Object.assign({},e),{[t]:this.getDefaultValue(n)})),{}):SS.throwArgumentError(`unknown type: ${e}`,"type",e)}}kS.DefaultGetter=PS;var MS={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getNextLayer=e.getRoot=e.fillArray=e.hashConcat=e.bufferKeccak=e.hexToBuffer=e.bufferToHex=e.chunk=e.makeArray=void 0;const t=pC;e.makeArray=(e,t)=>Array(e).fill(0).map(((e,n)=>t(n)));e.chunk=(t,n)=>(0,e.makeArray)(Math.ceil(t.length/n),(e=>t.slice(e*n,(e+1)*n)));e.bufferToHex=e=>(0,t.hexlify)(e);e.hexToBuffer=e=>Buffer.from(e.slice(2),"hex");e.bufferKeccak=n=>(0,e.hexToBuffer)((0,t.keccak256)(n));e.hashConcat=n=>(0,e.bufferKeccak)((0,t.hexConcat)(n));e.fillArray=(e,t,n)=>(t>e.length&&e.push(...Array(t-e.length).fill(n)),e);e.getRoot=(t,n=!0)=>{if(0===t.length)throw new Error("empty tree");const r=[t.map((t=>{const r=Buffer.isBuffer(t)?t:(0,e.hexToBuffer)(t);return n?(0,e.bufferKeccak)(r):r}))];for(;r[r.length-1].length>1;)r.push((0,e.getNextLayer)(r[r.length-1]));return r[r.length-1][0]};e.getNextLayer=t=>(0,e.chunk)(t,2).map(e.hashConcat)}(MS),Object.defineProperty(dk,"__esModule",{value:!0}),dk.Eip712MerkleTree=void 0;const BS=bC,DS=pC,FS=fk,LS=kS,US=MS;dk.Eip712MerkleTree=class{get completedSize(){return Math.pow(2,this.depth)}getCompleteElements(){const e=this.elements;return(0,US.fillArray)([...e],this.completedSize,this.defaultNode)}getCompleteLeaves(){const e=this.elements.map(this.leafHasher);return(0,US.fillArray)([...e],this.completedSize,this.defaultLeaf)}get root(){return this.tree.getHexRoot()}getProof(e){const t=this.getCompleteLeaves()[e];return{leaf:t,proof:this.tree.getHexProof(t,e),root:this.tree.getHexRoot()}}getEncodedProofAndSignature(e,t){const{proof:n}=this.getProof(e);return((e,t,n=`0x${"ff".repeat(64)}`)=>(0,DS.hexConcat)([n,`0x${e.toString(16).padStart(6,"0")}`,DS.defaultAbiCoder.encode([`uint256[${t.length}]`],[t])]))(e,n,t)}getDataToSign(){let e=this.getCompleteElements();for(;e.length>2;)e=(0,US.chunk)(e,2);return e}add(e){this.elements.push(e)}getBulkOrderHash(){const e=this.encoder.hashStruct("BulkOrder",{tree:this.getDataToSign()}),t=this.getCompleteLeaves().map(US.hexToBuffer),n=(0,US.bufferToHex)((0,US.getRoot)(t,!1)),r=(0,DS.keccak256)((0,DS.toUtf8Bytes)(this.encoder._types.BulkOrder));if((0,DS.keccak256)((0,DS.hexConcat)([r,n]))!==e)throw new Error("expected derived bulk order hash to match");return e}constructor(e,t,n,r,i){this.types=e,this.rootType=t,this.leafType=n,this.elements=r,this.depth=i;const a=BS._TypedDataEncoder.from(e);var o,s;this.encoder=a,this.leafHasher=e=>a.hashStruct(n,e),this.defaultNode=LS.DefaultGetter.from(e,n),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=(o=this.getCompleteLeaves(),s=this.defaultLeaf,new FS.MerkleTree(o.map(US.hexToBuffer),US.bufferKeccak,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:(0,US.hexToBuffer)(s)}))}},Object.defineProperty(lk,"__esModule",{value:!0}),lk.getBulkOrderTypeHashes=lk.getBulkOrderTypeHash=lk.getBulkOrderTree=lk.getBulkOrderTreeHeight=void 0;const qS=pC,jS=dk,GS=kS,HS=MS,zS=BC;function VS(e){const t=Object.assign({},zS.EIP_712_BULK_ORDER_TYPE);return t.BulkOrder=[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}],t}function WS(e){return Math.max(Math.ceil(Math.log2(e)),1)}function KS(e){const t=VS(e),n=qS._TypedDataEncoder.from(t),r=(0,qS.toUtf8Bytes)(n._types.BulkOrder);return(0,qS.keccak256)(r)}lk.getBulkOrderTreeHeight=WS,lk.getBulkOrderTree=function(e,t=0,n=WS(e.length+t)){const r=VS(n),i=GS.DefaultGetter.from(r,"OrderComponents");let a=[...e];return t>0&&(a=[...(0,HS.fillArray)([],t,i),...e]),new jS.Eip712MerkleTree(r,"BulkOrder","OrderComponents",a,n)},lk.getBulkOrderTypeHash=KS,lk.getBulkOrderTypeHashes=function(e){const t=[];for(let n=0;n<e;n++)t.push(KS(n+1));return t};var XS={},JS={},YS={};Object.defineProperty(YS,"__esModule",{value:!0}),YS.MerkleTree=void 0;const QS=fC,ZS=pC,$S=fk,eN=e=>(0,ZS.keccak256)(Buffer.from(QS.BigNumber.from(e).toHexString().slice(2).padStart(64,"0"),"hex"));YS.MerkleTree=class{constructor(e){this.tree=new $S.default(e.map(eN),ZS.keccak256,{sort:!0})}getProof(e){return this.tree.getHexProof(eN(e))}getRoot(){return this.tree.getRoot().toString("hex")?this.tree.getHexRoot():"0"}},Object.defineProperty(JS,"__esModule",{value:!0}),JS.shouldUseMatchForFulfill=JS.generateRandomSalt=JS.mapOrderAmountsFromUnitsToFill=JS.mapOrderAmountsFromFilledStatus=JS.totalItemsAmount=JS.areAllCurrenciesSame=JS.mapInputItemToOfferItem=JS.deductFees=JS.feeToConsiderationItem=void 0;const tN=fC,nN=pC,rN=BC,iN=VC(),aN=YS,oN=(e,t)=>tN.BigNumber.from(e).mul(tN.BigNumber.from(t)).div(rN.ONE_HUNDRED_PERCENT_BP);JS.feeToConsiderationItem=({fee:e,token:t,baseAmount:n,baseEndAmount:r=n})=>({itemType:t===tN.ethers.constants.AddressZero?rN.ItemType.NATIVE:rN.ItemType.ERC20,token:t,identifierOrCriteria:"0",startAmount:oN(n,e.basisPoints).toString(),endAmount:oN(r,e.basisPoints).toString(),recipient:e.recipient});JS.deductFees=(e,t)=>{if(!t)return e;const n=t.reduce(((e,t)=>e+t.basisPoints),0);return e.map((e=>Object.assign(Object.assign({},e),{startAmount:(0,iN.isCurrencyItem)(e)?tN.BigNumber.from(e.startAmount).sub(oN(e.startAmount,n)).toString():e.startAmount,endAmount:(0,iN.isCurrencyItem)(e)?tN.BigNumber.from(e.endAmount).sub(oN(e.endAmount,n)).toString():e.endAmount})))};JS.mapInputItemToOfferItem=e=>{var t,n,r,i,a,o,s,u;if("itemType"in e){if("identifiers"in e||"criteria"in e){const i="criteria"in e?e.criteria:new aN.MerkleTree(e.identifiers).getRoot();return{itemType:e.itemType===rN.ItemType.ERC721?rN.ItemType.ERC721_WITH_CRITERIA:rN.ItemType.ERC1155_WITH_CRITERIA,token:e.token,identifierOrCriteria:i,startAmount:null!==(t=e.amount)&&void 0!==t?t:"1",endAmount:null!==(r=null!==(n=e.endAmount)&&void 0!==n?n:e.amount)&&void 0!==r?r:"1"}}return"amount"in e||"endAmount"in e?{itemType:e.itemType,token:e.token,identifierOrCriteria:null!==(i=e.identifier)&&void 0!==i?i:"0",startAmount:e.amount,endAmount:null!==(o=null!==(a=e.endAmount)&&void 0!==a?a:e.amount)&&void 0!==o?o:"1"}:{itemType:e.itemType,token:e.token,identifierOrCriteria:e.identifier,startAmount:"1",endAmount:"1"}}return{itemType:e.token&&e.token!==tN.ethers.constants.AddressZero?rN.ItemType.ERC20:rN.ItemType.NATIVE,token:null!==(s=e.token)&&void 0!==s?s:tN.ethers.constants.AddressZero,identifierOrCriteria:"0",startAmount:e.amount,endAmount:null!==(u=e.endAmount)&&void 0!==u?u:e.amount}};JS.areAllCurrenciesSame=({offer:e,consideration:t})=>{const n=[...e,...t].filter(iN.isCurrencyItem);return n.every((({itemType:e,token:t})=>e===n[0].itemType&&t.toLowerCase()===n[0].token.toLowerCase()))};JS.totalItemsAmount=e=>(tN.BigNumber.from(0),tN.BigNumber.from(0),e.map((({startAmount:e,endAmount:t})=>({startAmount:e,endAmount:t}))).reduce((({startAmount:e,endAmount:t},{startAmount:n,endAmount:r})=>({startAmount:e.add(n),endAmount:t.add(r)})),{startAmount:tN.BigNumber.from(0),endAmount:tN.BigNumber.from(0)}));JS.mapOrderAmountsFromFilledStatus=(e,{totalFilled:t,totalSize:n})=>{if(t.eq(0)||n.eq(0))return e;const r=n.sub(t).mul(rN.ONE_HUNDRED_PERCENT_BP).div(n);return{parameters:Object.assign(Object.assign({},e.parameters),{offer:e.parameters.offer.map((e=>Object.assign(Object.assign({},e),{startAmount:oN(e.startAmount,r).toString(),endAmount:oN(e.endAmount,r).toString()}))),consideration:e.parameters.consideration.map((e=>Object.assign(Object.assign({},e),{startAmount:oN(e.startAmount,r).toString(),endAmount:oN(e.endAmount,r).toString()})))}),signature:e.signature}};const sN=(e,t,n)=>tN.BigNumber.from(e).mul(tN.BigNumber.from(t)).div(n);JS.mapOrderAmountsFromUnitsToFill=(e,{unitsToFill:t,totalSize:n})=>{const r=tN.BigNumber.from(t);if(r.lte(0))throw new Error("Units to fill must be greater than 1");const i=(0,iN.getMaximumSizeForOrder)(e);return n.eq(0)&&(n=i),{parameters:Object.assign(Object.assign({},e.parameters),{offer:e.parameters.offer.map((e=>Object.assign(Object.assign({},e),{startAmount:sN(e.startAmount,r,n).toString(),endAmount:sN(e.endAmount,r,n).toString()}))),consideration:e.parameters.consideration.map((e=>Object.assign(Object.assign({},e),{startAmount:sN(e.startAmount,r,n).toString(),endAmount:sN(e.endAmount,r,n).toString()})))}),signature:e.signature}};JS.generateRandomSalt=e=>e?`0x${Buffer.from((0,nN.concat)([(0,nN.keccak256)((0,nN.toUtf8Bytes)(e)).slice(0,10),Uint8Array.from(Array(20).fill(0)),(0,nN.randomBytes)(8)])).toString("hex")}`:`0x${Buffer.from((0,nN.randomBytes)(8)).toString("hex").padStart(64,"0")}`;JS.shouldUseMatchForFulfill=()=>!0,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getAdvancedOrderNumeratorDenominator=e.generateFulfillOrdersFulfillments=e.fulfillAvailableOrders=e.validateAndSanitizeFromOrderStatus=e.fulfillStandardOrder=e.fulfillBasicOrder=e.shouldUseBasicFulfill=void 0;const t=fC,n=BC,r=DC,i=ek,a=GC(),o=zC,s=VC(),u=JS,c=WC;e.shouldUseBasicFulfill=({offer:e,consideration:r,offerer:i},a)=>{if(!a.eq(0))return!1;if(e.length>1||0===r.length)return!1;const o=[...e,...r],c=o.filter((({itemType:e})=>[n.ItemType.ERC721,n.ItemType.ERC1155].includes(e))),l=o.filter((({itemType:e})=>(0,s.isCriteriaItem)(e)));if((0,s.isNativeCurrencyItem)(e[0]))return!1;if(1!==c.length||0!==l.length)return!1;if(!(0,u.areAllCurrenciesSame)({offer:e,consideration:r}))return!1;if(o.some((({startAmount:e,endAmount:t})=>e!==t)))return!1;const[d,...f]=r;if(d.recipient.toLowerCase()!==i.toLowerCase())return!1;if(r.length>1&&f.every((t=>t.itemType===e[0].itemType))&&(0,u.totalItemsAmount)(f).endAmount.gt(e[0].endAmount))return!1;const p=o.filter(s.isCurrencyItem),h=p.filter((({itemType:e})=>e===n.ItemType.NATIVE)).every((({token:e})=>e===t.ethers.constants.AddressZero)),m=p.every((({identifierOrCriteria:e})=>t.BigNumber.from(e).eq(0))),y=c.filter((({itemType:e})=>e===n.ItemType.ERC721)).every((({endAmount:e})=>"1"===e));return h&&m&&y};const l={[n.ItemType.ERC20]:{[n.ItemType.ERC721]:n.BasicOrderRouteType.ERC721_TO_ERC20,[n.ItemType.ERC1155]:n.BasicOrderRouteType.ERC1155_TO_ERC20},[n.ItemType.ERC721]:{[n.ItemType.NATIVE]:n.BasicOrderRouteType.ETH_TO_ERC721,[n.ItemType.ERC20]:n.BasicOrderRouteType.ERC20_TO_ERC721},[n.ItemType.ERC1155]:{[n.ItemType.NATIVE]:n.BasicOrderRouteType.ETH_TO_ERC1155,[n.ItemType.ERC20]:n.BasicOrderRouteType.ERC20_TO_ERC1155}};function d(e,t){const{isValidated:n,isCancelled:r,totalFilled:i,totalSize:a}=t;if(a.gt(0)&&i.div(a).eq(1))throw new Error("The order you are trying to fulfill is already filled");if(r)throw new Error("The order you are trying to fulfill is cancelled");return n?{parameters:Object.assign({},e.parameters),signature:"0x"}:e}function f(e){const t=({sourceOrDestination:e,operator:t="",token:n,identifier:r})=>`${e}-${t}-${n}-${r}`,n={},r={};return e.forEach((({order:e,offererOperator:r,offerCriteria:i},o)=>{const u=(0,a.getItemToCriteriaMap)(e.parameters.offer,i);return e.parameters.offer.forEach(((i,a)=>{var c,l,d;const f=`${t({sourceOrDestination:e.parameters.offerer,operator:r,token:i.token,identifier:null!==(l=null===(c=u.get(i))||void 0===c?void 0:c.identifier)&&void 0!==l?l:i.identifierOrCriteria})}${(0,s.isErc721Item)(i.itemType)?a:""}`;n[f]=[...null!==(d=n[f])&&void 0!==d?d:[],{orderIndex:o,itemIndex:a}]}))})),e.forEach((({order:e,considerationCriteria:n,tips:i},o)=>{const u=(0,a.getItemToCriteriaMap)(e.parameters.consideration,n);return[...e.parameters.consideration,...i].forEach(((e,n)=>{var i,a,c;const l=`${t({sourceOrDestination:e.recipient,token:e.token,identifier:null!==(a=null===(i=u.get(e))||void 0===i?void 0:i.identifier)&&void 0!==a?a:e.identifierOrCriteria})}${(0,s.isErc721Item)(e.itemType)?n:""}`;r[l]=[...null!==(c=r[l])&&void 0!==c?c:[],{orderIndex:o,itemIndex:n}]}))})),{offerFulfillments:Object.values(n),considerationFulfillments:Object.values(r)}}e.fulfillBasicOrder=function({order:e,seaportContract:a,offererBalancesAndApprovals:o,fulfillerBalancesAndApprovals:u,timeBasedItemParams:d,offererOperator:f,fulfillerOperator:p,signer:h,tips:m=[],conduitKey:y=n.NO_CONDUIT,domain:g},b){var v,w;const{offer:T,consideration:A}=e.parameters,E=[...A,...m],_=T[0],[I,...R]=E,C=null===(v=l[_.itemType])||void 0===v?void 0:v[I.itemType];if(void 0===C)throw new Error("Order parameters did not result in a valid basic fulfillment");const k=R.map((({startAmount:e,recipient:t})=>({amount:e,recipient:t}))),O=E.filter((e=>e.itemType!==T[0].itemType)),S=null===(w=(0,s.getSummedTokenAndIdentifierAmounts)({items:O,criterias:[],timeBasedItemParams:Object.assign(Object.assign({},d),{isConsiderationItem:!0})})[t.ethers.constants.AddressZero])||void 0===w?void 0:w[0],N=(0,i.validateBasicFulfillBalancesAndApprovals)({offer:T,consideration:E,offererBalancesAndApprovals:o,fulfillerBalancesAndApprovals:u,timeBasedItemParams:d,offererOperator:f,fulfillerOperator:p}),x={offerer:e.parameters.offerer,offererConduitKey:e.parameters.conduitKey,zone:e.parameters.zone,basicOrderType:e.parameters.orderType+4*C,offerToken:_.token,offerIdentifier:_.identifierOrCriteria,offerAmount:_.endAmount,considerationToken:I.token,considerationIdentifier:I.identifierOrCriteria,considerationAmount:I.endAmount,startTime:e.parameters.startTime,endTime:e.parameters.endTime,salt:e.parameters.salt,totalOriginalAdditionalRecipients:e.parameters.consideration.length-1,signature:e.signature,fulfillerConduitKey:y,additionalRecipients:k,zoneHash:e.parameters.zoneHash},P={value:S},M=[...(0,r.getApprovalActions)(N,b,h),{type:"exchange",transactionMethods:(0,c.getTransactionMethods)(a.connect(h),"fulfillBasicOrder",[x,P],g)}];return{actions:M,executeAllActions:()=>(0,c.executeAllActions)(M)}},e.fulfillStandardOrder=function({order:n,unitsToFill:o=0,totalSize:l,totalFilled:d,offerCriteria:f,considerationCriteria:p,tips:h=[],extraData:m,seaportContract:y,offererBalancesAndApprovals:g,fulfillerBalancesAndApprovals:b,offererOperator:v,fulfillerOperator:w,timeBasedItemParams:T,conduitKey:A,recipientAddress:E,signer:_,domain:I},R){var C;const k=o?(0,u.mapOrderAmountsFromUnitsToFill)(n,{unitsToFill:o,totalSize:l}):(0,u.mapOrderAmountsFromFilledStatus)(n,{totalFilled:d,totalSize:l}),{parameters:{offer:O,consideration:S}}=k,N=[...S,...h],x=O.filter((({itemType:e})=>(0,s.isCriteriaItem)(e))),P=N.filter((({itemType:e})=>(0,s.isCriteriaItem)(e))),M=x.length>0||P.length>0;if(x.length!==f.length||P.length!==p.length)throw new Error("You must supply the appropriate criterias for criteria based items");const B=null===(C=(0,s.getSummedTokenAndIdentifierAmounts)({items:N,criterias:p,timeBasedItemParams:Object.assign(Object.assign({},T),{isConsiderationItem:!0})})[t.ethers.constants.AddressZero])||void 0===C?void 0:C[0],D=(0,i.validateStandardFulfillBalancesAndApprovals)({offer:O,consideration:N,offerCriteria:f,considerationCriteria:p,offererBalancesAndApprovals:g,fulfillerBalancesAndApprovals:b,timeBasedItemParams:T,offererOperator:v,fulfillerOperator:w}),F={value:B},L=(0,r.getApprovalActions)(D,R,_),U=E!==t.ethers.constants.AddressZero,q=Boolean(o)||M||U,j=Object.assign(Object.assign({},n),{parameters:Object.assign(Object.assign({},n.parameters),{consideration:[...n.parameters.consideration,...h],totalOriginalConsiderationItems:S.length})}),{numerator:G,denominator:H}=(0,e.getAdvancedOrderNumeratorDenominator)(n,o),z=[...L,{type:"exchange",transactionMethods:q?(0,c.getTransactionMethods)(y.connect(_),"fulfillAdvancedOrder",[Object.assign(Object.assign({},j),{numerator:G,denominator:H,extraData:null!=m?m:"0x"}),M?(0,a.generateCriteriaResolvers)({orders:[n],offerCriterias:[f],considerationCriterias:[p]}):[],A,E,F],I):(0,c.getTransactionMethods)(y.connect(_),"fulfillOrder",[j,A,F],I)}];return{actions:z,executeAllActions:()=>(0,c.executeAllActions)(z)}},e.validateAndSanitizeFromOrderStatus=d,e.fulfillAvailableOrders=function({ordersMetadata:n,seaportContract:o,fulfillerBalancesAndApprovals:l,fulfillerOperator:p,currentBlockTimestamp:h,ascendingAmountTimestampBuffer:m,conduitKey:y,signer:g,recipientAddress:b,exactApproval:v,domain:w}){const T=n.map((e=>Object.assign(Object.assign({},e),{order:d(e.order,e.orderStatus)}))),A=T.map((e=>Object.assign(Object.assign({},e),{order:e.unitsToFill?(0,u.mapOrderAmountsFromUnitsToFill)(e.order,{unitsToFill:e.unitsToFill,totalSize:e.orderStatus.totalSize}):(0,u.mapOrderAmountsFromFilledStatus)(e.order,{totalFilled:e.orderStatus.totalFilled,totalSize:e.orderStatus.totalSize})})));let E=t.BigNumber.from(0);const _=[],I=T.flatMap((e=>[e.order.parameters.offer,e.order.parameters.consideration])).flat().filter((({itemType:e})=>(0,s.isCriteriaItem)(e))).length>0;A.forEach((({order:e,tips:n,offerCriteria:r,considerationCriteria:a,offererBalancesAndApprovals:o,offererOperator:u})=>{var c,d;const f=[...e.parameters.consideration,...n],y={startTime:e.parameters.startTime,endTime:e.parameters.endTime,currentBlockTimestamp:h,ascendingAmountTimestampBuffer:m,isConsiderationItem:!0};E=E.add(null!==(d=null===(c=(0,s.getSummedTokenAndIdentifierAmounts)({items:f,criterias:a,timeBasedItemParams:y})[t.ethers.constants.AddressZero])||void 0===c?void 0:c[0])&&void 0!==d?d:t.BigNumber.from(0));const g=(0,i.validateStandardFulfillBalancesAndApprovals)({offer:e.parameters.offer,consideration:f,offerCriteria:r,considerationCriteria:a,offererBalancesAndApprovals:o,fulfillerBalancesAndApprovals:l,timeBasedItemParams:y,offererOperator:u,fulfillerOperator:p}),b=e.parameters.offer.filter((({itemType:e})=>(0,s.isCriteriaItem)(e))),v=f.filter((({itemType:e})=>(0,s.isCriteriaItem)(e)));if(b.length!==r.length||v.length!==a.length)throw new Error("You must supply the appropriate criterias for criteria based items");g.forEach((e=>{_.find((t=>t.token===e.token))||_.push(e)}))}));const R={value:E},C=(0,r.getApprovalActions)(_,v,g),k=T.map((({order:t,unitsToFill:n=0,tips:r,extraData:i})=>{const{numerator:a,denominator:o}=(0,e.getAdvancedOrderNumeratorDenominator)(t,n),s=[...t.parameters.consideration,...r];return Object.assign(Object.assign({},t),{parameters:Object.assign(Object.assign({},t.parameters),{consideration:s,totalOriginalConsiderationItems:t.parameters.consideration.length}),numerator:a,denominator:o,extraData:i})})),{offerFulfillments:O,considerationFulfillments:S}=f(n),N={type:"exchange",transactionMethods:(0,c.getTransactionMethods)(o.connect(g),"fulfillAvailableAdvancedOrders",[k,I?(0,a.generateCriteriaResolvers)({orders:n.map((({order:e})=>e)),offerCriterias:n.map((({offerCriteria:e})=>e)),considerationCriterias:n.map((({considerationCriteria:e})=>e))}):[],O,S,y,b,k.length,R],w)},x=[...C,N];return{actions:x,executeAllActions:()=>(0,c.executeAllActions)(x)}},e.generateFulfillOrdersFulfillments=f;e.getAdvancedOrderNumeratorDenominator=(e,n)=>{const r=(0,s.getMaximumSizeForOrder)(e),i=t.BigNumber.from(n),a=(0,o.gcd)(i,r);return{numerator:n?i.div(a):t.BigNumber.from(1),denominator:n?r.div(a):t.BigNumber.from(1)}}}(XS);var uN=ct&&ct.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,a){function o(e){try{u(r.next(e))}catch(e){a(e)}}function s(e){try{u(r.throw(e))}catch(e){a(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}u((r=r.apply(e,t||[])).next())}))};Object.defineProperty(jR,"__esModule",{value:!0}),jR.Seaport=void 0;const cN=dC,lN=fC,dN=pC,fN=PC,pN=MC,hN=BC,mN=DC,yN=ek,gN=lk,bN=XS,vN=VC(),wN=JS,TN=WC;jR.Seaport=class{constructor(e,{overrides:t,ascendingAmountFulfillmentBuffer:n=300,balanceAndApprovalChecksOnOrderCreation:r=!0,conduitKeyToConduit:i,seaportVersion:a="1.5"}={}){var o,s,u;this.OPENSEA_CONDUIT_KEY=hN.OPENSEA_CONDUIT_KEY,this.getOrderHash=e=>{const t="OfferItem(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)",n="ConsiderationItem(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)",r=`OrderComponents(address offerer,address zone,OfferItem[] offer,ConsiderationItem[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 counter)${n}${t}`,i=lN.ethers.utils.keccak256(lN.ethers.utils.toUtf8Bytes(t)),a=lN.ethers.utils.keccak256(lN.ethers.utils.toUtf8Bytes(n)),o=lN.ethers.utils.keccak256(lN.ethers.utils.toUtf8Bytes(r)),s=lN.ethers.utils.keccak256("0x"+e.offer.map((e=>lN.ethers.utils.keccak256("0x"+[i.slice(2),e.itemType.toString().padStart(64,"0"),e.token.slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.identifierOrCriteria).toHexString().slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.startAmount).toHexString().slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.endAmount).toHexString().slice(2).padStart(64,"0")].join("")).slice(2))).join("")),u=lN.ethers.utils.keccak256("0x"+e.consideration.map((e=>lN.ethers.utils.keccak256("0x"+[a.slice(2),e.itemType.toString().padStart(64,"0"),e.token.slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.identifierOrCriteria).toHexString().slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.startAmount).toHexString().slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.endAmount).toHexString().slice(2).padStart(64,"0"),e.recipient.slice(2).padStart(64,"0")].join("")).slice(2))).join(""));return lN.ethers.utils.keccak256("0x"+[o.slice(2),e.offerer.slice(2).padStart(64,"0"),e.zone.slice(2).padStart(64,"0"),s.slice(2),u.slice(2),e.orderType.toString().padStart(64,"0"),lN.ethers.BigNumber.from(e.startTime).toHexString().slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.endTime).toHexString().slice(2).padStart(64,"0"),e.zoneHash.slice(2),lN.BigNumber.from(e.salt).toHexString().slice(2).padStart(64,"0"),e.conduitKey.slice(2).padStart(64,"0"),lN.ethers.BigNumber.from(e.counter).toHexString().slice(2).padStart(64,"0")].join(""))};const c=e instanceof lN.providers.Provider?e:e.provider;if(this.signer=e._isSigner?e:void 0,!c)throw new Error("Either a provider or custom signer with provider must be provided");this.provider=c,this.multicallProvider=new cN.providers.MulticallProvider(this.provider),this.contract=new lN.Contract(null!==(o=null==t?void 0:t.contractAddress)&&void 0!==o?o:"1.5"===a?hN.CROSS_CHAIN_SEAPORT_V1_5_ADDRESS:hN.CROSS_CHAIN_SEAPORT_V1_4_ADDRESS,pN.SeaportABIv14,this.multicallProvider),this.domainRegistry=new lN.Contract(null!==(s=null==t?void 0:t.domainRegistryAddress)&&void 0!==s?s:hN.DOMAIN_REGISTRY_ADDRESS,fN.DomainRegistryABI,this.multicallProvider),this.config={ascendingAmountFulfillmentBuffer:n,balanceAndApprovalChecksOnOrderCreation:r,conduitKeyToConduit:Object.assign(Object.assign(Object.assign({},hN.KNOWN_CONDUIT_KEYS_TO_CONDUIT),{[hN.NO_CONDUIT]:this.contract.address}),i),seaportVersion:a},this.defaultConduitKey=null!==(u=null==t?void 0:t.defaultConduitKey)&&void 0!==u?u:hN.NO_CONDUIT}createOrder(e,t,n){return uN(this,void 0,void 0,(function*(){const r=this._getSigner(t),i=null!=t?t:yield r.getAddress(),{orderComponents:a,approvalActions:o}=yield this._formatOrder(r,i,Boolean(n),e),s={type:"create",getMessageToSign:()=>this._getMessageToSign(a),createOrder:()=>uN(this,void 0,void 0,(function*(){const e=yield this.signOrder(a,i);return{parameters:a,signature:e}}))},u=[...o,s];return{actions:u,executeAllActions:()=>(0,TN.executeAllActions)(u)}}))}createBulkOrders(e,t,n){var r;return uN(this,void 0,void 0,(function*(){const i=this._getSigner(t),a=yield i.getAddress(),o=yield this.getCounter(a),s=[],u=[];for(const t of e){null!==(r=t.counter)&&void 0!==r||(t.counter=o);const{orderComponents:e,approvalActions:c}=yield this._formatOrder(i,a,Boolean(n),t);u.push(e);for(const e of c)void 0===s.find((t=>t.token===e.token))&&s.push(e)}const c={type:"createBulk",getMessageToSign:()=>this._getBulkMessageToSign(u),createBulkOrders:()=>uN(this,void 0,void 0,(function*(){return yield this.signBulkOrder(u,a)}))},l=[...s,c];return{actions:l,executeAllActions:()=>(0,TN.executeAllActions)(l)}}))}_formatOrder(e,t,n,{conduitKey:r=this.defaultConduitKey,zone:i=lN.ethers.constants.AddressZero,zoneHash:a=lN.ethers.constants.HashZero,startTime:o=Math.floor(Date.now()/1e3).toString(),endTime:s=hN.MAX_INT.toString(),offer:u,consideration:c,counter:l,allowPartialFills:d,restrictedByZone:f,fees:p,domain:h,salt:m}){var y;return uN(this,void 0,void 0,(function*(){const g=u.map(wN.mapInputItemToOfferItem),b=[...c.map((e=>{var n;return Object.assign(Object.assign({},(0,wN.mapInputItemToOfferItem)(e)),{recipient:null!==(n=e.recipient)&&void 0!==n?n:t})}))];if((null==p?void 0:p.length)&&!(0,wN.areAllCurrenciesSame)({offer:g,consideration:b}))throw new Error("All currency tokens in the order must be the same token when applying fees");const v=[...g,...b].filter(vN.isCurrencyItem),w=(0,wN.totalItemsAmount)(v),T=this.config.conduitKeyToConduit[r],A=this._getOrderTypeFromOrderOptions({allowPartialFills:d,restrictedByZone:f}),E=[...(0,wN.deductFees)(b,p),...v.length&&null!==(y=null==p?void 0:p.map((e=>(0,wN.feeToConsiderationItem)({fee:e,token:v[0].token,baseAmount:w.startAmount,baseEndAmount:w.endAmount}))))&&void 0!==y?y:[]],_=void 0!==m?`0x${lN.BigNumber.from(m).toHexString().slice(2).padStart(64,"0")}`:(0,wN.generateRandomSalt)(h),I={offerer:t,zone:i,zoneHash:a,startTime:o,endTime:s,orderType:A,offer:g,consideration:E,totalOriginalConsiderationItems:E.length,salt:_,conduitKey:r,counter:(null!=l?l:yield this.getCounter(t)).toString()},R=[];if(this.config.balanceAndApprovalChecksOnOrderCreation){const r=yield(0,yN.getBalancesAndApprovals)({owner:t,items:g,criterias:[],multicallProvider:this.multicallProvider,operator:T}),i=(0,yN.validateOfferBalancesAndApprovals)({offer:g,criterias:[],balancesAndApprovals:r,throwOnInsufficientBalances:!0,operator:T}),a=(0,mN.getApprovalActions)(i,n,e);R.push(...a)}return{orderComponents:I,approvalActions:R}}))}_getSigner(e){if(this.signer)return this.signer;if(!(this.provider instanceof lN.providers.JsonRpcProvider))throw new Error("Either signer or a JsonRpcProvider must be provided");return this.provider.getSigner(e)}_getOrderTypeFromOrderOptions({allowPartialFills:e,restrictedByZone:t}){return e?t?hN.OrderType.PARTIAL_RESTRICTED:hN.OrderType.PARTIAL_OPEN:t?hN.OrderType.FULL_RESTRICTED:hN.OrderType.FULL_OPEN}_getDomainData(){return uN(this,void 0,void 0,(function*(){const{chainId:e}=yield this.provider.getNetwork();return{name:hN.SEAPORT_CONTRACT_NAME,version:"1.5"===this.config.seaportVersion?hN.SEAPORT_CONTRACT_VERSION_V1_5:hN.SEAPORT_CONTRACT_VERSION_V1_4,chainId:e,verifyingContract:this.contract.address}}))}_getMessageToSign(e){return uN(this,void 0,void 0,(function*(){const t=yield this._getDomainData();return JSON.stringify(dN._TypedDataEncoder.getPayload(t,hN.EIP_712_ORDER_TYPE,e))}))}_getBulkMessageToSign(e){return uN(this,void 0,void 0,(function*(){const t=yield this._getDomainData(),n=(0,gN.getBulkOrderTree)(e),r=n.types,i=n.getDataToSign();return JSON.stringify(dN._TypedDataEncoder.getPayload(t,r,{tree:i}))}))}signOrder(e,t){return uN(this,void 0,void 0,(function*(){const n=this._getSigner(t),r=yield this._getDomainData();let i=yield n._signTypedData(r,hN.EIP_712_ORDER_TYPE,e);return 132===i.length&&(i=lN.ethers.utils.splitSignature(i).compact),i}))}signBulkOrder(e,t){return uN(this,void 0,void 0,(function*(){const n=this._getSigner(t),r=yield this._getDomainData(),i=(0,gN.getBulkOrderTree)(e),a=i.types,o={tree:i.getDataToSign()};let s=yield n._signTypedData(r,a,o);132===s.length&&(s=lN.ethers.utils.splitSignature(s).compact);return e.map(((e,t)=>({parameters:e,signature:i.getEncodedProofAndSignature(t,s)})))}))}cancelOrders(e,t,n){const r=this._getSigner(t);return(0,TN.getTransactionMethods)(this.contract.connect(r),"cancel",[e],n)}bulkCancelOrders(e,t){const n=this._getSigner(e);return(0,TN.getTransactionMethods)(this.contract.connect(n),"incrementCounter",[],t)}validate(e,t,n){const r=this._getSigner(t);return(0,TN.getTransactionMethods)(this.contract.connect(r),"validate",[e],n)}getOrderStatus(e){return this.contract.getOrderStatus(e)}getCounter(e){return this.contract.getCounter(e)}fulfillOrder({order:e,unitsToFill:t,offerCriteria:n=[],considerationCriteria:r=[],tips:i=[],extraData:a="0x",accountAddress:o,conduitKey:s=this.defaultConduitKey,recipientAddress:u=lN.ethers.constants.AddressZero,domain:c,exactApproval:l=!1}){return uN(this,void 0,void 0,(function*(){if(!e.signature)throw new Error("Order is missing signature");const{parameters:d}=e,{offerer:f,offer:p,consideration:h}=d,m=this._getSigner(o),y=yield m.getAddress(),g=this.config.conduitKeyToConduit[d.conduitKey],b=this.config.conduitKeyToConduit[s],[v,w,T,A]=yield Promise.all([(0,yN.getBalancesAndApprovals)({owner:f,items:p,criterias:n,multicallProvider:this.multicallProvider,operator:g}),(0,yN.getBalancesAndApprovals)({owner:y,items:[...p,...h],criterias:[...n,...r],multicallProvider:this.multicallProvider,operator:b}),this.multicallProvider.getBlock("latest"),this.getOrderStatus(this.getOrderHash(d))]),E=T.timestamp,{totalFilled:_,totalSize:I}=A,R=(0,bN.validateAndSanitizeFromOrderStatus)(e,A),C={startTime:R.parameters.startTime,endTime:R.parameters.endTime,currentBlockTimestamp:E,ascendingAmountTimestampBuffer:this.config.ascendingAmountFulfillmentBuffer},k=i.map((e=>Object.assign(Object.assign({},(0,wN.mapInputItemToOfferItem)(e)),{recipient:e.recipient}))),O=u===lN.ethers.constants.AddressZero;return!t&&O&&(0,bN.shouldUseBasicFulfill)(R.parameters,_)?(0,bN.fulfillBasicOrder)({order:R,seaportContract:this.contract,offererBalancesAndApprovals:v,fulfillerBalancesAndApprovals:w,timeBasedItemParams:C,conduitKey:s,offererOperator:g,fulfillerOperator:b,signer:m,tips:k,domain:c},l):(0,bN.fulfillStandardOrder)({order:R,unitsToFill:t,totalFilled:_,totalSize:I.eq(0)?(0,vN.getMaximumSizeForOrder)(R):I,offerCriteria:n,considerationCriteria:r,tips:k,extraData:a,seaportContract:this.contract,offererBalancesAndApprovals:v,fulfillerBalancesAndApprovals:w,timeBasedItemParams:C,conduitKey:s,signer:m,offererOperator:g,fulfillerOperator:b,recipientAddress:u,domain:c},l)}))}fulfillOrders({fulfillOrderDetails:e,accountAddress:t,conduitKey:n=this.defaultConduitKey,recipientAddress:r=lN.ethers.constants.AddressZero,domain:i,exactApproval:a=!1}){return uN(this,void 0,void 0,(function*(){if(e.some((e=>!e.order.signature)))throw new Error("All orders must include signatures");const o=this._getSigner(t),s=yield o.getAddress(),u=e.map((({order:e})=>this.config.conduitKeyToConduit[e.parameters.conduitKey])),c=this.config.conduitKeyToConduit[n],l=e.flatMap((({order:e})=>e.parameters.offer)),d=e.flatMap((({order:e})=>e.parameters.consideration)),f=e.flatMap((({offerCriteria:e=[]})=>e)),p=e.flatMap((({considerationCriteria:e=[]})=>e)),[h,m,y,g]=yield Promise.all([Promise.all(e.map((({order:e,offerCriteria:t=[]},n)=>(0,yN.getBalancesAndApprovals)({owner:e.parameters.offerer,items:e.parameters.offer,criterias:t,operator:u[n],multicallProvider:this.multicallProvider})))),(0,yN.getBalancesAndApprovals)({owner:s,items:[...l,...d],criterias:[...f,...p],operator:c,multicallProvider:this.multicallProvider}),this.multicallProvider.getBlock("latest"),Promise.all(e.map((({order:e})=>this.getOrderStatus(this.getOrderHash(e.parameters)))))]),b=e.map(((e,t)=>{var n,r,i,a,o;return{order:e.order,unitsToFill:e.unitsToFill,orderStatus:g[t],offerCriteria:null!==(n=e.offerCriteria)&&void 0!==n?n:[],considerationCriteria:null!==(r=e.considerationCriteria)&&void 0!==r?r:[],tips:null!==(a=null===(i=e.tips)||void 0===i?void 0:i.map((e=>Object.assign(Object.assign({},(0,wN.mapInputItemToOfferItem)(e)),{recipient:e.recipient}))))&&void 0!==a?a:[],extraData:null!==(o=e.extraData)&&void 0!==o?o:"0x",offererBalancesAndApprovals:h[t],offererOperator:u[t]}}));return(0,bN.fulfillAvailableOrders)({ordersMetadata:b,seaportContract:this.contract,fulfillerBalancesAndApprovals:m,currentBlockTimestamp:y.timestamp,ascendingAmountTimestampBuffer:this.config.ascendingAmountFulfillmentBuffer,fulfillerOperator:c,signer:o,conduitKey:n,recipientAddress:r,domain:i,exactApproval:a})}))}matchOrders({orders:e,fulfillments:t,overrides:n,accountAddress:r,domain:i}){const a=this._getSigner(r);return(0,TN.getTransactionMethods)(this.contract.connect(a),"matchOrders",[e,t,n],i)}setDomain(e,t){const n=this._getSigner(t);return(0,TN.getTransactionMethods)(this.domainRegistry.connect(n),"setDomain",[e])}getNumberOfDomains(e){return uN(this,void 0,void 0,(function*(){return this.domainRegistry.getNumberOfDomains(e)}))}getDomain(e,t){return this.domainRegistry.getDomain(e,t)}getDomains(e,t){return uN(this,void 0,void 0,(function*(){try{if(t)throw Error;return this.domainRegistry.getDomains(e)}catch(t){const n=(yield this.domainRegistry.getNumberOfDomains(e)).toNumber();return Promise.all([...Array(n).keys()].map((t=>this.domainRegistry.getDomain(e,t))))}}))}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Seaport=void 0;const t=jR;Object.defineProperty(e,"Seaport",{enumerable:!0,get:function(){return t.Seaport}})}(qR);class AN{config;constructor(e){this.config=e}}class EN extends Error{url;status;statusText;body;request;constructor(e,t,n){super(n),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}}class _N extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}}class IN{[Symbol.toStringTag];_isResolved;_isRejected;_isCancelled;_cancelHandlers;_promise;_resolve;_reject;constructor(e){this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise(((t,n)=>{this._resolve=t,this._reject=n;const r=e=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(e)};return Object.defineProperty(r,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(r,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(r,"isCancelled",{get:()=>this._isCancelled}),e((e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(e))}),(e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(e))}),r)}))}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(const e of this._cancelHandlers)e()}catch(e){return void console.warn("Cancellation threw an error",e)}this._cancelHandlers.length=0,this._reject?.(new _N("Request aborted"))}}get isCancelled(){return this._isCancelled}}const RN=e=>null!=e,CN=e=>"string"==typeof e,kN=e=>CN(e)&&""!==e,ON=e=>"object"==typeof e&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.arrayBuffer&&"function"==typeof e.constructor&&"string"==typeof e.constructor.name&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),SN=e=>{const t=[],n=(e,r)=>{RN(r)&&(Array.isArray(r)?r.forEach((t=>{n(e,t)})):"object"==typeof r?Object.entries(r).forEach((([t,r])=>{n(`${e}[${t}]`,r)})):((e,n)=>{t.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(n))}`)})(e,r))};return Object.entries(e).forEach((([e,t])=>{n(e,t)})),t.length>0?`?${t.join("&")}`:""},NN=async(e,t)=>"function"==typeof t?t(e):t,xN=async(e,t,n)=>{const r=await NN(t,e.TOKEN),i=await NN(t,e.USERNAME),a=await NN(t,e.PASSWORD),o=await NN(t,e.HEADERS),s="function"==typeof n?.getHeaders&&n?.getHeaders()||{},u=Object.entries({Accept:"application/json",...o,...t.headers,...s}).filter((([e,t])=>RN(t))).reduce(((e,[t,n])=>({...e,[t]:String(n)})),{});if(kN(r)&&(u.Authorization=`Bearer ${r}`),kN(i)&&kN(a)){const e=(e=>{try{return btoa(e)}catch(t){return Buffer.from(e).toString("base64")}})(`${i}:${a}`);u.Authorization=`Basic ${e}`}return t.body&&(t.mediaType?u["Content-Type"]=t.mediaType:ON(t.body)?u["Content-Type"]=t.body.type||"application/octet-stream":CN(t.body)?u["Content-Type"]="text/plain":t.body instanceof UR||(u["Content-Type"]="application/json")),u},PN=(e,t)=>new IN((async(n,r,i)=>{try{const r=((e,t)=>{const n=e.ENCODE_PATH||encodeURI,r=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,((e,r)=>t.path?.hasOwnProperty(r)?n(String(t.path[r])):e)),i=`${e.BASE}${r}`;return t.query?`${i}${SN(t.query)}`:i})(e,t),o=(e=>{if(e.formData){const t=new UR,n=(e,n)=>{CN(n)||ON(n)?t.append(e,n):t.append(e,JSON.stringify(n))};return Object.entries(e.formData).filter((([e,t])=>RN(t))).forEach((([e,t])=>{Array.isArray(t)?t.forEach((t=>n(e,t))):n(e,t)})),t}})(t),s=(e=>{if(e.body)return e.body})(t),u=await xN(e,t,o);if(!i.isCancelled){const c=await(async(e,t,n,r,i,a,o)=>{const s=Ve.CancelToken.source(),u={url:n,headers:a,data:r??i,method:t.method,withCredentials:e.WITH_CREDENTIALS,cancelToken:s.token};o((()=>s.cancel("The user aborted a request.")));try{return await Ve.request(u)}catch(e){const t=e;if(t.response)return t.response;throw e}})(e,t,r,s,o,u,i),l=(e=>{if(204!==e.status)return e.data})(c),d=((e,t)=>{if(t){const n=e.headers[t];if(CN(n))return n}})(c,t.responseHeader),f={url:r,ok:(a=c.status,a>=200&&a<300),status:c.status,statusText:c.statusText,body:d??l};((e,t)=>{const n={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(n)throw new EN(e,t,n);if(!t.ok)throw new EN(e,t,"Generic Error")})(t,f),n(f.body)}}catch(e){r(e)}var a}));class MN extends AN{constructor(e){super(e)}request(e){return PN(this.config,e)}}class BN{httpRequest;constructor(e){this.httpRequest=e}cancelOrders({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/cancel",path:{chain_name:e},body:t,mediaType:"application/json",errors:{400:"Bad Request (400)",401:"Unauthorised Request (401)",404:"The specified resource was not found (404)",429:"Too Many Requests (429)",500:"Internal Server Error (500)",501:"Not Implemented Error (501)"}})}listListings({chainName:e,status:t,sellItemContractAddress:n,buyItemContractAddress:r,sellItemTokenId:i,fromUpdatedAt:a,pageSize:o,sortBy:s,sortDirection:u,pageCursor:c}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:e},query:{status:t,sell_item_contract_address:n,buy_item_contract_address:r,sell_item_token_id:i,from_updated_at:a,page_size:o,sort_by:s,sort_direction:u,page_cursor:c},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}createListing({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/listings",path:{chain_name:e},body:t,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getListing({chainName:e,listingId:t}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/orders/listings/{listing_id}",path:{chain_name:e,listing_id:t},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}fulfillmentData({chainName:e,requestBody:t}){return this.httpRequest.request({method:"POST",url:"/v1/chains/{chain_name}/orders/fulfillment-data",path:{chain_name:e},body:t,mediaType:"application/json",errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}listTrades({chainName:e,accountAddress:t,fromIndexedAt:n,pageSize:r,sortBy:i,sortDirection:a,pageCursor:o}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades",path:{chain_name:e},query:{account_address:t,from_indexed_at:n,page_size:r,sort_by:i,sort_direction:a,page_cursor:o},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}getTrade({chainName:e,tradeId:t}){return this.httpRequest.request({method:"GET",url:"/v1/chains/{chain_name}/trades/{trade_id}",path:{chain_name:e,trade_id:t},errors:{400:"Bad Request (400)",404:"The specified resource was not found (404)",500:"Internal Server Error (500)"}})}}class DN{orders;request;constructor(e,t=MN){this.request=new t({BASE:e?.BASE??"https://api.sandbox.immutable.com",VERSION:e?.VERSION??"1.0.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.orders=new BN(this.request)}}var FN,LN,UN,qN,jN,GN,HN,zN,VN;function WN(e){const t=e.buy.map((e=>{if("ERC20"===e.item_type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.amount};if("NATIVE"===e.item_type)return{type:"NATIVE",amount:e.amount};throw new Error("Buy items must be either ERC20 or NATIVE")})),n=e.sell.map((e=>{if("ERC721"===e.item_type)return{type:"ERC721",contractAddress:e.contract_address,tokenId:e.token_id};throw new Error("Sell items must ERC721")}));return{id:e.id,accountAddress:e.account_address,buy:t,sell:n,fees:e.fees.map((e=>({amount:e.amount,recipient:e.recipient,type:e.fee_type}))),chain:e.chain,createdAt:e.created_at,endAt:e.end_at,protocolData:{counter:e.protocol_data.counter,orderType:e.protocol_data.order_type,seaportAddress:e.protocol_data.seaport_address,seaportVersion:e.protocol_data.seaport_version,zoneAddress:e.protocol_data.zone_address},salt:e.salt,signature:e.signature,startAt:e.start_at,status:e.status,updatedAt:e.updated_at}}function KN(e){const t=e.buy.map((e=>{if("ERC20"===e.item_type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.amount};if("NATIVE"===e.item_type)return{type:"NATIVE",amount:e.amount};throw new Error("Buy items must be either ERC20 or NATIVE")})),n=e.sell.map((e=>{if("ERC721"===e.item_type)return{type:"ERC721",contractAddress:e.contract_address,tokenId:e.token_id};throw new Error("Sell items must ERC721")}));return{id:e.id,orderId:e.order_id,buy:t,sell:n,buyerFees:e.buyer_fees.map((e=>({amount:e.amount,recipient:e.recipient,type:e.fee_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 XN(e){return{nextCursor:e.next_cursor,previousCursor:e.previous_cursor}}!function(e){var t;(t=e.cancellation_type||(e.cancellation_type={})).ON_CHAIN="ON_CHAIN",t.OFF_CHAIN="OFF_CHAIN"}(FN||(FN={})),function(e){(e.reason_code||(e.reason_code={})).FILLED="FILLED"}(LN||(LN={})),function(e){var t;(t=e.fee_type||(e.fee_type={})).ROYALTY="ROYALTY",t.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",t.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",t.PROTOCOL="PROTOCOL"}(UN||(UN={})),function(e){e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.FILLED="FILLED",e.EXPIRED="EXPIRED",e.CANCELLED="CANCELLED"}(qN||(qN={})),function(e){(e.order_type||(e.order_type={})).FULL_RESTRICTED="FULL_RESTRICTED"}(jN||(jN={})),function(e){e.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",e.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",e.PROTOCOL="PROTOCOL",e.ROYALTY="ROYALTY"}(GN||(GN={})),function(e){e.APPROVAL="APPROVAL",e.FULFILL_ORDER="FULFILL_ORDER",e.CANCEL="CANCEL"}(HN||(HN={})),function(e){e.CREATE_LISTING="CREATE_LISTING",e.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION"}(zN||(zN={})),function(e){e.TRANSACTION="TRANSACTION",e.SIGNABLE="SIGNABLE"}(VN||(VN={}));const JN="1.5",YN={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 QN,ZN,$N,ex;function tx(e,t){return async()=>{const n=await e.buildTransaction();return n.gasLimit=await e.estimateGas(),n.gasLimit=n.gasLimit.add(n.gasLimit.div(5)),n.chainId=t,n}}!function(e){e[e.FULL_OPEN=0]="FULL_OPEN",e[e.PARTIAL_OPEN=1]="PARTIAL_OPEN",e[e.FULL_RESTRICTED=2]="FULL_RESTRICTED",e[e.PARTIAL_RESTRICTED=3]="PARTIAL_RESTRICTED"}(QN||(QN={})),function(e){e[e.NATIVE=0]="NATIVE",e[e.ERC20=1]="ERC20",e[e.ERC721=2]="ERC721",e[e.ERC1155=3]="ERC1155",e[e.ERC721_WITH_CRITERIA=4]="ERC721_WITH_CRITERIA",e[e.ERC1155_WITH_CRITERIA=5]="ERC1155_WITH_CRITERIA"}(ZN||(ZN={})),function(e){e[e.OFFER=0]="OFFER",e[e.CONSIDERATION=1]="CONSIDERATION"}($N||($N={})),function(e){e[e.ETH_TO_ERC721=0]="ETH_TO_ERC721",e[e.ETH_TO_ERC1155=1]="ETH_TO_ERC1155",e[e.ERC20_TO_ERC721=2]="ERC20_TO_ERC721",e[e.ERC20_TO_ERC1155=3]="ERC20_TO_ERC1155",e[e.ERC721_TO_ERC20=4]="ERC721_TO_ERC20",e[e.ERC1155_TO_ERC20=5]="ERC1155_TO_ERC20"}(ex||(ex={}));class nx{seaportLibFactory;provider;seaportContractAddress;zoneContractAddress;constructor(e,t,n,r){this.seaportLibFactory=e,this.provider=t,this.seaportContractAddress=n,this.zoneContractAddress=r}async prepareSeaportOrder(e,t,n,r,i){const{actions:a}=await this.createSeaportOrder(e,t,n,r,i),o=[],s=a.find((e=>"approval"===e.type));s&&o.push({type:VN.TRANSACTION,purpose:HN.APPROVAL,buildTransaction:tx(s.transactionMethods,(await this.provider.getNetwork()).chainId)});const u=a.find((e=>"create"===e.type));if(!u)throw new Error("No create order action found");const c=function(e){const t=JSON.parse(e).message;return t.salt=tr.from(t.salt).toHexString(),t}(await u.getMessageToSign());return o.push({type:VN.SIGNABLE,purpose:zN.CREATE_LISTING,message:await this.getTypedDataFromOrderComponents(c)}),{actions:o,orderComponents:c,orderHash:this.getSeaportLib().getOrderHash(c)}}async fulfillOrder(e,t,n){const{orderComponents:r,tips:i}=this.mapImmutableOrderToSeaportOrderComponents(e),a=this.getSeaportLib(e),{actions:o}=await a.fulfillOrders({accountAddress:t,fulfillOrderDetails:[{order:{parameters:r,signature:e.signature},extraData:n,tips:i}]}),s=[],u=o.find((e=>"approval"===e.type));u&&s.push({type:VN.TRANSACTION,buildTransaction:tx(u.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:HN.APPROVAL});const c=o.find((e=>"exchange"===e.type));if(!c)throw new Error("No exchange action found");return s.push({type:VN.TRANSACTION,buildTransaction:tx(c.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:HN.FULFILL_ORDER}),{actions:s,expiration:nx.getExpirationISOTimeFromExtraData(n),order:WN(e)}}async fulfillBulkOrders(e,t){const n=e.map((e=>{const{orderComponents:t,tips:n}=this.mapImmutableOrderToSeaportOrderComponents(e.order);return{order:{parameters:t,signature:e.order.signature},extraData:e.extra_data,tips:n}})),{actions:r}=await this.getSeaportLib().fulfillOrders({fulfillOrderDetails:n,accountAddress:t}),i=[],a=r.find((e=>"approval"===e.type));a&&i.push({type:VN.TRANSACTION,buildTransaction:tx(a.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:HN.APPROVAL});const o=r.find((e=>"exchange"===e.type));if(!o)throw new Error("No exchange action found");return i.push({type:VN.TRANSACTION,buildTransaction:tx(o.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:HN.FULFILL_ORDER}),{actions:i,expiration:n.map((e=>nx.getExpirationISOTimeFromExtraData(e.extraData))).reduce(((e,t)=>new Date(e)<new Date(t)?e:t))}}async cancelOrders(e,t){const n=e.map((e=>this.mapImmutableOrderToSeaportOrderComponents(e).orderComponents)),r=this.getSeaportLib(e[0]),i=await r.cancelOrders(n,t);return{type:VN.TRANSACTION,buildTransaction:tx(i,(await this.provider.getNetwork()).chainId),purpose:HN.CANCEL}}mapImmutableOrderToSeaportOrderComponents(e){return function(e,t,n){const r=e.buy.map((t=>{switch(t.item_type){case"NATIVE":return{startAmount:t.amount,endAmount:t.amount,itemType:ZN.NATIVE,recipient:e.account_address,token:ji,identifierOrCriteria:"0"};case"ERC20":return{startAmount:t.amount,endAmount:t.amount,itemType:ZN.ERC20,recipient:e.account_address,token:t.contract_address||ji,identifierOrCriteria:"0"};default:return{startAmount:"1",endAmount:"1",itemType:ZN.ERC721,recipient:e.account_address,token:t.contract_address||ji,identifierOrCriteria:"0"}}})),i=e.fees.map((t=>({amount:t.amount,itemType:"ERC20"===e.buy[0].item_type?ZN.ERC20:ZN.NATIVE,recipient:t.recipient,token:"ERC20"===e.buy[0].item_type?e.buy[0].contract_address:ji,identifierOrCriteria:"0"})));return{orderComponents:{conduitKey:Yi,consideration:[...r],offer:e.sell.map((e=>{const t=e;return{startAmount:"1",endAmount:"1",itemType:ZN.ERC721,token:t.contract_address,identifierOrCriteria:t.token_id}})),counter:t,endTime:Math.round(new Date(e.end_at).getTime()/1e3).toString(),startTime:Math.round(new Date(e.start_at).getTime()/1e3).toString(),salt:e.salt,offerer:e.account_address,zone:n,totalOriginalConsiderationItems:r.length,orderType:QN.FULL_RESTRICTED,zoneHash:Yi},tips:i}}(e,e.protocol_data.counter,this.zoneContractAddress)}createSeaportOrder(e,t,n,r,i){return this.getSeaportLib().createOrder({allowPartialFills:!1,offer:[{itemType:ZN.ERC721,token:t.contractAddress,identifier:t.tokenId}],consideration:[{token:"ERC20"===n.type?n.contractAddress:void 0,amount:n.amount,recipient:e}],startTime:(r.getTime()/1e3).toFixed(0),endTime:(i.getTime()/1e3).toFixed(0),zone:this.zoneContractAddress,restrictedByZone:!0},e)}async getTypedDataFromOrderComponents(e){const{chainId:t}=await this.provider.getNetwork();return{domain:{name:"ImmutableSeaport",version:JN,chainId:t,verifyingContract:this.seaportContractAddress},types:YN,value:e}}getSeaportLib(e){const t=e?.protocol_data?.seaport_address??this.seaportContractAddress,n=JN;return this.seaportLibFactory.create(n,t)}static getExpirationISOTimeFromExtraData(e){const t=e.slice(44,60),n=parseInt(t,16);return new Date(1e3*n).toISOString()}}class rx{orderbookService;chainName;seaportAddress;constructor(e,t,n){this.orderbookService=e,this.chainName=t,this.seaportAddress=n}async fulfillmentData(e){return this.orderbookService.fulfillmentData({chainName:this.chainName,requestBody:e})}async getListing(e){return this.orderbookService.getListing({chainName:this.chainName,listingId:e})}async getTrade(e){return this.orderbookService.getTrade({chainName:this.chainName,tradeId:e})}async listListings(e){return this.orderbookService.listListings({chainName:this.chainName,...e})}async listTrades(e){return this.orderbookService.listTrades({chainName:this.chainName,...e})}async cancelOrders(e,t,n){return this.orderbookService.cancelOrders({chainName:this.chainName,requestBody:{account_address:t,orders:e,signature:n}})}async createListing({orderHash:e,orderComponents:t,orderSignature:n,makerFees:r}){if(1!==t.offer.length)throw new Error("Only one item can be listed at a time");if(Number(t.offer[0].itemType)!==ZN.ERC721)throw new Error("Only ERC721 tokens can be listed");const i=[...t.consideration.map((e=>e.itemType))];if(!(1===new Set(i).size))throw new Error("All consideration items must be of the same type");return this.orderbookService.createListing({chainName:this.chainName,requestBody:{order_hash:e,account_address:t.offerer,buy:[{item_type:Number(t.consideration[0].itemType)===ZN.NATIVE?"NATIVE":"ERC20",amount:t.consideration[0].startAmount,contract_address:t.consideration[0].token}],fees:r.map((e=>({amount:e.amount,fee_type:GN.MAKER_ECOSYSTEM,recipient:e.recipient}))),end_at:new Date(parseInt(`${t.endTime.toString()}000`,10)).toISOString(),protocol_data:{order_type:jN.order_type.FULL_RESTRICTED,zone_address:t.zone,seaport_address:this.seaportAddress,seaport_version:JN,counter:t.counter.toString()},salt:t.salt,sell:[{contract_address:t.offer[0].token,token_id:t.offer[0].identifierOrCriteria,item_type:"ERC721"}],signature:n,start_at:new Date(parseInt(`${t.startTime.toString()}000`,10)).toISOString()}})}}class ix{chainName;seaportAddress;orderbookClient;constructor(e,t,n){this.chainName=t,this.seaportAddress=n,this.orderbookClient=new DN({BASE:e})}create(){return new rx(this.orderbookClient.orders,this.chainName,this.seaportAddress)}}class ax{defaultSeaportContractAddress;provider;constructor(e,t){this.defaultSeaportContractAddress=e,this.provider=t}create(e,t){const n=e??JN,r=t??this.defaultSeaportContractAddress;return new qR.Seaport(this.provider,{seaportVersion:n,balanceAndApprovalChecksOnOrderCreation:!0,overrides:{contractAddress:r}})}}class ox{apiClient;seaport;orderbookConfig;constructor(e){const t={...function(e){switch(e){case st.SANDBOX:return{seaportContractAddress:"0x2CFA8f64e1B49A2DF28532D1D30Cda45117cF778",zoneContractAddress:"0x1Bb4Fb11Ba021Bd0104F0Ee8E5F5c728Bc83d7F1",apiEndpoint:"https://api.sandbox.immutable.com",chainName:"imtbl-zkevm-testnet",provider:new up("https://rpc.testnet.immutable.com")};case st.PRODUCTION:return{seaportContractAddress:"",zoneContractAddress:"",apiEndpoint:"https://api.immutable.com",chainName:"imtbl-zkevm-mainnet",provider:new up("https://rpc.immutable.com")};default:return null}}(e.baseConfig.environment),...e.overrides};if(!t)throw new Error("Orderbook configuration not passed, please specify the environment under config.baseConfig.environment");this.orderbookConfig=t;const{apiEndpoint:n,chainName:r}=this.orderbookConfig;if(!n)throw new Error("API endpoint must be provided");this.apiClient=new ix(n,r,this.orderbookConfig.seaportContractAddress).create();const i=new ax(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new nx(i,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress)}config(){return this.orderbookConfig}async getListing(e){return{result:WN((await this.apiClient.getListing(e)).result)}}async getTrade(e){return{result:KN((await this.apiClient.getTrade(e)).result)}}async listListings(e){const t=await this.apiClient.listListings(e);return{page:XN(t.page),result:t.result.map(WN)}}async listTrades(e){const t=await this.apiClient.listTrades(e);return{page:XN(t.page),result:t.result.map(KN)}}async prepareListing({makerAddress:e,sell:t,buy:n,orderExpiry:r}){return this.seaport.prepareSeaportOrder(e,t,n,new Date,r||new Date(Date.now()+63072e6))}async createListing(e){return{result:WN((await this.apiClient.createListing({...e})).result)}}async fulfillOrder(e,t,n){const r=await this.apiClient.fulfillmentData([{order_id:e,fees:n.map((e=>({amount:e.amount,fee_type:GN.TAKER_ECOSYSTEM,recipient:e.recipient})))}]);if(r.result.unfulfillable_orders?.length>0)throw new Error(`Unable to prepare fulfillment date: ${r.result.unfulfillable_orders[0].reason}`);if(1!==r.result.fulfillable_orders?.length)throw new Error("unexpected fulfillable order result length");const i=r.result.fulfillable_orders[0].extra_data,a=r.result.fulfillable_orders[0].order;if(a.status.name!==qN.ACTIVE)throw new Error(`Cannot fulfil order that is not active. Current status: ${a.status}`);return this.seaport.fulfillOrder(a,t,i)}async fulfillBulkOrders(e,t){const n=await this.apiClient.fulfillmentData(e.map((e=>({order_id:e.listingId,fees:e.takerFees.map((e=>({amount:e.amount,fee_type:GN.TAKER_ECOSYSTEM,recipient:e.recipient})))}))));try{return{...await this.seaport.fulfillBulkOrders(n.result.fulfillable_orders,t),fulfillableOrders:n.result.fulfillable_orders.map((e=>WN(e.order))),unfulfillableOrders:n.result.unfulfillable_orders.map((e=>({orderId:e.order_id,reason:e.reason}))),sufficientBalance:!0}}catch(e){if(String(e).includes("The fulfiller does not have the balances needed to fulfill."))return{fulfillableOrders:n.result.fulfillable_orders.map((e=>WN(e.order))),unfulfillableOrders:n.result.unfulfillable_orders.map((e=>({orderId:e.order_id,reason:e.reason}))),sufficientBalance:!1};throw e}}async prepareOrderCancellations(e){const t={name:"imtbl-order-book",chainId:(await this.orderbookConfig.provider.getNetwork()).chainId,verifyingContract:this.orderbookConfig.seaportContractAddress},n={orders:e.map((e=>({id:e})))};return{signableAction:{purpose:zN.OFF_CHAIN_CANCELLATION,type:VN.SIGNABLE,message:{domain:t,types:{CancelPayload:[{name:"orders",type:"Order[]"}],Order:[{name:"id",type:"string"}]},value:n}}}}async cancelOrders(e,t,n){return this.apiClient.cancelOrders(e,t,n)}async cancelOrdersOnChain(e,t){const n=await Promise.all(e.map((e=>this.apiClient.getListing(e))));for(const e of n){if(e.result.status.name!==qN.ACTIVE&&e.result.status.name!==qN.INACTIVE&&e.result.status.name!==qN.PENDING)throw new Error(`Cannot cancel order with status ${e.result.status}`);if(e.result.account_address!==t.toLowerCase())throw new Error(`Only account ${e.result.account_address} can cancel order ${e.result.id}`)}const r=n.map((e=>e.result)),i=r.map((e=>e.protocol_data.seaport_address));if(1!==new Set(...[i]).size)throw new Error("Cannot cancel multiple orders from different seaport contracts. Please group your orderIds accordingly");return{cancellationAction:await this.seaport.cancelOrders(r,t)}}}const sx=4e5,ux="https://api.sandbox.immutable.com".replace(/\/+$/,"");class cx{basePath;axios;configuration;constructor(e,t=ux,n=Ve){this.basePath=t,this.axios=n,e&&(this.configuration=e,this.basePath=e.basePath||this.basePath)}}class lx extends Error{field;constructor(e,t){super(t),this.field=e,this.name="RequiredError"}}const dx="https://example.com",fx=function(e,t,n){if(null==n)throw new lx(t,`Required parameter ${t} was null or undefined when calling ${e}.`)},px=async function(e,t,n){if(n&&n.apiKey){const r="function"==typeof n.apiKey?await n.apiKey(t):await n.apiKey;e[t]=r}},hx=async function(e,t){if(t&&t.accessToken){const n="function"==typeof t.accessToken?await t.accessToken():await t.accessToken;e.Authorization="Bearer "+n}};function mx(e,t,n=""){null!=t&&("object"==typeof t?Array.isArray(t)?t.forEach((t=>mx(e,t,n))):Object.keys(t).forEach((r=>mx(e,t[r],`${n}${""!==n?".":""}${r}`))):e.has(n)?e.append(n,t):e.set(n,t))}const yx=function(e,...t){const n=new URLSearchParams(e.search);mx(n,t),e.search=n.toString()},gx=function(e,t,n){const r="string"!=typeof e;return(r&&n&&n.isJsonMime?n.isJsonMime(t.headers["Content-Type"]):r)?JSON.stringify(void 0!==e?e:{}):e||""},bx=function(e){return e.pathname+e.search+e.hash},vx=function(e,t,n,r){return(i=t,a=n)=>{const o={...e.options,url:(r?.basePath||i.defaults.baseURL||a)+e.url};return i.request(o)}},wx=function(e){return{getActivity:async(t,n,r={})=>{fx("getActivity","chainName",t),fx("getActivity","activityId",n);const i="/v1/chains/{chain_name}/activities/{activity_id}".replace("{chain_name}",encodeURIComponent(String(t))).replace("{activity_id}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};yx(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:bx(a),options:s}},listActivities:async(t,n,r,i,a,o,s,u,c,l,d={})=>{fx("listActivities","chainName",t);const f="/v1/chains/{chain_name}/activities".replace("{chain_name}",encodeURIComponent(String(t))),p=new URL(f,dx);let h;e&&(h=e.baseOptions);const m={method:"GET",...h,...d},y={};void 0!==n&&(y.contract_address=n),void 0!==r&&(y.token_id=r),void 0!==i&&(y.account_address=i),void 0!==a&&(y.activity_type=a),void 0!==o&&(y.from_indexed_at=o instanceof Date?o.toISOString():o),void 0!==s&&(y.to_indexed_at=s instanceof Date?s.toISOString():s),void 0!==u&&(y.transaction_hash=u),void 0!==c&&(y.page_cursor=c),void 0!==l&&(y.page_size=l),yx(p,y);let g=h&&h.headers?h.headers:{};return m.headers={...g,...d.headers},{url:bx(p),options:m}}}},Tx=function(e){const t=wx(e);return{async getActivity(n,r,i){const a=await t.getActivity(n,r,i);return vx(a,Ve,ux,e)},async listActivities(n,r,i,a,o,s,u,c,l,d,f){const p=await t.listActivities(n,r,i,a,o,s,u,c,l,d,f);return vx(p,Ve,ux,e)}}};const Ax=function(e){return{listChains:async(t,n,r={})=>{const i=new URL("/v1/chains",dx);let a;e&&(a=e.baseOptions);const o={method:"GET",...a,...r},s={};void 0!==t&&(s.page_cursor=t),void 0!==n&&(s.page_size=n),yx(i,s);let u=a&&a.headers?a.headers:{};return o.headers={...u,...r.headers},{url:bx(i),options:o}}}},Ex=function(e){const t=Ax(e);return{async listChains(n,r,i){const a=await t.listChains(n,r,i);return vx(a,Ve,ux,e)}}};const _x=function(e){return{getCollection:async(t,n,r={})=>{fx("getCollection","contractAddress",t),fx("getCollection","chainName",n);const i="/v1/chains/{chain_name}/collections/{contract_address}".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};yx(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:bx(a),options:s}},listCollections:async(t,n,r,i,a,o={})=>{fx("listCollections","chainName",t);const s="/v1/chains/{chain_name}/collections".replace("{chain_name}",encodeURIComponent(String(t))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};n&&(d.contract_address=n),void 0!==r&&(d.from_updated_at=r instanceof Date?r.toISOString():r),void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}},listCollectionsByNFTOwner:async(t,n,r,i,a={})=>{fx("listCollectionsByNFTOwner","accountAddress",t),fx("listCollectionsByNFTOwner","chainName",n);const o="/v1/chains/{chain_name}/accounts/{account_address}/collections".replace("{account_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),s=new URL(o,dx);let u;e&&(u=e.baseOptions);const c={method:"GET",...u,...a},l={};void 0!==r&&(l.page_cursor=r),void 0!==i&&(l.page_size=i),yx(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:bx(s),options:c}},refreshCollectionMetadata:async(t,n,r,i={})=>{fx("refreshCollectionMetadata","contractAddress",t),fx("refreshCollectionMetadata","chainName",n),fx("refreshCollectionMetadata","refreshCollectionMetadataRequest",r);const a="/v1/chains/{chain_name}/collections/{contract_address}/refresh-metadata".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),o=new URL(a,dx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await px(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",yx(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=gx(r,u,e),{url:bx(o),options:u}}}},Ix=function(e){const t=_x(e);return{async getCollection(n,r,i){const a=await t.getCollection(n,r,i);return vx(a,Ve,ux,e)},async listCollections(n,r,i,a,o,s){const u=await t.listCollections(n,r,i,a,o,s);return vx(u,Ve,ux,e)},async listCollectionsByNFTOwner(n,r,i,a,o){const s=await t.listCollectionsByNFTOwner(n,r,i,a,o);return vx(s,Ve,ux,e)},async refreshCollectionMetadata(n,r,i,a){const o=await t.refreshCollectionMetadata(n,r,i,a);return vx(o,Ve,ux,e)}}};const Rx=function(e){return{getMetadata:async(t,n,r,i={})=>{fx("getMetadata","chainName",t),fx("getMetadata","contractAddress",n),fx("getMetadata","metadataId",r);const a="/v1/chains/{chain_name}/collections/{contract_address}/metadata/{metadata_id}".replace("{chain_name}",encodeURIComponent(String(t))).replace("{contract_address}",encodeURIComponent(String(n))).replace("{metadata_id}",encodeURIComponent(String(r))),o=new URL(a,dx);let s;e&&(s=e.baseOptions);const u={method:"GET",...s,...i};yx(o,{});let c=s&&s.headers?s.headers:{};return u.headers={...c,...i.headers},{url:bx(o),options:u}},listMetadata:async(t,n,r,i,a,o={})=>{fx("listMetadata","chainName",t),fx("listMetadata","contractAddress",n);const s="/v1/chains/{chain_name}/collections/{contract_address}/metadata".replace("{chain_name}",encodeURIComponent(String(t))).replace("{contract_address}",encodeURIComponent(String(n))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};void 0!==r&&(d.from_updated_at=r instanceof Date?r.toISOString():r),void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}},refreshMetadataByID:async(t,n,r,i={})=>{fx("refreshMetadataByID","chainName",t),fx("refreshMetadataByID","contractAddress",n),fx("refreshMetadataByID","refreshMetadataByIDRequest",r);const a="/v1/chains/{chain_name}/collections/{contract_address}/metadata/refresh-metadata".replace("{chain_name}",encodeURIComponent(String(t))).replace("{contract_address}",encodeURIComponent(String(n))),o=new URL(a,dx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await px(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",yx(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=gx(r,u,e),{url:bx(o),options:u}},refreshNFTMetadataByTokenID:async(t,n,r,i={})=>{fx("refreshNFTMetadataByTokenID","contractAddress",t),fx("refreshNFTMetadataByTokenID","chainName",n),fx("refreshNFTMetadataByTokenID","refreshNFTMetadataByTokenIDRequest",r);const a="/v1/chains/{chain_name}/collections/{contract_address}/nfts/refresh-metadata".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),o=new URL(a,dx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await px(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",yx(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=gx(r,u,e),{url:bx(o),options:u}}}},Cx=function(e){const t=Rx(e);return{async getMetadata(n,r,i,a){const o=await t.getMetadata(n,r,i,a);return vx(o,Ve,ux,e)},async listMetadata(n,r,i,a,o,s){const u=await t.listMetadata(n,r,i,a,o,s);return vx(u,Ve,ux,e)},async refreshMetadataByID(n,r,i,a){const o=await t.refreshMetadataByID(n,r,i,a);return vx(o,Ve,ux,e)},async refreshNFTMetadataByTokenID(n,r,i,a){const o=await t.refreshNFTMetadataByTokenID(n,r,i,a);return vx(o,Ve,ux,e)}}};const kx=function(e){return{listNFTOwners:async(t,n,r,i,a,o={})=>{fx("listNFTOwners","contractAddress",t),fx("listNFTOwners","tokenId",n),fx("listNFTOwners","chainName",r);const s="/v1/chains/{chain_name}/collections/{contract_address}/nfts/{token_id}/owners".replace("{contract_address}",encodeURIComponent(String(t))).replace("{token_id}",encodeURIComponent(String(n))).replace("{chain_name}",encodeURIComponent(String(r))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}},listOwnersByContractAddress:async(t,n,r,i,a,o={})=>{fx("listOwnersByContractAddress","contractAddress",t),fx("listOwnersByContractAddress","chainName",n);const s="/v1/chains/{chain_name}/collections/{contract_address}/owners".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};void 0!==r&&(d.from_updated_at=r instanceof Date?r.toISOString():r),void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}}}},Ox=function(e){const t=kx(e);return{async listNFTOwners(n,r,i,a,o,s){const u=await t.listNFTOwners(n,r,i,a,o,s);return vx(u,Ve,ux,e)},async listOwnersByContractAddress(n,r,i,a,o,s){const u=await t.listOwnersByContractAddress(n,r,i,a,o,s);return vx(u,Ve,ux,e)}}};const Sx=function(e){return{getNFT:async(t,n,r,i={})=>{fx("getNFT","contractAddress",t),fx("getNFT","tokenId",n),fx("getNFT","chainName",r);const a="/v1/chains/{chain_name}/collections/{contract_address}/nfts/{token_id}".replace("{contract_address}",encodeURIComponent(String(t))).replace("{token_id}",encodeURIComponent(String(n))).replace("{chain_name}",encodeURIComponent(String(r))),o=new URL(a,dx);let s;e&&(s=e.baseOptions);const u={method:"GET",...s,...i};yx(o,{});let c=s&&s.headers?s.headers:{};return u.headers={...c,...i.headers},{url:bx(o),options:u}},listAllNFTOwners:async(t,n,r,i,a={})=>{fx("listAllNFTOwners","chainName",t),fx("listAllNFTOwners","fromUpdatedAt",n);const o="/v1/chains/{chain_name}/nft-owners".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,dx);let u;e&&(u=e.baseOptions);const c={method:"GET",...u,...a},l={};void 0!==n&&(l.from_updated_at=n instanceof Date?n.toISOString():n),void 0!==r&&(l.page_cursor=r),void 0!==i&&(l.page_size=i),yx(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:bx(s),options:c}},listAllNFTs:async(t,n,r,i,a={})=>{fx("listAllNFTs","chainName",t);const o="/v1/chains/{chain_name}/nfts".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,dx);let u;e&&(u=e.baseOptions);const c={method:"GET",...u,...a},l={};void 0!==n&&(l.from_updated_at=n instanceof Date?n.toISOString():n),void 0!==r&&(l.page_cursor=r),void 0!==i&&(l.page_size=i),yx(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:bx(s),options:c}},listNFTs:async(t,n,r,i,a,o={})=>{fx("listNFTs","contractAddress",t),fx("listNFTs","chainName",n);const s="/v1/chains/{chain_name}/collections/{contract_address}/nfts".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};void 0!==r&&(d.from_updated_at=r instanceof Date?r.toISOString():r),void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}},listNFTsByAccountAddress:async(t,n,r,i,a,o={})=>{fx("listNFTsByAccountAddress","accountAddress",t),fx("listNFTsByAccountAddress","chainName",n);const s="/v1/chains/{chain_name}/accounts/{account_address}/nfts".replace("{account_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),u=new URL(s,dx);let c;e&&(c=e.baseOptions);const l={method:"GET",...c,...o},d={};void 0!==r&&(d.contract_address=r),void 0!==i&&(d.page_cursor=i),void 0!==a&&(d.page_size=a),yx(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:bx(u),options:l}}}},Nx=function(e){const t=Sx(e);return{async getNFT(n,r,i,a){const o=await t.getNFT(n,r,i,a);return vx(o,Ve,ux,e)},async listAllNFTOwners(n,r,i,a,o){const s=await t.listAllNFTOwners(n,r,i,a,o);return vx(s,Ve,ux,e)},async listAllNFTs(n,r,i,a,o){const s=await t.listAllNFTs(n,r,i,a,o);return vx(s,Ve,ux,e)},async listNFTs(n,r,i,a,o,s){const u=await t.listNFTs(n,r,i,a,o,s);return vx(u,Ve,ux,e)},async listNFTsByAccountAddress(n,r,i,a,o,s){const u=await t.listNFTsByAccountAddress(n,r,i,a,o,s);return vx(u,Ve,ux,e)}}};const xx=function(e){return{cancelOrders:async(t,n,r={})=>{fx("cancelOrders","chainName",t),fx("cancelOrders","cancelOrdersRequestBody",n);const i="/v1/chains/{chain_name}/orders/cancel".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",yx(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=gx(n,s,e),{url:bx(a),options:s}},createListing:async(t,n,r={})=>{fx("createListing","chainName",t),fx("createListing","createListingRequestBody",n);const i="/v1/chains/{chain_name}/orders/listings".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",yx(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=gx(n,s,e),{url:bx(a),options:s}},fulfillmentData:async(t,n,r={})=>{fx("fulfillmentData","chainName",t),fx("fulfillmentData","fulfillmentDataRequest",n);const i="/v1/chains/{chain_name}/orders/fulfillment-data".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",yx(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=gx(n,s,e),{url:bx(a),options:s}},getListing:async(t,n,r={})=>{fx("getListing","chainName",t),fx("getListing","listingId",n);const i="/v1/chains/{chain_name}/orders/listings/{listing_id}".replace("{chain_name}",encodeURIComponent(String(t))).replace("{listing_id}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};yx(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:bx(a),options:s}},getTrade:async(t,n,r={})=>{fx("getTrade","chainName",t),fx("getTrade","tradeId",n);const i="/v1/chains/{chain_name}/trades/{trade_id}".replace("{chain_name}",encodeURIComponent(String(t))).replace("{trade_id}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};yx(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:bx(a),options:s}},listListings:async(t,n,r,i,a,o,s,u,c,l={})=>{fx("listListings","chainName",t);const d="/v1/chains/{chain_name}/orders/listings".replace("{chain_name}",encodeURIComponent(String(t))),f=new URL(d,dx);let p;e&&(p=e.baseOptions);const h={method:"GET",...p,...l},m={};void 0!==n&&(m.status=n),void 0!==r&&(m.sell_item_contract_address=r),void 0!==i&&(m.buy_item_contract_address=i),void 0!==a&&(m.sell_item_token_id=a),void 0!==o&&(m.page_size=o),void 0!==s&&(m.sort_by=s),void 0!==u&&(m.sort_direction=u),void 0!==c&&(m.page_cursor=c),yx(f,m);let y=p&&p.headers?p.headers:{};return h.headers={...y,...l.headers},{url:bx(f),options:h}},listTrades:async(t,n,r,i,a,o,s={})=>{fx("listTrades","chainName",t);const u="/v1/chains/{chain_name}/trades".replace("{chain_name}",encodeURIComponent(String(t))),c=new URL(u,dx);let l;e&&(l=e.baseOptions);const d={method:"GET",...l,...s},f={};void 0!==n&&(f.account_address=n),void 0!==r&&(f.page_size=r),void 0!==i&&(f.sort_by=i),void 0!==a&&(f.sort_direction=a),void 0!==o&&(f.page_cursor=o),yx(c,f);let p=l&&l.headers?l.headers:{};return d.headers={...p,...s.headers},{url:bx(c),options:d}}}},Px=function(e){const t=xx(e);return{async cancelOrders(n,r,i){const a=await t.cancelOrders(n,r,i);return vx(a,Ve,ux,e)},async createListing(n,r,i){const a=await t.createListing(n,r,i);return vx(a,Ve,ux,e)},async fulfillmentData(n,r,i){const a=await t.fulfillmentData(n,r,i);return vx(a,Ve,ux,e)},async getListing(n,r,i){const a=await t.getListing(n,r,i);return vx(a,Ve,ux,e)},async getTrade(n,r,i){const a=await t.getTrade(n,r,i);return vx(a,Ve,ux,e)},async listListings(n,r,i,a,o,s,u,c,l,d){const f=await t.listListings(n,r,i,a,o,s,u,c,l,d);return vx(f,Ve,ux,e)},async listTrades(n,r,i,a,o,s,u){const c=await t.listTrades(n,r,i,a,o,s,u);return vx(c,Ve,ux,e)}}};const Mx=function(e){return{createCounterfactualAddress:async(t,n,r={})=>{fx("createCounterfactualAddress","chainName",t),fx("createCounterfactualAddress","createCounterfactualAddressRequest",n);const i="/v1/chains/{chain_name}/passport/counterfactual-address".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};await hx(u,e),u["Content-Type"]="application/json",yx(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=gx(n,s,e),{url:bx(a),options:s}},createCounterfactualAddressDeprecated:async(t,n={})=>{fx("createCounterfactualAddressDeprecated","createCounterfactualAddressRequestDeprecated",t);const r=new URL("/passport-mr/v1/counterfactual-address",dx);let i;e&&(i=e.baseOptions);const a={method:"POST",...i,...n},o={};await hx(o,e),o["Content-Type"]="application/json",yx(r,{});let s=i&&i.headers?i.headers:{};return a.headers={...o,...s,...n.headers},a.data=gx(t,a,e),{url:bx(r),options:a}},getLinkedAddresses:async(t,n,r={})=>{fx("getLinkedAddresses","userId",t),fx("getLinkedAddresses","chainName",n);const i="/v1/chains/{chain_name}/passport/users/{user_id}/linked-addresses".replace("{user_id}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r},u={};await hx(u,e),yx(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},{url:bx(a),options:s}},getLinkedAddressesDeprecated:async(t,n={})=>{fx("getLinkedAddressesDeprecated","userId",t);const r="/passport-mr/v1/users/{userId}/linked-addresses".replace("{userId}",encodeURIComponent(String(t))),i=new URL(r,dx);let a;e&&(a=e.baseOptions);const o={method:"GET",...a,...n},s={};await hx(s,e),yx(i,{});let u=a&&a.headers?a.headers:{};return o.headers={...s,...u,...n.headers},{url:bx(i),options:o}}}},Bx=function(e){const t=Mx(e);return{async createCounterfactualAddress(n,r,i){const a=await t.createCounterfactualAddress(n,r,i);return vx(a,Ve,ux,e)},async createCounterfactualAddressDeprecated(n,r){const i=await t.createCounterfactualAddressDeprecated(n,r);return vx(i,Ve,ux,e)},async getLinkedAddresses(n,r,i){const a=await t.getLinkedAddresses(n,r,i);return vx(a,Ve,ux,e)},async getLinkedAddressesDeprecated(n,r){const i=await t.getLinkedAddressesDeprecated(n,r);return vx(i,Ve,ux,e)}}};const Dx=function(e){return{getERC20Token:async(t,n,r={})=>{fx("getERC20Token","contractAddress",t),fx("getERC20Token","chainName",n);const i="/v1/chains/{chain_name}/tokens/{contract_address}".replace("{contract_address}",encodeURIComponent(String(t))).replace("{chain_name}",encodeURIComponent(String(n))),a=new URL(i,dx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};yx(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:bx(a),options:s}},listERC20Tokens:async(t,n,r,i,a={})=>{fx("listERC20Tokens","chainName",t);const o="/v1/chains/{chain_name}/tokens".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,dx);let u;e&&(u=e.baseOptions);const c={method:"GET",...u,...a},l={};void 0!==n&&(l.from_updated_at=n instanceof Date?n.toISOString():n),void 0!==r&&(l.page_cursor=r),void 0!==i&&(l.page_size=i),yx(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:bx(s),options:c}}}},Fx=function(e){const t=Dx(e);return{async getERC20Token(n,r,i){const a=await t.getERC20Token(n,r,i);return vx(a,Ve,ux,e)},async listERC20Tokens(n,r,i,a,o){const s=await t.listERC20Tokens(n,r,i,a,o);return vx(s,Ve,ux,e)}}};var Lx=Object.freeze({__proto__:null,ActiveOrderStatusNameEnum:{Active:"ACTIVE"},ActivitiesApi:class extends cx{getActivity(e,t){return Tx(this.configuration).getActivity(e.chainName,e.activityId,t).then((e=>e(this.axios,this.basePath)))}listActivities(e,t){return Tx(this.configuration).listActivities(e.chainName,e.contractAddress,e.tokenId,e.accountAddress,e.activityType,e.fromIndexedAt,e.toIndexedAt,e.transactionHash,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},ActivitiesApiAxiosParamCreator:wx,ActivitiesApiFactory:function(e,t,n){const r=Tx(e);return{getActivity:(e,i)=>r.getActivity(e.chainName,e.activityId,i).then((e=>e(n,t))),listActivities:(e,i)=>r.listActivities(e.chainName,e.contractAddress,e.tokenId,e.accountAddress,e.activityType,e.fromIndexedAt,e.toIndexedAt,e.transactionHash,e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},ActivitiesApiFp:Tx,ActivityType:{Mint:"mint",Burn:"burn",Transfer:"transfer",Sale:"sale",Deposit:"deposit",Withdrawal:"withdrawal"},CancelledOrderStatusCancellationTypeEnum:{OnChain:"ON_CHAIN",OffChain:"OFF_CHAIN"},CancelledOrderStatusNameEnum:{Cancelled:"CANCELLED"},ChainsApi:class extends cx{listChains(e={},t){return Ex(this.configuration).listChains(e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},ChainsApiAxiosParamCreator:Ax,ChainsApiFactory:function(e,t,n){const r=Ex(e);return{listChains:(e={},i)=>r.listChains(e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},ChainsApiFp:Ex,CollectionContractType:{Erc721:"ERC721"},CollectionsApi:class extends cx{getCollection(e,t){return Ix(this.configuration).getCollection(e.contractAddress,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listCollections(e,t){return Ix(this.configuration).listCollections(e.chainName,e.contractAddress,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listCollectionsByNFTOwner(e,t){return Ix(this.configuration).listCollectionsByNFTOwner(e.accountAddress,e.chainName,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}refreshCollectionMetadata(e,t){return Ix(this.configuration).refreshCollectionMetadata(e.contractAddress,e.chainName,e.refreshCollectionMetadataRequest,t).then((e=>e(this.axios,this.basePath)))}},CollectionsApiAxiosParamCreator:_x,CollectionsApiFactory:function(e,t,n){const r=Ix(e);return{getCollection:(e,i)=>r.getCollection(e.contractAddress,e.chainName,i).then((e=>e(n,t))),listCollections:(e,i)=>r.listCollections(e.chainName,e.contractAddress,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),listCollectionsByNFTOwner:(e,i)=>r.listCollectionsByNFTOwner(e.accountAddress,e.chainName,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),refreshCollectionMetadata:(e,i)=>r.refreshCollectionMetadata(e.contractAddress,e.chainName,e.refreshCollectionMetadataRequest,i).then((e=>e(n,t)))}},CollectionsApiFp:Ix,Configuration:class{apiKey;username;password;accessToken;basePath;baseOptions;formDataCtor;constructor(e={}){this.apiKey=e.apiKey,this.username=e.username,this.password=e.password,this.accessToken=e.accessToken,this.basePath=e.basePath,this.baseOptions=e.baseOptions,this.formDataCtor=e.formDataCtor}isJsonMime(e){const t=new RegExp("^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$","i");return null!==e&&(t.test(e)||"application/json-patch+json"===e.toLowerCase())}},ERC20ItemItemTypeEnum:{Erc20:"ERC20"},ERC721ItemItemTypeEnum:{Erc721:"ERC721"},ExpiredOrderStatusNameEnum:{Expired:"EXPIRED"},FailedOrderCancellationReasonCodeEnum:{AlreadyFilled:"ALREADY_FILLED"},FeeFeeTypeEnum:{Royalty:"ROYALTY",MakerEcosystem:"MAKER_ECOSYSTEM",TakerEcosystem:"TAKER_ECOSYSTEM",Protocol:"PROTOCOL"},FilledOrderStatusNameEnum:{Filled:"FILLED"},InactiveOrderStatusNameEnum:{Inactive:"INACTIVE"},ListListingsSortByEnum:{CreatedAt:"created_at",UpdatedAt:"updated_at",BuyItemAmount:"buy_item_amount"},ListListingsSortDirectionEnum:{Asc:"asc",Desc:"desc"},ListTradesSortByEnum:{IndexedAt:"indexed_at"},ListTradesSortDirectionEnum:{Asc:"asc",Desc:"desc"},MetadataApi:class extends cx{getMetadata(e,t){return Cx(this.configuration).getMetadata(e.chainName,e.contractAddress,e.metadataId,t).then((e=>e(this.axios,this.basePath)))}listMetadata(e,t){return Cx(this.configuration).listMetadata(e.chainName,e.contractAddress,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}refreshMetadataByID(e,t){return Cx(this.configuration).refreshMetadataByID(e.chainName,e.contractAddress,e.refreshMetadataByIDRequest,t).then((e=>e(this.axios,this.basePath)))}refreshNFTMetadataByTokenID(e,t){return Cx(this.configuration).refreshNFTMetadataByTokenID(e.contractAddress,e.chainName,e.refreshNFTMetadataByTokenIDRequest,t).then((e=>e(this.axios,this.basePath)))}},MetadataApiAxiosParamCreator:Rx,MetadataApiFactory:function(e,t,n){const r=Cx(e);return{getMetadata:(e,i)=>r.getMetadata(e.chainName,e.contractAddress,e.metadataId,i).then((e=>e(n,t))),listMetadata:(e,i)=>r.listMetadata(e.chainName,e.contractAddress,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),refreshMetadataByID:(e,i)=>r.refreshMetadataByID(e.chainName,e.contractAddress,e.refreshMetadataByIDRequest,i).then((e=>e(n,t))),refreshNFTMetadataByTokenID:(e,i)=>r.refreshNFTMetadataByTokenID(e.contractAddress,e.chainName,e.refreshNFTMetadataByTokenIDRequest,i).then((e=>e(n,t)))}},MetadataApiFp:Cx,NFTContractType:{Erc721:"ERC721"},NativeItemItemTypeEnum:{Native:"NATIVE"},NftOwnersApi:class extends cx{listNFTOwners(e,t){return Ox(this.configuration).listNFTOwners(e.contractAddress,e.tokenId,e.chainName,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listOwnersByContractAddress(e,t){return Ox(this.configuration).listOwnersByContractAddress(e.contractAddress,e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},NftOwnersApiAxiosParamCreator:kx,NftOwnersApiFactory:function(e,t,n){const r=Ox(e);return{listNFTOwners:(e,i)=>r.listNFTOwners(e.contractAddress,e.tokenId,e.chainName,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),listOwnersByContractAddress:(e,i)=>r.listOwnersByContractAddress(e.contractAddress,e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},NftOwnersApiFp:Ox,NftsApi:class extends cx{getNFT(e,t){return Nx(this.configuration).getNFT(e.contractAddress,e.tokenId,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listAllNFTOwners(e,t){return Nx(this.configuration).listAllNFTOwners(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listAllNFTs(e,t){return Nx(this.configuration).listAllNFTs(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listNFTs(e,t){return Nx(this.configuration).listNFTs(e.contractAddress,e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listNFTsByAccountAddress(e,t){return Nx(this.configuration).listNFTsByAccountAddress(e.accountAddress,e.chainName,e.contractAddress,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},NftsApiAxiosParamCreator:Sx,NftsApiFactory:function(e,t,n){const r=Nx(e);return{getNFT:(e,i)=>r.getNFT(e.contractAddress,e.tokenId,e.chainName,i).then((e=>e(n,t))),listAllNFTOwners:(e,i)=>r.listAllNFTOwners(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),listAllNFTs:(e,i)=>r.listAllNFTs(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),listNFTs:(e,i)=>r.listNFTs(e.contractAddress,e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t))),listNFTsByAccountAddress:(e,i)=>r.listNFTsByAccountAddress(e.accountAddress,e.chainName,e.contractAddress,e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},NftsApiFp:Nx,OrderStatusName:{Pending:"PENDING",Active:"ACTIVE",Inactive:"INACTIVE",Filled:"FILLED",Expired:"EXPIRED",Cancelled:"CANCELLED"},OrdersApi:class extends cx{cancelOrders(e,t){return Px(this.configuration).cancelOrders(e.chainName,e.cancelOrdersRequestBody,t).then((e=>e(this.axios,this.basePath)))}createListing(e,t){return Px(this.configuration).createListing(e.chainName,e.createListingRequestBody,t).then((e=>e(this.axios,this.basePath)))}fulfillmentData(e,t){return Px(this.configuration).fulfillmentData(e.chainName,e.fulfillmentDataRequest,t).then((e=>e(this.axios,this.basePath)))}getListing(e,t){return Px(this.configuration).getListing(e.chainName,e.listingId,t).then((e=>e(this.axios,this.basePath)))}getTrade(e,t){return Px(this.configuration).getTrade(e.chainName,e.tradeId,t).then((e=>e(this.axios,this.basePath)))}listListings(e,t){return Px(this.configuration).listListings(e.chainName,e.status,e.sellItemContractAddress,e.buyItemContractAddress,e.sellItemTokenId,e.pageSize,e.sortBy,e.sortDirection,e.pageCursor,t).then((e=>e(this.axios,this.basePath)))}listTrades(e,t){return Px(this.configuration).listTrades(e.chainName,e.accountAddress,e.pageSize,e.sortBy,e.sortDirection,e.pageCursor,t).then((e=>e(this.axios,this.basePath)))}},OrdersApiAxiosParamCreator:xx,OrdersApiFactory:function(e,t,n){const r=Px(e);return{cancelOrders:(e,i)=>r.cancelOrders(e.chainName,e.cancelOrdersRequestBody,i).then((e=>e(n,t))),createListing:(e,i)=>r.createListing(e.chainName,e.createListingRequestBody,i).then((e=>e(n,t))),fulfillmentData:(e,i)=>r.fulfillmentData(e.chainName,e.fulfillmentDataRequest,i).then((e=>e(n,t))),getListing:(e,i)=>r.getListing(e.chainName,e.listingId,i).then((e=>e(n,t))),getTrade:(e,i)=>r.getTrade(e.chainName,e.tradeId,i).then((e=>e(n,t))),listListings:(e,i)=>r.listListings(e.chainName,e.status,e.sellItemContractAddress,e.buyItemContractAddress,e.sellItemTokenId,e.pageSize,e.sortBy,e.sortDirection,e.pageCursor,i).then((e=>e(n,t))),listTrades:(e,i)=>r.listTrades(e.chainName,e.accountAddress,e.pageSize,e.sortBy,e.sortDirection,e.pageCursor,i).then((e=>e(n,t)))}},OrdersApiFp:Px,PassportApi:class extends cx{createCounterfactualAddress(e,t){return Bx(this.configuration).createCounterfactualAddress(e.chainName,e.createCounterfactualAddressRequest,t).then((e=>e(this.axios,this.basePath)))}createCounterfactualAddressDeprecated(e,t){return Bx(this.configuration).createCounterfactualAddressDeprecated(e.createCounterfactualAddressRequestDeprecated,t).then((e=>e(this.axios,this.basePath)))}getLinkedAddresses(e,t){return Bx(this.configuration).getLinkedAddresses(e.userId,e.chainName,t).then((e=>e(this.axios,this.basePath)))}getLinkedAddressesDeprecated(e,t){return Bx(this.configuration).getLinkedAddressesDeprecated(e.userId,t).then((e=>e(this.axios,this.basePath)))}},PassportApiAxiosParamCreator:Mx,PassportApiFactory:function(e,t,n){const r=Bx(e);return{createCounterfactualAddress:(e,i)=>r.createCounterfactualAddress(e.chainName,e.createCounterfactualAddressRequest,i).then((e=>e(n,t))),createCounterfactualAddressDeprecated:(e,i)=>r.createCounterfactualAddressDeprecated(e.createCounterfactualAddressRequestDeprecated,i).then((e=>e(n,t))),getLinkedAddresses:(e,i)=>r.getLinkedAddresses(e.userId,e.chainName,i).then((e=>e(n,t))),getLinkedAddressesDeprecated:(e,i)=>r.getLinkedAddressesDeprecated(e.userId,i).then((e=>e(n,t)))}},PassportApiFp:Bx,PendingOrderStatusNameEnum:{Pending:"PENDING"},ProtocolDataOrderTypeEnum:{FullRestricted:"FULL_RESTRICTED"},SaleFeeTypeEnum:{Royalty:"ROYALTY"},TokenContractType:{Erc20:"ERC20"},TokensApi:class extends cx{getERC20Token(e,t){return Fx(this.configuration).getERC20Token(e.contractAddress,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listERC20Tokens(e,t){return Fx(this.configuration).listERC20Tokens(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},TokensApiAxiosParamCreator:Dx,TokensApiFactory:function(e,t,n){const r=Fx(e);return{getERC20Token:(e,i)=>r.getERC20Token(e.contractAddress,e.chainName,i).then((e=>e(n,t))),listERC20Tokens:(e,i)=>r.listERC20Tokens(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},TokensApiFp:Fx});class Ux extends Error{code;details;link;traceId;constructor({message:e,code:t,details:n,link:r,trace_id:i}){super(e),this.code=t,this.details=n,this.link=r,this.traceId=i}}const qx={sdkVersion:"ts-immutable-sdk-multi-rollup-api-client-0.31.2-alpha"},jx=({baseConfig:e,basePath:t,headers:n})=>{if(!t.trim())throw Error("basePath can not be empty");const r={...e,basePath:t,baseOptions:{headers:{...n||{},...qx}}};return new Lx.Configuration(r)};class Gx{apiConfig;baseConfig;constructor({baseConfig:e,overrides:t}){if(this.baseConfig=e,t)this.apiConfig=jx(t);else switch(e.environment){case st.SANDBOX:this.apiConfig=jx({basePath:"https://api.sandbox.immutable.com",baseConfig:e});break;case st.PRODUCTION:this.apiConfig=jx({basePath:"https://api.immutable.com",baseConfig:e});break;default:this.apiConfig=jx({basePath:"https://api.sandbox.immutable.com",baseConfig:e})}}}function Hx(e){if(Ve.isAxiosError(e)&&e.response){const t=e.response.data;return t.code&&t.message?new Ux({code:t.code,message:t.message,details:t.details||null,link:t.link||"",trace_id:t.trace_id||""}):new Ux({code:e.code??e.response?.status.toString()??"unknown_error_code",message:String(e),details:null,link:"",trace_id:""})}return new Ux({code:"unknown_error_code",message:String(e),details:null,link:"",trace_id:""})}class zx{config;activities;chains;collections;nfts;nftOwners;tokens;metadata;constructor(e){this.config=new Gx(e),this.activities=new Lx.ActivitiesApi(this.config.apiConfig),this.chains=new Lx.ChainsApi(this.config.apiConfig),this.collections=new Lx.CollectionsApi(this.config.apiConfig),this.nfts=new Lx.NftsApi(this.config.apiConfig),this.nftOwners=new Lx.NftOwnersApi(this.config.apiConfig),this.tokens=new Lx.TokensApi(this.config.apiConfig),this.metadata=new Lx.MetadataApi(this.config.apiConfig)}async listActivities(e){return await this.activities.listActivities(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async getActivity(e){return await this.activities.getActivity(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listChains(e){return await this.chains.listChains(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listCollections(e){return await this.collections.listCollections(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listCollectionsByNFTOwner(e){return await this.collections.listCollectionsByNFTOwner(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async getCollection(e){return await this.collections.getCollection(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async getNFT(e){return await this.nfts.getNFT(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listNFTs(e){return await this.nfts.listNFTs(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listNFTsByAccountAddress(e){return await this.nfts.listNFTsByAccountAddress(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listAllNFTs(e){return await this.nfts.listAllNFTs(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listNFTOwners(e){return await this.nftOwners.listNFTOwners(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listNFTOwnersByContractAddress(e){return await this.nftOwners.listOwnersByContractAddress(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listAllNFTOwners(e){return await this.nfts.listAllNFTOwners(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listTokens(e){return await this.tokens.listERC20Tokens(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async getToken(e){return await this.tokens.getERC20Token(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async getMetadata(e){return await this.metadata.getMetadata(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async listNFTMetadataByContractAddress(e){return await this.metadata.listMetadata(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async refreshCollectionMetadata(e){return await this.collections.refreshCollectionMetadata(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async refreshNFTMetadata(e){return await this.metadata.refreshNFTMetadataByTokenID(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}async refreshStackedMetadata(e){return await this.metadata.refreshMetadataByID(e).then((e=>e.data)).catch((e=>{throw Hx(e)}))}}async function Vx(t,n,r,i){const a=r.get(t),o=r.get(n);if(!a)throw new lm(`Chain:${t} is not a supported chain`,e.CheckoutErrorType.CHAIN_NOT_SUPPORTED_ERROR);if(!o)throw new lm(`Chain:${n} is not a supported chain`,e.CheckoutErrorType.CHAIN_NOT_SUPPORTED_ERROR);let s=jm;i.isDevelopment&&(s=qm),i.isProduction&&(s=Gm);const u=new nv({baseConfig:new ut({environment:i.environment}),bridgeInstance:s,rootProvider:a,childProvider:o});return new Qb(u)}async function Wx(e,t){const n=await t.remote.getConfig("dex");return new LR({chainId:e,baseConfig:new ut({environment:t.environment}),overrides:n?.overrides})}function Kx(e){return new ox({baseConfig:{environment:e.environment}})}function Xx(e){return new zx({baseConfig:{environment:e.environment}})}const Jx="0x0000000000000000000000000000000000000001",Yx=18;async function Qx(t,n,r){const i=bm(n),a=vm(n),o=await n.remote.getConfig("gasEstimateTokens"),{fromAddress:s}=o[i].bridgeToL2Addresses,u=t.get(i);if(!u)throw new Error(`Missing JsonRpcProvider for chain id: ${i}`);try{let o={};const c=async()=>{o=await async function(e,t){const n=await Dm(e);return n&&t?{estimatedAmount:n.add(n)}:{estimatedAmount:n}}(u,r),o.token=n.networkMap.get(i)?.nativeCurrency};let l={bridgeFee:{},bridgeable:!1};const d=async()=>{const e=await Vx(i,a,t,n);l=await async function(e,t){const n=await e.getFee({token:t});return{bridgeFee:{estimatedAmount:n.feeAmount},bridgeable:n.bridgeable}}(e,s)};return await Promise.all([c(),d()]),{gasEstimateType:e.GasEstimateType.BRIDGE_TO_L2,gasFee:o,bridgeFee:{estimatedAmount:l.bridgeFee?.estimatedAmount,token:l.bridgeFee?.token},bridgeable:l.bridgeable}}catch{return{gasEstimateType:e.GasEstimateType.BRIDGE_TO_L2,gasFee:{},bridgeFee:{},bridgeable:!1}}}async function Zx(t,n,r){switch(t.gasEstimateType){case e.GasEstimateType.BRIDGE_TO_L2:return await Qx(n,r,t.isSpendingCapApprovalRequired);case e.GasEstimateType.SWAP:return await async function(t){const n=vm(t),r=await t.remote.getConfig("gasEstimateTokens"),{inAddress:i,outAddress:a}=r[n].swapAddresses;try{const r=await Wx(n,t),{swap:o}=await r.getUnsignedSwapTxFromAmountIn(Jx,i,a,tr.from(kh("1",Yx)));if(null===o.gasFeeEstimate)return{gasEstimateType:e.GasEstimateType.SWAP,gasFee:{}};let s;return o.gasFeeEstimate.value&&(s=tr.from(o.gasFeeEstimate.value)),{gasEstimateType:e.GasEstimateType.SWAP,gasFee:{estimatedAmount:s,token:{address:o.gasFeeEstimate?.token.address,symbol:o.gasFeeEstimate?.token.symbol??"",name:o.gasFeeEstimate?.token.name??"",decimals:o.gasFeeEstimate?.token.decimals??Yx}}}}catch{return{gasEstimateType:e.GasEstimateType.SWAP,gasFee:{}}}}(r);default:throw new lm("Invalid type provided for gasEstimateType",e.CheckoutErrorType.INVALID_GAS_ESTIMATE_TYPE)}}const $x=t=>(t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.ERC721)return void r.push(t);const{contractAddress:a,spenderAddress:o,id:s}=t,u=`${a}${o}${s}`;n.get(u)||n.set(u,{...t})})),r.concat(Array.from(n.values()))})((t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.ERC20)return void r.push(t);const{contractAddress:a,spenderAddress:o,amount:s}=t,u=`${a}${o}`,c=n.get(u);c&&c.type===e.ItemType.ERC20?c.amount=tr.from(c.amount).add(s):n.set(u,{...t})})),r.concat(Array.from(n.values()))})((t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.NATIVE)return void r.push(t);const{amount:a}=t,o=n.get(i);o&&o.type===e.ItemType.NATIVE?o.amount=tr.from(o.amount).add(a):n.set(i,{...t})})),r.concat(Array.from(n.values()))})(t))),eP=async(t,n,r,i)=>{try{const e=new vl(r,JSON.stringify(tm),t);return await e.allowance(n,i)}catch(t){throw new lm("Failed to get the allowance for ERC20",e.CheckoutErrorType.GET_ERC20_ALLOWANCE_ERROR,{contractAddress:r})}},tP=async(t,n,r,i,a)=>{try{const e=new vl(r,JSON.stringify(tm),t),o=await e.populateTransaction.approve(i,a);return o&&(o.from=n),o}catch{throw new lm("Failed to get the approval transaction for ERC20",e.CheckoutErrorType.GET_ERC20_ALLOWANCE_ERROR,{contractAddress:r})}},nP=async(t,n,r,i)=>{try{const e=new vl(r,JSON.stringify(nm),t);return await e.isApprovedForAll(n,i)}catch(t){throw new lm("Failed to check approval for all ERC721s of collection",e.CheckoutErrorType.GET_ERC721_ALLOWANCE_ERROR,{ownerAddress:n,contractAddress:r,spenderAddress:i})}},rP=async(t,n,r,i,a)=>{try{const e=new vl(r,JSON.stringify(nm),t),o=await e.populateTransaction.approve(i,a);return o&&(o.from=n),o}catch(t){throw new lm("Failed to get the approval transaction for ERC721",e.CheckoutErrorType.GET_ERC721_ALLOWANCE_ERROR,{id:a.toString(),contractAddress:r,spenderAddress:i,ownerAddress:n})}},iP=async(t,n,r)=>{try{const e=new vl(n,JSON.stringify(nm),t);return await e.getApproved(r)}catch(t){throw new lm("Failed to get approved address for ERC721",e.CheckoutErrorType.GET_ERC721_ALLOWANCE_ERROR,{id:r.toString(),contractAddress:n})}},aP=(t,n)=>{const r=parseInt(t,10);if(Number.isNaN(r))throw new lm("Invalid ERC721 ID",e.CheckoutErrorType.GET_ERC721_ALLOWANCE_ERROR,{id:t,contractAddress:n});return r},oP=async(t,n,r)=>{let i=!0;const a=[],o=new Map,s=new Map,u=new Map,c=new Map,l=await(async(t,n,r)=>{const i=new Map,a=new Map;for(const o of n){if(o.type!==e.ItemType.ERC721)continue;const{contractAddress:n,spenderAddress:s}=o,u=`${n}-${s}`;i.set(u,!1),a.has(u)||a.set(u,nP(t,r,n,s))}const o=await Promise.all(a.values()),s=Array.from(a.keys());return o.forEach(((e,t)=>{i.set(s[t],e)})),i})(t,r,n);for(const n of r){if(n.type!==e.ItemType.ERC721)continue;const{contractAddress:r,id:i,spenderAddress:u}=n,c=`${r}-${u}`;if(l.get(c)){a.push({sufficient:!0,itemRequirement:n});continue}const d=`${r}-${i}`,f=aP(i,r);o.set(d,n),s.set(d,iP(t,r,f))}const d=await Promise.all(s.values()),f=Array.from(s.keys());for(let r=0;r<d.length;r++){const s=o.get(f[r]);if(!s||s.type!==e.ItemType.ERC721)continue;if(d[r]===s.spenderAddress){a.push({sufficient:!0,itemRequirement:s});continue}i=!1;const{contractAddress:l,id:p,spenderAddress:h}=s,m=`${l}-${p}`,y=aP(p,l);u.set(m,{type:e.ItemType.ERC721,sufficient:!1,itemRequirement:s,approvalTransaction:void 0}),c.set(m,rP(t,n,l,h,y))}const p=await Promise.all(c.values()),h=Array.from(c.keys());return p.forEach(((e,t)=>{const n=u.get(h[t]);n&&(n.sufficient||(n.approvalTransaction=e))})),{sufficient:i,allowances:a.concat(Array.from(u.values()))}},sP=t=>(t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.ERC721)return void r.push(t);const{contractAddress:a,id:o}=t,s=`${a}${o}`;n.get(s)||n.set(s,{...t})})),r.concat(Array.from(n.values()))})((t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.ERC20)return void r.push(t);const{contractAddress:a,amount:o}=t,s=`${a}`,u=n.get(s);u&&u.type===e.ItemType.ERC20?u.amount=tr.from(u.amount).add(o):n.set(s,{...t})})),r.concat(Array.from(n.values()))})((t=>{const n=new Map,r=[];return t.forEach((t=>{const{type:i}=t;if(i!==e.ItemType.NATIVE)return void r.push(t);const{amount:a}=t,o=n.get(i);o&&o.type===e.ItemType.NATIVE?o.amount=tr.from(o.amount).add(a):n.set(i,{...t})})),r.concat(Array.from(n.values()))})(t))),uP=async(t,n,r,i)=>{try{const a=new Map;(t=>t.map((t=>t.type===e.ItemType.NATIVE?{address:Vh}:{address:t.contractAddress})))(i).forEach((e=>a.set((e.address||"").toLocaleLowerCase(),e)));const{balances:o}=await Om(t,n,r);return o.filter((e=>a.get((e.token.address||"").toLocaleLowerCase())))}catch(t){throw new lm("Failed to get balances",e.CheckoutErrorType.GET_BALANCE_ERROR)}},cP=async(t,n,r,i)=>{const a=sP(i),o=[],s=[];if(a.forEach((t=>{switch(t.type){case e.ItemType.ERC20:case e.ItemType.NATIVE:o.push(t);break;case e.ItemType.ERC721:s.push(t)}})),0===s.length&&0===o.length)throw new lm("Unsupported item requirement balance check",e.CheckoutErrorType.UNSUPPORTED_BALANCE_REQUIREMENT_ERROR);const u=[];o.length>0&&u.push(uP(t,n,r,a)),s.length>0&&u.push((async(t,n,r)=>{const i=[],a=new Map,o=new Map;r.forEach((n=>{if(n.type!==e.ItemType.ERC721)return;const r=new vl(n.contractAddress,JSON.stringify(nm),t);a.set(n.contractAddress,n),o.set(n.contractAddress,r.ownerOf(n.id))}));try{const t=await Promise.all(o.values()),r=Array.from(o.keys());t.forEach(((t,o)=>{const s=a.get(r[o]);let u=0;s&&n===t&&(u=1),i.push({type:e.ItemType.ERC721,balance:tr.from(u),formattedBalance:u.toString(),contractAddress:s.contractAddress,id:s.id})}))}catch(t){throw new lm("Failed to get ERC721 balances",e.CheckoutErrorType.GET_ERC721_BALANCE_ERROR)}return i})(n,r,a));const c=await Promise.all(u),l=[];if(o.length>0&&c.length>0){const t=c.shift();t&&o.forEach((n=>{l.push(((t,n)=>{let r;t.type===e.ItemType.ERC20?r=n.find((e=>e.token?.address===t.contractAddress)):t.type===e.ItemType.NATIVE&&(r=n.find((e=>""===e.token?.address||e.token?.address===Vh)));const i=t.amount,a=i.isNegative()||i.isZero()||(r?.balance.gte(i)??!1),o=i.sub(r?.balance??tr.from(0));let s="",u="",c=Wh;r&&(c=r.token?.decimals??Wh,s=r.token.name,u=r.token.symbol);let l=r;return t.type===e.ItemType.NATIVE?(l||(l={type:e.ItemType.NATIVE,balance:tr.from(0),formattedBalance:"0",token:{name:s,symbol:u,decimals:Wh,address:Vh}}),{sufficient:a,type:e.ItemType.NATIVE,delta:{balance:o,formattedBalance:Ch(o,c)},current:{...l,type:e.ItemType.NATIVE},required:{...l,type:e.ItemType.NATIVE,balance:tr.from(t.amount),formattedBalance:Ch(t.amount,c)}}):(l||(l={type:t.type,balance:tr.from(0),formattedBalance:"0",token:{name:s,symbol:u,address:t.contractAddress,decimals:c}}),{sufficient:a,type:e.ItemType.ERC20,delta:{balance:o,formattedBalance:Ch(o,c)},current:l,required:{...l,balance:tr.from(t.amount),formattedBalance:Ch(t.amount,c)}})})(n,t))}))}if(s.length>0&&c.length>0){const t=c.shift();t&&s.forEach((n=>{l.push(((t,n)=>{const r=tr.from(1),i=n.find((e=>{const n=e;return n.contractAddress===t.contractAddress&&n.id===t.id})),a=r.isNegative()||r.isZero()||(i?.balance.gte(r)??!1),o=r.sub(i?.balance??tr.from(0));let s=i;return s||(s={type:e.ItemType.ERC721,balance:tr.from(0),formattedBalance:"0",contractAddress:t.contractAddress,id:t.id}),{sufficient:a,type:e.ItemType.ERC721,delta:{balance:o,formattedBalance:o.toString()},current:s,required:{...s,balance:tr.from(1),formattedBalance:"1"}}})(n,t))}))}return{sufficient:void 0===l.find((e=>!1===e.sufficient)),balanceRequirements:l}},lP=async(t,n)=>{try{return await t.estimateGas(n)}catch(t){throw new lm("Failed to estimate gas for transaction",e.CheckoutErrorType.UNPREDICTABLE_GAS_LIMIT)}},dP=async(t,n,r)=>{const i=[];let a=tr.from(0);for(const e of n)void 0!==e.approvalTransaction&&i.push(lP(t,e.approvalTransaction));if(r.type===e.TransactionOrGasType.TRANSACTION)i.push(lP(t,r.transaction));else{const e=await t.getFeeData(),n=Bm(e);if(null!==n){const e=n?.mul(r.gasToken.limit);e&&(a=a.add(e))}}return(await Promise.all(i)).forEach((e=>{a=a.add(e)})),a.eq(0)?null:((t,n)=>n.type===e.TransactionOrGasType.TRANSACTION||n.gasToken.type===e.GasTokenType.NATIVE?{type:e.ItemType.NATIVE,amount:t}:{type:e.ItemType.ERC20,amount:t,contractAddress:n.gasToken.contractAddress,spenderAddress:""})(a,r)},fP=(t,n)=>({checkDexAvailability:async()=>{let r;try{r=await Ve.post(`${t?Xh[zh]:n?Xh[st.PRODUCTION]:Xh[st.SANDBOX]}/v1/availability/checkout/swap`)}catch(e){r=e.response}if(403===r.status)return!1;if(204===r.status)return!0;throw new lm(`Error fetching from api: ${r.status} ${r.statusText}`,e.CheckoutErrorType.API_ERROR)}}),pP=async()=>!0,hP=async e=>{const t=fP(e.isDevelopment,e.isProduction);try{return await t.checkDexAvailability()}catch{return!1}};async function mP(t,n){if(t.isProduction&&n?.has(e.ChainId.ETHEREUM))return n;if(n?.has(e.ChainId.SEPOLIA))return n;const r=new Map;return(await pm(t,{type:e.NetworkFilterTypes.ALL})).networks.forEach((e=>{const n=t.networkMap.get(e.chainId)?.rpcUrls[0],i=new up(n);r.set(e.chainId,i)})),r}const yP=async(e,t,n,r,i)=>{const a=new Map;try{const o=await Wx(t,e),s=[],u=[];for(const e of i)e!==r.address&&(s.push(o.getUnsignedSwapTxFromAmountOut(n,e,r.address,r.amount,1)),u.push(e));return(await Im(e,"Time to resolve swap quotes from the dex",Promise.allSettled(s))).forEach(((e,t)=>{if("rejected"===e.status)return;const n=u[t];a.set(n,{quote:e.value.quote,approval:e.value.approval?.gasFeeEstimate??null,swap:e.value.swap.gasFeeEstimate})})),a}catch{return a}},gP=(e,t,n)=>{let r,i=tr.from(0),a="0";e&&(i=e.value,a=Ch(e.value,e.token.decimals),r={name:e.token.name??"",symbol:e.token.symbol??"",address:e.token.address,decimals:e.token.decimals});let o,s=tr.from(0),u="0";t&&(s=t.value,u=Ch(t.value,t.token.decimals),o={name:t.token.name??"",symbol:t.token.symbol??"",address:t.token.address,decimals:t.token.decimals});const c=[];for(const e of n)c.push({amount:e.amount.value,formattedAmount:Ch(e.amount.value,e.amount.token.decimals),token:{name:e.amount.token.name??"",symbol:e.amount.token.symbol??"",address:e.amount.token.address,decimals:e.amount.token.decimals}});return{approvalGasFees:{amount:i,formattedAmount:a,token:r},swapGasFees:{amount:s,formattedAmount:u,token:o},swapFees:c}},bP=(t,n,r,i)=>{const a=r.token.address;let o=e.ItemType.ERC20;return a===Vh&&(o=e.ItemType.NATIVE),{type:e.FundingStepType.SWAP,chainId:t,fundingItem:{type:o,fundsRequired:{amount:n,formattedAmount:Ch(n,r.token.decimals)},userBalance:{balance:r.balance,formattedBalance:r.formattedBalance},token:r.token},fees:i}},vP=(e,t)=>{if(!t)return{sufficient:!0,approvalGasFee:tr.from(0),approvalGasTokenAddress:""};const n=t.value,r=t.token.address;if(0===e.length)return{sufficient:!1,approvalGasFee:n,approvalGasTokenAddress:r};const i=e.find((e=>e.token.address===r));return i?i.balance.lt(n)?{sufficient:!1,approvalGasFee:n,approvalGasTokenAddress:r}:{sufficient:!0,approvalGasFee:n,approvalGasTokenAddress:r}:{sufficient:!1,approvalGasFee:n,approvalGasTokenAddress:r}},wP=(e,t,n,r,i)=>{const a=new Map;if(""!==t.approvalGasTokenAddress&&a.set(t.approvalGasTokenAddress,t.approvalGasFee),n){const e=a.get(n.token.address);e?a.set(n.token.address,e.add(n.value)):a.set(n.token.address,n.value)}if(i){const e=a.get(i.address);e?a.set(i.address,e.add(i.amount)):a.set(i.address,i.amount)}for(const e of r){const t=a.get(e.amount.token.address);t?a.set(e.amount.token.address,t.add(e.amount.value)):a.set(e.amount.token.address,e.amount.value)}for(const[t,n]of a.entries()){if(n===tr.from(0))continue;const r=e.find((e=>e.token.address===t));if(!r)return!1;if(r.balance.lt(n))return!1}return!0},TP=(t,n,r,i,a,o)=>{let s=tr.from(0),u="",c=!1;if(n.balanceRequirements.forEach((n=>{n.type!==e.ItemType.NATIVE&&n.type!==e.ItemType.ERC20||n.required.token.address===r&&(u=n.required.token.address,c=!0,s=t.sub(n.required.balance))})),!c)return!0;a.approvalGasTokenAddress===u&&(s=s.sub(a.approvalGasFee));for(const e of o)e.amount.token.address===u&&(s=s.sub(e.amount.value));return s.gte(i)},AP=async(t,n,r,i,a,o,s)=>{const u=[];if(!n.swap)return u;if(0===o.length)return u;const c=(t=>{let n="",r=tr.from(0);switch(t.type){case e.ItemType.ERC20:n=t.required.token.address??"",r=t.delta.balance;break;case e.ItemType.NATIVE:n=Vh,r=t.delta.balance}return{address:n,amount:r}})(i);if(""===c.address)return u;const l=vm(t),d=a.get(l);if(!d)return u;const f=d.balances;if(0===f.length)return u;const p=await yP(t,vm(t),r,c,o),h=Array.from(p.keys());for(const e of h){const t=p.get(e);if(!t)continue;const n=f.find((t=>t.token.address===e));if(!n)continue;const r=t.quote.amount;if(n.balance.lt(r.value))continue;const i=vP(f,t.approval);if(!i.sufficient)continue;if(!wP(f,i,t.swap,t.quote.fees,{amount:r.value,address:e}))continue;if(!TP(n.balance,s,e,r.value,i,t.quote.fees))continue;const a=gP(t.approval,t.swap,t.quote.fees);u.push(bP(l,r.value,n,a))}return u},EP=(e,t)=>t&&t.success?e.filter((e=>"address"in e?t.balances.find((t=>t.token.address===e.address&&t.balance.gt(0))):t.balances.find((e=>!("address"in e.token)&&e.balance.gt(0))))):[],_P=async(e,t)=>{if(t.onRamp){const t=await e.remote.getConfig("onramp"),n={};return Object.entries(t).forEach((([e,t])=>{n[e]=t.tokens??[]})),n}return{}},IP=async(e,t,n)=>{if(n.bridge){const n=(await e.remote.getConfig("bridge"))?.tokens??[],r=t.get(bm(e));return EP(n,r)}return[]},RP=async(e,t,n)=>{const r={};return r.swap=await(async(e,t,n)=>{if(n.swap){const n=(await e.remote.getConfig("dex"))?.tokens??[],r=t.get(vm(e));return EP(n,r)}return[]})(e,t,n),r.bridge=await IP(e,t,n),r.onRamp=await _P(e,n),r},CP="0x0000000000000000000000000000000000000001",kP=async(e,t)=>(await t.remote.getConfig("imxAddressMapping"))[e]??"",OP=async(t,n)=>{if(""===n)return{l1address:"",l2address:n};if(n===Vh)return{l1address:await kP(bm(t),t),l2address:Vh};const r=(i=vm(t))===e.ChainId.IMTBL_ZKEVM_MAINNET?"imtbl-zkevm-mainnet":i===e.ChainId.IMTBL_ZKEVM_TESTNET?"imtbl-zkevm-testnet":i===e.ChainId.IMTBL_ZKEVM_DEVNET?"imtbl-zkevm-devent":"";var i;if(""===r)return{l1address:"",l2address:n};const a=Xx(t),o=(await a.getToken({chainName:r,contractAddress:n})).result.root_contract_address;return null===o?{l1address:"",l2address:n}:{l1address:o,l2address:n}},SP=async(t,n,r,i,a,o)=>{if(a===CP)return tr.from(0);const s=bm(t),u=vm(t);return await(async(t,n,r,i,a,o,s,u)=>{try{const e=await Vx(a,o,n,t),{unsignedTx:c}=await e.getUnsignedApproveDepositBridgeTx({depositorAddress:i,token:s,depositAmount:u});return null===c?tr.from(0):await r.estimateGas(c)}catch(t){throw new lm("Error occurred while attempting ot estimate gas for approval transaction",e.CheckoutErrorType.BRIDGE_GAS_ESTIMATE_ERROR,{message:t.message})}})(t,n,r,i,s,u,a,o)},NP=(e,t)=>(e=>{for(const t of e.balances)if(!t.token.address||""===t.token.address)return t.balance;return tr.from(0)})(e).gte(t),xP=async(t,n,r)=>{let i=r.get(e.FundingStepType.BRIDGE);return i||(i=await(async(t,n)=>{try{const r=await Zx({gasEstimateType:e.GasEstimateType.BRIDGE_TO_L2,isSpendingCapApprovalRequired:!1},n,t),i=r.gasFee.estimatedAmount,a=r.bridgeFee.estimatedAmount;let o=tr.from(0);return i&&(o=o.add(i)),a&&(o=o.add(a)),{type:e.FundingStepType.BRIDGE,gasFee:{estimatedAmount:i??tr.from(0),token:r.gasFee.token},bridgeFee:{estimatedAmount:a??tr.from(0),token:r.bridgeFee.token},totalFees:o}}catch(t){throw new lm("Error estimating gas for bridge",e.CheckoutErrorType.BRIDGE_GAS_ESTIMATE_ERROR,{message:t.message})}})(t,n),r.set(e.FundingStepType.BRIDGE,i),i)},PP=(e,t,n)=>{const r=n.token?.decimals??Wh;return{approvalGasFees:{amount:e,formattedAmount:Ch(e,Wh),token:t.token},bridgeGasFees:{amount:t.estimatedAmount,formattedAmount:Ch(t.estimatedAmount,Wh),token:t.token},bridgeFees:[{amount:n.estimatedAmount,formattedAmount:Ch(n.estimatedAmount,r),token:n.token}]}},MP=(t,n,r,i,a)=>({type:e.FundingStepType.BRIDGE,chainId:t,fundingItem:{type:i,fundsRequired:{amount:r.amount,formattedAmount:r.formattedAmount},userBalance:{balance:n.balance,formattedBalance:n.formattedBalance},token:{name:n.token.name,symbol:n.token.symbol,address:n.token.address,decimals:n.token.decimals}},fees:a}),BP=async(t,n,r,i,a,o,s)=>{if(!i.bridge)return;if(void 0===a.l2address||""===a.l2address)return;const u=bm(t),c=o.get(u),l=n.get(u);if(!l)throw new lm("No L1 provider available",e.CheckoutErrorType.PROVIDER_ERROR,{chainId:u.toString()});if(void 0===c||!1===c.success)return;const d=await IP(t,o,i);if(0===d.length)return;const f=await xP(t,n,s);if(!NP(c,f.totalFees))return;const p=await OP(t,a.l2address),{l1address:h}=p;if(""===h)return;if(h===CP){if(!d.find((e=>!("address"in e))))return}else if(!d.find((e=>e.address===h)))return;const m=await SP(t,n,l,r,h,a.amount);let y=f.bridgeFee.estimatedAmount;if(h===CP){const t=c.balances.find((e=>{return!(t=e.token.address)||""===t;var t}));if(f.gasFee.estimatedAmount&&(y=y.add(f.gasFee.estimatedAmount)),!NP(c,y))return;if(t&&t.balance.gte(a.amount.add(y))){const n=PP(m,f.gasFee,f.bridgeFee);return MP(u,t,a,e.ItemType.NATIVE,n)}return}if(y.add(m).add(f.gasFee.estimatedAmount),!NP(c,y))return;const g=c.balances.find((e=>e.token.address===h));if(g&&g.balance.gte(a.amount)){const t=PP(m,f.gasFee,f.bridgeFee);return MP(u,g,a,e.ItemType.ERC20,t)}},DP=(e,t)=>{let n=tr.from(0);return e.quote.fees.forEach((e=>{e.amount.token.address===t&&(n=n.add(e.amount.value))})),e.approval&&e.approval.token.address===t&&(n=n.add(e.approval.value)),n},FP=(t,n)=>{for(const r of t.balanceRequirements)if((r.type===e.ItemType.NATIVE||r.type===e.ItemType.ERC20)&&r.required.token.address===n)return r.required.balance;return tr.from(0)},LP=(e,t,n)=>{const r=n?.balance??tr.from(0);if(r.gte(e.add(t)))return tr.from(0);if(r.lte(0))return e.add(t);const i=r.sub(t);return i.gte(0)?e.sub(i):e.add(t).sub(r)},UP=async(e,t,n,r,i,a,o,s,u,c)=>{const{l1balances:l,l2balances:d}=((e,t)=>{const n={l1balances:[],l2balances:[]},r=t.get(bm(e)),i=t.get(vm(e));return r?void 0!==r.error?n:r.success&&i?void 0!==i.error?n:i.success?{l1balances:r.balances,l2balances:i.balances}:n:n:n})(e,o),f=r.required.token.address;if(((e,t,n,r,i,a)=>0===e.length||0===t.length||0===n.length||0===r.length||!i.bridge||!i.swap||void 0===a||""===a)(s,u,l,d,n,f))return[];const p=await(async(e,t)=>{const n=t.map((t=>OP(e,t.address??"")));return await Promise.all(n)})(e,u),h=((e,t,n,r)=>{const i=[];for(const a of r){if(""===a.l1address)continue;if(""===a.l2address)continue;if(!t.includes(a.l1address))continue;if(a.l2address===e)continue;const r=n.find((e=>e.address===a.l2address));r&&i.push(r)}return i})(f,s,u,p);if(0===h.length)return[];const m=await(async(e,t,n,r,i)=>{const a=[];for(const e of i)e.address&&a.push(e.address);return await yP(e,vm(e),t,{address:n,amount:r.delta.balance},a)})(e,i,f,r,h),y=((e,t,n,r,i)=>{const a=[];for(const[o,s]of e){const e=n.find((e=>e.token.address===o)),u=r.find((e=>e.l2address===o));if(!u)continue;const{l1address:c,l2address:l}=u;if(!c)continue;const d=t.find((e=>void 0===e.token.address&&c===CP||e.token.address===c));if(!d)continue;const f=s.quote.amountWithMaxSlippage.value,p=DP(s,o),h=f.add(p),m=FP(i,o),y=LP(h,m,e);y.lte(0)||y.gte(d.balance)||a.push({amount:y,formattedAmount:Ch(y,d.token.decimals),l2address:l})}return a})(m,l,d,p,c);if(0===y.length)return[];const g=new Map,b=new Map,v=[];for(const r of y)r.l2address&&(g.set(r.l2address,BP(e,t,i,n,r,o,a)),b.set(r.l2address,{amount:r.amount,formattedAmount:r.formattedAmount,l2address:r.l2address}));const w=await Promise.all(g.values()),T=Array.from(g.keys()),A=[];if(w.forEach(((e,t)=>{const n=T[t];if(void 0===e)return;A.push(n);const r=b.get(n);r&&v.push({amount:r.amount,formattedAmount:r.formattedAmount,l2address:r.l2address})})),0===A.length)return[];if(0===v.length)return[];const E=((e,t,n,r,i)=>{const a=new Map;for(const[e,n]of t)a.set(e,{success:n.success,balances:n.balances});const o=new Map;for(const e of n)e.token.address&&o.set(e.token.address,e);for(const e of r){const{amount:t,l2address:n}=e;if(""===n)continue;let r=tr.from(0);const a=o.get(n);a&&(r=a.balance);const s=r.add(t),u=i.find((e=>e.address===n));o.set(n,{balance:s,formattedBalance:Ch(s,u.decimals),token:u})}const s=Array.from(o.values());return a.set(vm(e),{success:!0,balances:s}),a})(e,o,d,v,u),_=await AP(e,n,i,r,E,A,c);if(!_)return[];const I=((e,t)=>{const n=[];for(const r of t){const{chainId:t,fundingItem:i}=r,{userBalance:a}=r.fundingItem,o=e.get(t);if(!o)continue;let s=tr.from(0),u="0";const c=o.balances.find((e=>e.token.address===i.token.address));c&&(s=c.balance,u=c.formattedBalance),a.balance=s,a.formattedBalance=u,n.push(r)}return n})(o,_);return((e,t,n)=>{const r=[];for(const i of e){if(!i)continue;const e=n.find((e=>void 0===i.fundingItem.token.address?e.l1address===CP&&e.l2address:e.l1address===i.fundingItem.token.address&&e.l2address));if(!e)continue;const a=t.find((t=>t.fundingItem.token.address===e.l2address));a&&r.push({bridgeFundingStep:i,swapFundingStep:a})}return r})(w,I,p)},qP=async(t,n,r)=>{if(!n.onRamp)return;if(void 0===r)return;const i=await(async(t,n,r)=>{if(r.type!==e.ItemType.ERC20&&r.type!==e.ItemType.NATIVE)return;const{required:i,current:a,delta:o}=r;let s=!1;const u=await _P(t,n);return Object.values(u).forEach((e=>{e.length>0&&!s&&(s=!!e.find((e=>e.address===i.token?.address)))})),s?{type:e.FundingStepType.ONRAMP,chainId:vm(t),fundingItem:{type:i.token.address===Vh?e.ItemType.NATIVE:e.ItemType.ERC20,fundsRequired:{amount:o.balance,formattedAmount:o.formattedBalance},userBalance:{balance:a.balance,formattedBalance:a.formattedBalance},token:i.token}}:void 0})(t,n,r);return i},jP=async(t,n,r,i)=>{if(!(e=>e.bridge||e.swap||e.onRamp)(i))return{type:e.RoutingOutcomeType.NO_ROUTE_OPTIONS,message:"No routing options are available"};let a;try{a=await mP(t)}catch(t){throw new lm("Error occurred while creating read only providers",e.CheckoutErrorType.PROVIDER_ERROR,{message:t.message})}const o=await Im(t,"Time to get token balances inside router",(async(t,n,r,i)=>{const a=new Map,o=new Map;if(0===n.size){const n={success:!1,error:new lm("No L1 or L2 provider available",e.CheckoutErrorType.PROVIDER_ERROR),balances:[]};return a.set(bm(t),n),a.set(vm(t),n),a}if(i.bridge){const i=bm(t);n.has(i)?o.set(i,Om(t,n.get(i),r,i)):a.set(bm(t),{success:!1,error:new lm(`No L1 provider available for ${i}`,e.CheckoutErrorType.PROVIDER_ERROR),balances:[]})}const s=vm(t);if(n.has(s)?o.set(s,Om(t,n.get(s),r,s)):a.set(vm(t),{success:!1,error:new lm(`No L2 provider available for ${s}`,e.CheckoutErrorType.PROVIDER_ERROR),balances:[]}),o.size>0){const t=Array.from(o.keys());(await Promise.allSettled(o.values())).forEach(((n,r)=>{const i=t[r];"fulfilled"===n.status?a.set(i,{success:!0,balances:n.value.balances}):a.set(i,{success:!1,error:new lm(`Error getting ${s} balances`,e.CheckoutErrorType.GET_BALANCE_ERROR),balances:[]})}))}return a})(t,a,n,i)),s=await Im(t,"Time to get routing allowlist",RP(t,o,i)),u=new Map,c=(e=>{let t,n=0;for(const r of e.balanceRequirements)r.sufficient||(n++,t=r);if(1===n)return t})(r),l=[];l.push((async(t,n,r,i,a,o,s)=>{let u;if(void 0===i)return;if(i.type!==e.ItemType.NATIVE&&i.type!==e.ItemType.ERC20)return;const c={amount:i.delta.balance,formattedAmount:i.delta.formattedBalance,l2address:i.required.token.address??""};return r.bridge&&i&&(u=await BP(t,n,a,r,c,o,s)),u})(t,a,i,c,n,o,u)),l.push((async(e,t,n,r,i,a,o)=>{const s=[];if(!t.swap)return s;if(void 0===n)return s;if(void 0===a)return s;const u=i.get(vm(e));if(!u)return s;if(void 0!==u.error||!u.success)return s;if(0===a.length)return s;const c=a.filter((e=>e.address)).map((e=>e.address));return 0===c.length?s:await AP(e,t,r,n,i,c,o)})(t,i,c,n,o,s.swap,r)),l.push(qP(t,i,c)),l.push((async(t,n,r,i,a,o,s,u,c)=>{if(!i)return[];const l=o.get(bm(t)),d=o.get(vm(t));if(!l)return[];if(void 0!==l.error||!l.success)return[];if(!d)return[];if(void 0!==d.error||!d.success)return[];const f=(s?.bridge??[]).map((e=>void 0===e.address?CP:e.address)),p=s?.swap??[];return i.type!==e.ItemType.NATIVE&&i.type!==e.ItemType.ERC20?[]:await UP(t,n,r,i,a,u,o,f,p,c)})(t,a,i,c,n,o,s,u,r));const d=await Im(t,"Time to resolve all routes",Promise.all(l));let f,p,h=[],m=[];if(d.forEach(((e,t)=>{0===t&&(f=e),1===t&&(h=e),2===t&&(p=e),3===t&&(m=e)})),!f&&0===h.length&&!p&&0===m.length)return{type:e.RoutingOutcomeType.NO_ROUTES_FOUND,message:"Smart Checkout did not find any funding routes to fulfill the transaction"};const y={type:e.RoutingOutcomeType.ROUTES_FOUND,fundingRoutes:[]};let g=0;return h.length>0&&(g++,h.forEach((e=>{y.fundingRoutes.push({priority:g,steps:[e]})}))),f&&(g++,y.fundingRoutes.push({priority:g,steps:[f]})),p&&(g++,y.fundingRoutes.push({priority:g,steps:[p]})),m&&(g++,m.forEach((e=>{const t=e.bridgeFundingStep,n=e.swapFundingStep;y.fundingRoutes.push({priority:g,steps:[t,n]})}))),y},GP=async(t,n,r,i)=>{const a=await n.getSigner().getAddress();let o=$x(r);const s=(async(t,n,r)=>{let i=!0;const a=[],o=new Map,s=new Map,u=new Map,c=new Map;for(const i of r){if(i.type!==e.ItemType.ERC20)continue;const{contractAddress:r,spenderAddress:a}=i,u=`${r}${a}`;o.set(u,i),s.set(u,eP(t,n,r,a))}const l=await Promise.all(s.values()),d=Array.from(s.keys());for(let r=0;r<l.length;r++){const s=o.get(d[r]);if(!s||s.type!==e.ItemType.ERC20)continue;if(l[r].gte(s.amount)){a.push({sufficient:!0,itemRequirement:s});continue}i=!1;const{contractAddress:f,spenderAddress:p}=s,h=`${f}${p}`,m=s.amount.sub(l[r]);u.set(h,{type:e.ItemType.ERC20,sufficient:!1,delta:m,itemRequirement:s,approvalTransaction:void 0}),c.set(h,tP(t,n,f,p,m))}const f=await Promise.all(c.values()),p=Array.from(c.keys());return f.forEach(((e,t)=>{const n=u.get(p[t]);n&&(n.sufficient||(n.approvalTransaction=e))})),{sufficient:i,allowances:a.concat(Array.from(u.values()))}})(n,a,o),u=oP(n,a,o),c=await Im(t,"Time to calculate token allowances",Promise.all([s,u])),l=((e,t)=>{const n=[];if(!e.sufficient)for(const t of e.allowances)t.sufficient||n.push(t);if(!t.sufficient)for(const e of t.allowances)e.sufficient||n.push(e);return n})(c[0],c[1]),d=await Im(t,"Time to run gas calculator",dP(n,l,i));null!==d&&(o.push(d),o=$x(o));const f=await Im(t,"Time to run balance checks",cP(t,n,a,o)),{sufficient:p}=f,h=f.balanceRequirements;if(p)return{sufficient:p,transactionRequirements:h};const m=await Im(t,"Time to fetch available routing options",(async(e,t)=>{const n={onRamp:e.isOnRampEnabled,swap:e.isSwapEnabled,bridge:e.isBridgeEnabled},r=[];if(n.onRamp&&r.push({id:"onRamp",promise:pP()}),n.swap&&r.push({id:"swap",promise:hP(e)}),r.length>0){const e=r.map((e=>e.promise));(await Promise.allSettled(e)).forEach(((e,t)=>{const i=r[t].id;n[i]=n[i]&&"fulfilled"===e.status&&e.value}))}return n.bridge=n.bridge&&!(e=>!0===e.provider?.isPassport??!1)(t),n})(t,n));return{sufficient:p,transactionRequirements:h,router:{availableRoutingOptions:m,routingOutcome:await Im(t,"Total time to run the routing calculator",jP(t,a,f,m))}}};var HP;!function(e){e.SUCCESS="SUCCESS",e.FAILED="FAILED"}(HP||(HP={}));const zP=async(t,n)=>{let r=[];try{const e=await Promise.all(n.map((e=>t.getSigner().sendTransaction(e))));r=await Promise.all(e.map((e=>e.wait())))}catch(t){throw new lm("An error occurred while executing the approval transaction",e.CheckoutErrorType.EXECUTE_APPROVAL_TRANSACTION_ERROR,{message:t.message})}for(const e of r)if(0===e.status)return{type:HP.FAILED,transactionHash:e.transactionHash,reason:"Approval transaction failed and was reverted"};return{type:HP.SUCCESS}},VP=async(t,n)=>{let r=[];try{const e=await Promise.all(n.map((e=>t.getSigner().sendTransaction(e))));r=await Promise.all(e.map((e=>e.wait())))}catch(t){throw new lm("An error occurred while executing the fulfillment transaction",e.CheckoutErrorType.EXECUTE_FULFILLMENT_TRANSACTION_ERROR,{message:t.message})}for(const e of r)if(0===e.status)return{type:HP.FAILED,transactionHash:e.transactionHash,reason:"Fulfillment transaction failed and was reverted"};return{type:HP.SUCCESS}},WP=async e=>{let t=[];const n=[];for(const t of e)t.type===VN.TRANSACTION&&t.purpose===HN.FULFILL_ORDER&&n.push(t.buildTransaction());return t=await Promise.all(n),t},KP=(e,t)=>{const n=e.amount,r=Math.round(n.percentageDecimal*10**6);return t.mul(tr.from(r)).div(10**6)},XP=(e,t)=>kh(e.amount.token,t),JP=(t,n,r=18)=>{let i=tr.from(0);const a=tr.from(n),o=a.mul(1e6).div(10**6),s=[];for(const n of t){let t=tr.from(0);if(Object.hasOwn(n.amount,"percentageDecimal"))t=KP(n,a),i=i.add(t);else{if(!Object.hasOwn(n.amount,"token"))throw new lm("Unknown fee type parsed, must be percentageDecimal or token",e.CheckoutErrorType.ORDER_FEE_ERROR);t=XP(n,r),i=i.add(t)}if(i.gt(o))throw new lm("The combined fees are above the allowed maximum of 100%",e.CheckoutErrorType.ORDER_FEE_ERROR);t.gt(0)&&s.push({amount:t.toString(),recipient:n.recipient})}return s},YP=(t,n,r,i)=>{switch(t){case e.ItemType.ERC20:return{type:t,amount:r,contractAddress:n,spenderAddress:i};case e.ItemType.NATIVE:default:return{type:e.ItemType.NATIVE,amount:r}}},QP=async(t,n,r)=>{if(0===r.length)throw new lm("No orders were provided to the orders array. Please provide at least one order.",e.CheckoutErrorType.FULFILL_ORDER_LISTING_ERROR);let i,a="",o=18;const s=sx,u=Kx(t),c=Xx(t),l=await Im(t,"Time to get the address from the provider",n.getSigner().getAddress());km.clear(),Om(t,n,l,bm(t)),Om(t,n,l,vm(t));const{id:d,takerFees:f}=r[0];let p;try{i=await Im(t,"Time to fetch the listing from the orderbook",u.getListing(d));const{seaportContractAddress:e,chainName:n}=u.config();p=n,a=e}catch(t){throw new lm("An error occurred while getting the order listing",e.CheckoutErrorType.GET_ORDER_LISTING_ERROR,{orderId:d,message:t.message})}if(0===i.result.buy.length)throw new lm("An error occurred with the get order listing",e.CheckoutErrorType.GET_ORDER_LISTING_ERROR,{orderId:d,message:"No buy side tokens found on order"});const h=i.result.buy[0];if("ERC20"===h.type){const e=await Im(t,"Time to get decimals of token contract for the buy token",c.getToken({contractAddress:h.contractAddress,chainName:p}));e.result.decimals&&(o=e.result.decimals)}let m=[];f&&f.length>0&&(m=JP(f,h.amount,o));let y=[],g=[],b=[];const v=performance.now();try{const{actions:e}=await Im(t,"Time to call fulfillOrder from the orderbook",u.fulfillOrder(d,l,m));b=e,y=await Im(t,"Time to construct the unsigned approval transactions",(async e=>{let t=[];const n=[];for(const t of e)t.type===VN.TRANSACTION&&t.purpose===HN.APPROVAL&&n.push(t.buildTransaction());return t=await Promise.all(n),t})(e))}catch(n){const r=(performance.now()-v)/1e3;if(_m(t,"Time to call fulfillOrder from the orderbook",r),n.message.includes(qN.EXPIRED))throw new lm("Order is expired",e.CheckoutErrorType.ORDER_EXPIRED_ERROR,{orderId:d});if(!n.message.includes("The fulfiller does not have the balances needed to fulfill"))throw new lm("Error occurred while trying to fulfill the order",e.CheckoutErrorType.FULFILL_ORDER_LISTING_ERROR,{orderId:d,message:n.message})}try{g=await Im(t,"Time to construct the unsigned fulfillment transactions",WP(b))}catch{}let w=tr.from("0"),T=e.ItemType.NATIVE,A="";const E=i.result.buy;if(E.length>0)switch(E[0].type){case"NATIVE":T=e.ItemType.NATIVE;break;case"ERC20":T=e.ItemType.ERC20,A=E[0].contractAddress;break;default:throw new lm("Purchasing token type is unsupported",e.CheckoutErrorType.UNSUPPORTED_TOKEN_TYPE_ERROR,{orderId:d})}E.forEach((t=>{t.type!==e.ItemType.ERC721&&(w=w.add(tr.from(t.amount)))}));i.result.fees.forEach((e=>{w=w.add(tr.from(e.amount))}));const _=[YP(T,A,w,a)],I=await Im(t,"Total time running smart checkout",GP(t,n,_,((t,n)=>n.length>0?{type:e.TransactionOrGasType.TRANSACTION,transaction:n[0]}:{type:e.TransactionOrGasType.GAS,gasToken:{type:e.GasTokenType.NATIVE,limit:tr.from(t)}})(s,g)));if(I.sufficient){const t=await zP(n,y);if(t.type===HP.FAILED)return{status:e.CheckoutStatus.FAILED,transactionHash:t.transactionHash,reason:t.reason,smartCheckoutResult:I};try{0===g.length&&(g=await WP(b))}catch(t){throw new lm("Error fetching fulfillment transaction",e.CheckoutErrorType.FULFILL_ORDER_LISTING_ERROR,{message:t.message})}const r=await VP(n,g);return r.type===HP.FAILED?{status:e.CheckoutStatus.FAILED,transactionHash:r.transactionHash,reason:r.reason,smartCheckoutResult:I}:{status:e.CheckoutStatus.SUCCESS,smartCheckoutResult:I}}return{status:e.CheckoutStatus.INSUFFICIENT_FUNDS,smartCheckoutResult:I}},ZP=(t,n,r)=>({type:e.ItemType.ERC721,id:t,contractAddress:n,spenderAddress:r}),$P=async(t,n,r)=>{let i,a,o="";if(0===r.length)throw new lm("No orders were provided to the orders array. Please provide at least one order.",e.CheckoutErrorType.PREPARE_ORDER_LISTING_ERROR);const{buyToken:s,sellToken:u,makerFees:c}=r[0];let l=18;if(s.type===e.ItemType.ERC20){const e=new vl(s.contractAddress,JSON.stringify(tm),n);l=await Im(t,"Time to get decimals of token contract for the buy token",e.decimals())}const d=((t,n=18)=>{const r=kh(t.amount,n);return t.type===e.ItemType.NATIVE?{type:e.ItemType.NATIVE,amount:r.toString()}:{type:e.ItemType.ERC20,amount:r.toString(),contractAddress:t.contractAddress}})(s,l);try{const r=await Im(t,"Time to get the address from the provider",n.getSigner().getAddress());i=Kx(t);const{seaportContractAddress:s}=i.config();o=s,a=await Im(t,"Time to prepare the listing from the orderbook",i.prepareListing({makerAddress:r,buy:d,sell:{type:e.ItemType.ERC721,contractAddress:u.collectionAddress,tokenId:u.id}}))}catch(t){throw new lm("An error occurred while preparing the listing",e.CheckoutErrorType.PREPARE_ORDER_LISTING_ERROR,{message:t.message,id:u.id,collectionAddress:u.collectionAddress})}const f=[ZP(u.id,u.collectionAddress,o)],p=await Im(t,"Total time running smart checkout",GP(t,n,f,{type:e.TransactionOrGasType.GAS,gasToken:{type:e.GasTokenType.NATIVE,limit:tr.from(sx)}}));if(p.sufficient){const t=await(async e=>{let t=[],n=[];const r=[],i=[];for(const t of e)t.type===VN.TRANSACTION&&(t.purpose===HN.APPROVAL&&r.push(t.buildTransaction()),t.purpose===HN.FULFILL_ORDER&&i.push(t.buildTransaction()));return t=await Promise.all(r),n=await Promise.all(i),{approvalTransactions:t,fulfillmentTransactions:n}})(a.actions),r=await zP(n,t.approvalTransactions);if(r.type===HP.FAILED)return{status:e.CheckoutStatus.FAILED,transactionHash:r.transactionHash,reason:r.reason,smartCheckoutResult:p};const o=((e,t,n)=>{let r;for(const e of n)e.type===VN.SIGNABLE&&e.purpose===zN.CREATE_LISTING&&(r={domain:e.message.domain,types:e.message.types,value:e.message.value});if(r)return{orderHash:e,orderComponents:t,unsignedMessage:r}})(a.orderHash,a.orderComponents,a.actions);if(!o)throw new lm("The unsigned message is missing after preparing the listing",e.CheckoutErrorType.SIGN_MESSAGE_ERROR,{id:u.id,collectionAddress:u.collectionAddress});const s=await(async(t,n)=>{try{const e=await t.getSigner()._signTypedData(n.unsignedMessage.domain,n.unsignedMessage.types,n.unsignedMessage.value);return{orderComponents:n.orderComponents,orderHash:n.orderHash,signedMessage:e}}catch(t){throw new lm("An error occurred while signing the message",e.CheckoutErrorType.SIGN_MESSAGE_ERROR,{message:t.message})}})(n,o);let f="";const h={orderComponents:s.orderComponents,orderHash:s.orderHash,orderSignature:s.signedMessage,makerFees:[]};if(void 0!==c){const t=JP(c,d.amount,l);if(t.length!==c.length)throw new lm("One of the fees is too small, must be greater than 0.000001",e.CheckoutErrorType.CREATE_ORDER_LISTING_ERROR);h.makerFees=t}try{f=(await i.createListing(h)).result.id}catch(t){throw new lm("An error occurred while creating the listing",e.CheckoutErrorType.CREATE_ORDER_LISTING_ERROR,{message:t.message,collectionId:u.id,collectionAddress:u.collectionAddress})}return{status:e.CheckoutStatus.SUCCESS,orderIds:[f],smartCheckoutResult:p}}return{status:e.CheckoutStatus.INSUFFICIENT_FUNDS,smartCheckoutResult:p}};class eM{config;constructor(e){this.config=e}async feeEstimate(){const e=await this.config.remote.getConfig("onramp");return e[Fh.TRANSAK]?.fees}async createWidgetUrl(e){return await this.getTransakWidgetUrl(e)}async getTransakWidgetUrl(e){let t=`${Yh[this.config.environment]}?`;if(t+=`${`apiKey=${(await this.config.remote.getConfig("onramp"))[Fh.TRANSAK].publishableApiKey}`}&network=immutablezkevm&defaultPaymentMethod=credit_debit_card&disablePaymentMethods=sepa_bank_transfer,gbp_bank_transfer,pm_cash_app,pm_jwire,pm_paymaya,pm_bpi,pm_ubp,pm_grabpay,pm_shopeepay,pm_gcash,pm_pix,pm_astropay,pm_pse,inr_bank_transfer&productsAvailed=buy&exchangeScreenTitle=Buy&themeColor=0D0D0D`,e.isPassport&&e.email){t+=`&email=${encodeURIComponent(e.email)}&isAutoFillUserData=true&disableWalletAddressForm=true`}return e.tokenAmount&&e.tokenSymbol?t+=`&defaultCryptoAmount=${e.tokenAmount}&cryptoCurrencyCode=${e.tokenSymbol}`:t+="&defaultCryptoCurrency=IMX",e.walletAddress&&(t+=`&walletAddress=${e.walletAddress}`),t}}async function tM(t,n){const r=[];n.forEach((n=>{if(n.type===e.ItemType.ERC20){const{contractAddress:e}=n;r.push((i=e,a=tm,o=t,new vl(i,a,o)).decimals())}var i,a,o}));const i=await Promise.all(r),a=n.map(((t,n)=>t.type===e.ItemType.NATIVE?{...t,amount:kh(t.amount,18)}:t.type===e.ItemType.ERC20?{...t,amount:kh(t.amount,i[n])}:t));return a}const nM=()=>"0.31.2-alpha";function rM(e){if(void 0===window)throw new Error("missing window object: please run Checkout client side");if(void 0===document)throw new Error("missing document object: please run Checkout client side");const t="immutable-checkout-widgets-bundle",n=function(e){const t=nM();if(void 0===e||void 0===e.major)return t;if(!Number.isInteger(e.major)||e.major<0)return t;if(void 0!==e.minor&&e.minor<0)return t;if(void 0!==e.patch&&e.patch<0)return t;if(0===e.major&&void 0===e.minor)return t;if(0===e.major&&0===e.minor&&void 0===e.patch)return t;if(0===e.major&&void 0===e.minor&&void 0===e.patch)return t;if(0===e.major&&0===e.minor&&0===e.patch)return t;let n=e.major.toString();return void 0===e.minor||(Number.isInteger(e.minor)&&(n+=`.${e.minor.toString()}`),void 0===e.patch||(Number.isInteger(e.patch)&&(n+=`.${e.patch.toString()}`),void 0===e.prerelease||"alpha"!==e.prerelease||("alpha"===e.prerelease&&(n+=`-${e.prerelease}`),void 0===e.build||Number.isInteger(e.build)&&e.build>=0&&(n+=`.${e.build.toString()}`)))),n}(e),r=document.getElementById(t);if(r)return{loaded:!0,element:r};const i=document.createElement("script");let a=`https://cdn.jsdelivr.net/npm/@imtbl/sdk@${n}/dist/browser/checkout/widgets.js`;return i.setAttribute("id",t),i.setAttribute("data-version",n),i.setAttribute("src",a),document.head.appendChild(i),{loaded:!1,element:i}}const iM={baseConfig:{environment:st.SANDBOX},passport:void 0};e.CHECKOUT_API_BASE_URL=Jh,e.Checkout=class{readOnlyProviders;config;fiatRampService;availability;passport;constructor(e=iM){this.config=new wm(e),this.fiatRampService=new eM(this.config),this.readOnlyProviders=new Map,this.availability=fP(this.config.isDevelopment,this.config.isProduction),this.passport=e.passport}async widgets(t){const n=this,r=new Promise(((r,i)=>{try{rM(t.version).loaded&&"undefined"!=typeof ImmutableCheckoutWidgets?(console.warn("Checkout widgets script is already loaded"),r(new ImmutableCheckoutWidgets.WidgetsFactory(n,t.config))):function e(){"undefined"!=typeof ImmutableCheckoutWidgets?r(new ImmutableCheckoutWidgets.WidgetsFactory(n,t.config)):setTimeout(e,100)}()}catch(t){i(new lm("Failed to load widgets script",e.CheckoutErrorType.WIDGETS_SCRIPT_LOAD_ERROR,{message:t.message}))}}));return r}async createProvider(e){return await xm(e.walletProviderName,this.passport)}async checkIsWalletConnected(t){return async function(t){if(!t?.provider?.request)throw new lm("Check wallet connection request failed",e.CheckoutErrorType.PROVIDER_REQUEST_FAILED_ERROR,{rpcMethod:qh.CHECK_CONNECTION});let n=[];try{n=await t.provider.request({method:qh.CHECK_CONNECTION,params:[]})}catch(t){throw new lm("Check wallet connection request failed",e.CheckoutErrorType.PROVIDER_REQUEST_FAILED_ERROR,{rpcMethod:qh.CHECK_CONNECTION})}return{isConnected:n&&n.length>0,walletAddress:n[0]??""}}(await Mm(this.config,t.provider,{allowUnsupportedProvider:!0}))}async connect(t){const n=await Mm(this.config,t.provider,{allowUnsupportedProvider:!0});return await async function(t){if(!t||!t.provider?.request)throw new lm("Incompatible provider",e.CheckoutErrorType.PROVIDER_REQUEST_MISSING_ERROR,{details:"Attempting to connect with an incompatible provider"});return await dm((async()=>{t.provider.request&&await t.provider.request({method:qh.CONNECT,params:[]})}),{type:e.CheckoutErrorType.USER_REJECTED_REQUEST_ERROR}),t}(n),{provider:n}}async switchNetwork(e){const t=await Mm(this.config,e.provider,{allowUnsupportedProvider:!0,allowMistmatchedChainId:!0});return await mm(this.config,t,e.chainId)}async getBalance(e){const t=await Mm(this.config,e.provider);return e.contractAddress&&""!==e.contractAddress?await Cm(t,e.walletAddress,e.contractAddress):await Rm(this.config,t,e.walletAddress)}async getAllBalances(e){const t=await Mm(this.config,e.provider);return Om(this.config,t,e.walletAddress,e.chainId)}async getNetworkAllowList(e){return await pm(this.config,e)}async getTokenAllowList(e){return await Tm(this.config,e)}async getWalletAllowList(t){return await async function(t){const n=[],r=t.exclude?.map((e=>e.walletProviderName))??[];let i=Object.values(e.WalletProviderName);0!==r.length&&(i=i.filter((e=>!r.includes(e))));for(const e of i)n.push({walletProviderName:e});return{wallets:n}}(t)}async sendTransaction(t){const n=await Mm(this.config,t.provider);return await(async(t,n)=>{try{return{transactionResponse:await t.getSigner().sendTransaction(n)}}catch(t){if(t.code===En.INSUFFICIENT_FUNDS)throw new lm(t.message,e.CheckoutErrorType.INSUFFICIENT_FUNDS);if(t.code===En.ACTION_REJECTED)throw new lm(t.message,e.CheckoutErrorType.USER_REJECTED_REQUEST_ERROR);if(t.code===En.UNPREDICTABLE_GAS_LIMIT)throw new lm(t.message,e.CheckoutErrorType.UNPREDICTABLE_GAS_LIMIT);throw new lm(t.message,e.CheckoutErrorType.TRANSACTION_FAILED)}})(n,t.transaction)}async getNetworkInfo(e){const t=await Mm(this.config,e.provider,{allowUnsupportedProvider:!0,allowMistmatchedChainId:!0});return await hm(this.config,t)}async buy(e){e.orders.length>1&&console.warn("This endpoint currently only processes the first order in the array.");const t=await Mm(this.config,e.provider);return await QP(this.config,t,e.orders)}async sell(e){e.orders.length>1&&console.warn("This endpoint currently only processes the first order in the array.");const t=await Mm(this.config,e.provider);return await $P(this.config,t,e.orders)}async cancel(t){console.warn("This endpoint currently only processes the first order in the array.");const n=await Mm(this.config,t.provider);return await(async(t,n,r)=>{let i;if(0===r.length)throw new lm("No orderIds were provided to the orderIds array. Please provide at least one orderId.",e.CheckoutErrorType.CANCEL_ORDER_LISTING_ERROR);const a=r[0];try{const e=await Im(t,"Time to get the address from the provider",n.getSigner().getAddress()),r=Kx(t),o=await Im(t,"Time to get the cancel order from the orderbook",r.cancelOrdersOnChain([a],e));i=await o.cancellationAction.buildTransaction()}catch(t){throw new lm("An error occurred while cancelling the order listing",e.CheckoutErrorType.CANCEL_ORDER_LISTING_ERROR,{orderId:a,message:t.message})}const o=await VP(n,[i]);return o.type===HP.FAILED?{status:e.CheckoutStatus.FAILED,transactionHash:o.transactionHash,reason:o.reason}:{status:e.CheckoutStatus.SUCCESS}})(this.config,n,t.orderIds)}async smartCheckout(t){const n=await Mm(this.config,t.provider);let r=[];try{r=await tM(n,t.itemRequirements)}catch{throw new lm("Failed to map item requirements",e.CheckoutErrorType.ITEM_REQUIREMENTS_ERROR)}return await GP(this.config,n,r,t.transactionOrGasAmount)}static isWeb3Provider(e){return Pm(e)}async gasEstimate(e){return this.readOnlyProviders=await mP(this.config,this.readOnlyProviders),await Zx(e,this.readOnlyProviders,this.config)}async createFiatRampUrl(t){let n,r,i="IMX";const a=await t.web3Provider.getSigner().getAddress(),o=t.web3Provider.provider?.isPassport||!1;if(o&&t.passport){const e=await t.passport.getUserInfo();r=e?.email}const s=await Tm(this.config,{type:e.TokenFilterTypes.ONRAMP}),u=s.tokens?.find((e=>e.address?.toLowerCase()===t.tokenAddress?.toLowerCase()));return u&&(n=t.tokenAmount,i=u.symbol),await this.fiatRampService.createWidgetUrl({exchangeType:t.exchangeType,isPassport:o,walletAddress:a,tokenAmount:n,tokenSymbol:i,email:r})}async getExchangeFeeEstimate(){return await this.fiatRampService.feeEstimate()}async isSwapAvailable(){return this.availability.checkDexAvailability()}},e.CheckoutConfiguration=wm}));
|