@imtbl/sdk 0.30.0 → 0.30.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blockchain_data.js +1 -1
- package/dist/browser/checkout/sdk.js +1 -1
- package/dist/checkout_sdk.js +2 -2
- package/dist/immutablex_client.js +1 -1
- package/dist/index.browser.js +3 -3
- package/dist/index.cjs +4 -4
- package/dist/index.js +4 -4
- package/dist/passport.js +2 -2
- package/package.json +1 -1
|
@@ -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,M=c.words,P=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,M[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,P[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)}(Zk)),tO(),nO||(nO=1,function(e,t){var n;e.exports=(n=gk(),qk(),tO(),function(){var e=n,t=e.lib,r=t.Base,i=t.WordArray,a=e.algo,o=a.SHA1,s=a.HMAC,u=a.PBKDF2=r.extend({cfg:r.extend({keySize:4,hasher:o,iterations:1}),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)}(rO)),oO(),cO(),fO(),mO(),bO(),TO(),AO||(AO=1,function(e,t){var n,r;e.exports=(r=gk(),cO(),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)}(EO)),_O||(_O=1,function(e,t){var n;e.exports=(n=gk(),cO(),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)}(IO)),RO||(RO=1,function(e,t){var n;e.exports=(n=gk(),cO(),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)}(CO)),kO||(kO=1,function(e,t){var n;e.exports=(n=gk(),cO(),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)}(OO)),SO||(SO=1,function(e,t){var n;e.exports=(n=gk(),cO(),n.pad.ZeroPadding={pad:function(e,t){var n=4*t;e.clamp(),e.sigBytes+=n-(e.sigBytes%n||n)},unpad:function(e){for(var t=e.words,n=e.sigBytes-1;!(t[n>>>2]>>>24-n%4*8&255);)n--;e.sigBytes=n+1}},n.pad.ZeroPadding)}(NO)),xO||(xO=1,function(e,t){var n;e.exports=(n=gk(),cO(),n.pad.NoPadding={pad:function(){},unpad:function(){}},n.pad.NoPadding)}(MO)),PO||(PO=1,function(e,t){var n,r,i,a;e.exports=(a=gk(),cO(),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)}(BO)),DO||(DO=1,function(e,t){var n;e.exports=(n=gk(),Pk(),Fk(),oO(),cO(),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++)if(o<n)a[o]=t[o];else{var s=a[o-1];o%n?n>6&&o%n==4&&(s=i[s>>>24]<<24|i[s>>>16&255]<<16|i[s>>>8&255]<<8|i[255&s]):(s=i[(s=s<<8|s>>>24)>>>24]<<24|i[s>>>16&255]<<16|i[s>>>8&255]<<8|i[255&s],s^=h[o/n|0]<<24),a[o]=a[o-n]^s}for(var u=this._invKeySchedule=[],c=0;c<r;c++)o=r-c,s=c%4?a[o]:a[o-4],u[c]=c<4||o<=4?s:l[i[s>>>24]]^d[i[s>>>16&255]]^f[i[s>>>8&255]]^p[i[255&s]]}},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)}(FO)),LO||(LO=1,function(e,t){var n;e.exports=(n=gk(),Pk(),Fk(),oO(),cO(),function(){var e=n,t=e.lib,r=t.WordArray,i=t.BlockCipher,a=e.algo,o=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],s=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],u=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],c=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],l=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],d=a.DES=i.extend({_doReset:function(){for(var e=this._key.words,t=[],n=0;n<56;n++){var r=o[n]-1;t[n]=e[r>>>5]>>>31-r%32&1}for(var i=this._subKeys=[],a=0;a<16;a++){var c=i[a]=[],l=u[a];for(n=0;n<24;n++)c[n/6|0]|=t[(s[n]-1+l)%28]<<31-n%6,c[4+(n/6|0)]|=t[28+(s[n+24]-1+l)%28]<<31-n%6;for(c[0]=c[0]<<1|c[0]>>>31,n=1;n<7;n++)c[n]=c[n]>>>4*(n-1)+3;c[7]=c[7]<<5|c[7]>>>27}var d=this._invSubKeys=[];for(n=0;n<16;n++)d[n]=i[15-n]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._subKeys)},decryptBlock:function(e,t){this._doCryptBlock(e,t,this._invSubKeys)},_doCryptBlock:function(e,t,n){this._lBlock=e[t],this._rBlock=e[t+1],f.call(this,4,252645135),f.call(this,16,65535),p.call(this,2,858993459),p.call(this,8,16711935),f.call(this,1,1431655765);for(var r=0;r<16;r++){for(var i=n[r],a=this._lBlock,o=this._rBlock,s=0,u=0;u<8;u++)s|=c[u][((o^i[u])&l[u])>>>0];this._lBlock=o,this._rBlock=a^s}var d=this._lBlock;this._lBlock=this._rBlock,this._rBlock=d,f.call(this,1,1431655765),p.call(this,8,16711935),p.call(this,2,858993459),f.call(this,16,65535),f.call(this,4,252645135),e[t]=this._lBlock,e[t+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function f(e,t){var n=(this._lBlock>>>e^this._rBlock)&t;this._rBlock^=n,this._lBlock^=n<<e}function p(e,t){var n=(this._rBlock>>>e^this._lBlock)&t;this._lBlock^=n,this._rBlock^=n<<e}e.DES=i._createHelper(d);var h=a.TripleDES=i.extend({_doReset:function(){var e=this._key.words;this._des1=d.createEncryptor(r.create(e.slice(0,2))),this._des2=d.createEncryptor(r.create(e.slice(2,4))),this._des3=d.createEncryptor(r.create(e.slice(4,6)))},encryptBlock:function(e,t){this._des1.encryptBlock(e,t),this._des2.decryptBlock(e,t),this._des3.encryptBlock(e,t)},decryptBlock:function(e,t){this._des3.decryptBlock(e,t),this._des2.encryptBlock(e,t),this._des1.decryptBlock(e,t)},keySize:6,ivSize:2,blockSize:2});e.TripleDES=i._createHelper(h)}(),n.TripleDES)}(UO)),qO||(qO=1,function(e,t){var n;e.exports=(n=gk(),Pk(),Fk(),oO(),cO(),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)}(jO)),GO||(GO=1,function(e,t){var n;e.exports=(n=gk(),Pk(),Fk(),oO(),cO(),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)}(HO)),zO||(zO=1,function(e,t){var n;e.exports=(n=gk(),Pk(),Fk(),oO(),cO(),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)}(VO)),n)}(Ek);var WO=Ek.exports,KO=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ak,"__esModule",{value:!0}),Ak.Base=void 0;const XO=hn,JO=KO(WO);class YO{print(){YO.print(this)}bufferIndexOf(e,t,n=!1){if(n)return this.binarySearch(e,t,XO.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 YO.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 YO.linearSearch(e,t,n)}static bufferify(e){if(!XO.Buffer.isBuffer(e)){if("object"==typeof e&&e.words)return XO.Buffer.from(e.toString(JO.default.enc.Hex),"hex");if(YO.isHexString(e))return XO.Buffer.from(e.replace(/^0x/,""),"hex");if("string"==typeof e)return XO.Buffer.from(e);if("bigint"==typeof e)return XO.Buffer.from(e.toString(16),"hex");if(e instanceof Uint8Array)return XO.Buffer.from(e.buffer);if("number"==typeof e){let t=e.toString();return t.length%2&&(t=`0${t}`),XO.Buffer.from(t,"hex")}if(ArrayBuffer.isView(e))return XO.Buffer.from(e.buffer,e.byteOffset,e.byteLength)}return e}bigNumberify(e){return YO.bigNumberify(e)}static bigNumberify(e){if("bigint"==typeof e)return e;if("string"==typeof e)return e.startsWith("0x")&&YO.isHexString(e)?BigInt("0x"+e.replace("0x","").toString()):BigInt(e);if(XO.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 YO.bufferToHex(e,t)}static bufferToHex(e,t=!0){return`${t?"0x":""}${(e||XO.Buffer.alloc(0)).toString("hex")}`}bufferify(e){return YO.bufferify(e)}bufferifyFn(e){return t=>{const n=e(t);return XO.Buffer.isBuffer(n)?n:this.isHexString(n)?XO.Buffer.from(n.replace("0x",""),"hex"):"string"==typeof n?XO.Buffer.from(n):"bigint"==typeof n?XO.Buffer.from(t.toString(16),"hex"):ArrayBuffer.isView(n)?XO.Buffer.from(n.buffer,n.byteOffset,n.byteLength):XO.Buffer.from(e(JO.default.enc.Hex.parse(t.toString("hex"))).toString(JO.default.enc.Hex),"hex")}}isHexString(e){return YO.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")}}Ak.Base=YO,Ak.default=YO;var QO=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(hk,"__esModule",{value:!0}),hk.MerkleTree=void 0;const ZO=hn,$O=QO((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})),eS=QO(bk),tS=QO(Tk),nS=QO(Ak);let rS=class e extends nS.default{constructor(e,t=eS.default,n={}){if(super(),this.duplicateOdd=!1,this.concatenator=ZO.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(!ZO.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(ZO.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([$O.default(n),$O.default(n)])),i=$O.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?[$O.default(i),$O.default(a)]:[i,a],this.sortPairs&&o.sort(ZO.Buffer.compare);let s=this.hashFn(this.concatenator(o));this.isBitcoinTree&&(s=$O.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(ZO.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?ZO.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(ZO.Buffer.from([0])),e}getHexLayersFlat(){return this.getLayersFlat().map((e=>this.bufferToHex(e)))}getLayerCount(){return this.getLayers().length}getRoot(){return 0===this.layers.length?ZO.Buffer.from([]):this.layers[this.layers.length-1][0]||ZO.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===ZO.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:ZO.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=eS.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(ZO.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(ZO.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($O.default(r)),o[a?"unshift":"push"]($O.default(i)),r=this.hashFn(this.concatenator(o)),r=$O.default(this.hashFn(r))):this.sortPairs?-1===ZO.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===ZO.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(ZO.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(ZO.Buffer.compare);o[e]=this.hashFn(this.concatenator(a))}return 0===ZO.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=eS.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 tS.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]}};hk.MerkleTree=rS,"undefined"!=typeof window&&(window.MerkleTree=rS),hk.default=rS;var iS={},aS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(iS,"__esModule",{value:!0}),iS.MerkleMountainRange=void 0;const oS=hn,sS=aS(bk),uS=aS(Ak);class cS extends uS.default{constructor(e=sS.default,t=[],n,r,i){super(),this.root=oS.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(oS.Buffer.concat([this.bufferify(e),t]))}hashBranch(e,t,n){return this.hashBranchFn?this.bufferify(this.hashBranchFn(e,t,n)):this.hashFn(oS.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(oS.Buffer.concat([this.bufferify(n),...t.map(this.bufferify)])):oS.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]}}iS.MerkleMountainRange=cS,"undefined"!=typeof window&&(window.MerkleMountainRange=cS),iS.default=cS;var lS={},dS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(lS,"__esModule",{value:!0}),lS.IncrementalMerkleTree=void 0;const fS=dS(Ak),pS=dS(Tk);class hS extends fS.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 pS.default.asTree(e,!0)}}lS.IncrementalMerkleTree=hS,"undefined"!=typeof window&&(window.IncrementalMerkleTree=hS),lS.default=hS;var mS={};Object.defineProperty(mS,"__esModule",{value:!0}),mS.MerkleSumTree=mS.ProofStep=mS.Leaf=mS.Bucket=void 0;const yS=Ak;class gS{constructor(e,t){this.size=BigInt(e),this.hashed=t,this.parent=null,this.left=null,this.right=null}}mS.Bucket=gS;mS.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 gS(BigInt(this.rng[1])-BigInt(this.rng[0]),e)}};class bS{constructor(e,t){this.bucket=e,this.right=t}}mS.ProofStep=bS;class vS extends yS.Base{constructor(e,t){super(),this.leaves=e,this.hashFn=t,vS.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 gS(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 bS(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 gS(BigInt(a.size)+BigInt(e.bucket.size),i);return a.size===e.size&&a.hashed.toString("hex")===e.hashed.toString("hex")}}mS.MerkleSumTree=vS,"undefined"!=typeof window&&(window.MerkleSumTree=vS),mS.default=vS,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(hk);e.MerkleTree=n.default;var r=iS;Object.defineProperty(e,"MerkleMountainRange",{enumerable:!0,get:function(){return r.MerkleMountainRange}});var i=lS;Object.defineProperty(e,"IncrementalMerkleTree",{enumerable:!0,get:function(){return i.IncrementalMerkleTree}});var a=mS;Object.defineProperty(e,"MerkleSumTree",{enumerable:!0,get:function(){return a.MerkleSumTree}}),e.default=n.default}(pk);var wS={};Object.defineProperty(wS,"__esModule",{value:!0}),wS.DefaultGetter=void 0;const TS=pC,AS=new AC.Logger("defaults"),ES={integer:0,address:(0,TS.hexZeroPad)("0x",20),bool:!1,bytes:"0x",string:""},_S=e=>void 0!==e&&(null!=e&&(["string","number"].includes(typeof e)&&BigInt(e)===BigInt(0)||Array.isArray(e)&&e.every(_S)||"object"==typeof e&&Object.values(e).every(_S)||"boolean"==typeof e&&!1===e));class IS{constructor(e){this.types=e,this.defaultValues={};for(const t in e){const e=this.getDefaultValue(t);this.defaultValues[t]=e,_S(e)||AS.throwError(`Got non-empty value for type ${t} in default generator: ${e}`)}}static from(e,t){const{defaultValues:n}=new IS(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,TS.hexZeroPad)("0x",parseInt(n)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),ES[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)})),{}):AS.throwArgumentError(`unknown type: ${e}`,"type",e)}}wS.DefaultGetter=IS;var RS={};!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)}(RS),Object.defineProperty(fk,"__esModule",{value:!0}),fk.Eip712MerkleTree=void 0;const CS=bC,kS=pC,OS=pk,SS=wS,NS=RS;fk.Eip712MerkleTree=class{get completedSize(){return Math.pow(2,this.depth)}getCompleteElements(){const e=this.elements;return(0,NS.fillArray)([...e],this.completedSize,this.defaultNode)}getCompleteLeaves(){const e=this.elements.map(this.leafHasher);return(0,NS.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,kS.hexConcat)([n,`0x${e.toString(16).padStart(6,"0")}`,kS.defaultAbiCoder.encode([`uint256[${t.length}]`],[t])]))(e,n,t)}getDataToSign(){let e=this.getCompleteElements();for(;e.length>2;)e=(0,NS.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(NS.hexToBuffer),n=(0,NS.bufferToHex)((0,NS.getRoot)(t,!1)),r=(0,kS.keccak256)((0,kS.toUtf8Bytes)(this.encoder._types.BulkOrder));if((0,kS.keccak256)((0,kS.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=CS._TypedDataEncoder.from(e);var o,s;this.encoder=a,this.leafHasher=e=>a.hashStruct(n,e),this.defaultNode=SS.DefaultGetter.from(e,n),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=(o=this.getCompleteLeaves(),s=this.defaultLeaf,new OS.MerkleTree(o.map(NS.hexToBuffer),NS.bufferKeccak,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:(0,NS.hexToBuffer)(s)}))}},Object.defineProperty(dk,"__esModule",{value:!0}),dk.getBulkOrderTypeHashes=dk.getBulkOrderTypeHash=dk.getBulkOrderTree=dk.getBulkOrderTreeHeight=void 0;const xS=pC,MS=fk,PS=wS,BS=RS,DS=BC;function FS(e){const t=Object.assign({},DS.EIP_712_BULK_ORDER_TYPE);return t.BulkOrder=[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}],t}function LS(e){return Math.max(Math.ceil(Math.log2(e)),1)}function US(e){const t=FS(e),n=xS._TypedDataEncoder.from(t),r=(0,xS.toUtf8Bytes)(n._types.BulkOrder);return(0,xS.keccak256)(r)}dk.getBulkOrderTreeHeight=LS,dk.getBulkOrderTree=function(e,t=0,n=LS(e.length+t)){const r=FS(n),i=PS.DefaultGetter.from(r,"OrderComponents");let a=[...e];return t>0&&(a=[...(0,BS.fillArray)([],t,i),...e]),new MS.Eip712MerkleTree(r,"BulkOrder","OrderComponents",a,n)},dk.getBulkOrderTypeHash=US,dk.getBulkOrderTypeHashes=function(e){const t=[];for(let n=0;n<e;n++)t.push(US(n+1));return t};var qS={},jS={},GS={};Object.defineProperty(GS,"__esModule",{value:!0}),GS.MerkleTree=void 0;const HS=fC,zS=pC,VS=pk,WS=e=>(0,zS.keccak256)(Buffer.from(HS.BigNumber.from(e).toHexString().slice(2).padStart(64,"0"),"hex"));GS.MerkleTree=class{constructor(e){this.tree=new VS.default(e.map(WS),zS.keccak256,{sort:!0})}getProof(e){return this.tree.getHexProof(WS(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 KS=fC,XS=pC,JS=BC,YS=VC(),QS=GS,ZS=(e,t)=>KS.BigNumber.from(e).mul(KS.BigNumber.from(t)).div(JS.ONE_HUNDRED_PERCENT_BP);jS.feeToConsiderationItem=({fee:e,token:t,baseAmount:n,baseEndAmount:r=n})=>({itemType:t===KS.ethers.constants.AddressZero?JS.ItemType.NATIVE:JS.ItemType.ERC20,token:t,identifierOrCriteria:"0",startAmount:ZS(n,e.basisPoints).toString(),endAmount:ZS(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,YS.isCurrencyItem)(e)?KS.BigNumber.from(e.startAmount).sub(ZS(e.startAmount,n)).toString():e.startAmount,endAmount:(0,YS.isCurrencyItem)(e)?KS.BigNumber.from(e.endAmount).sub(ZS(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 QS.MerkleTree(e.identifiers).getRoot();return{itemType:e.itemType===JS.ItemType.ERC721?JS.ItemType.ERC721_WITH_CRITERIA:JS.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!==KS.ethers.constants.AddressZero?JS.ItemType.ERC20:JS.ItemType.NATIVE,token:null!==(s=e.token)&&void 0!==s?s:KS.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(YS.isCurrencyItem);return n.every((({itemType:e,token:t})=>e===n[0].itemType&&t.toLowerCase()===n[0].token.toLowerCase()))};jS.totalItemsAmount=e=>(KS.BigNumber.from(0),KS.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:KS.BigNumber.from(0),endAmount:KS.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(JS.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:ZS(e.startAmount,r).toString(),endAmount:ZS(e.endAmount,r).toString()}))),consideration:e.parameters.consideration.map((e=>Object.assign(Object.assign({},e),{startAmount:ZS(e.startAmount,r).toString(),endAmount:ZS(e.endAmount,r).toString()})))}),signature:e.signature}};const $S=(e,t,n)=>KS.BigNumber.from(e).mul(KS.BigNumber.from(t)).div(n);jS.mapOrderAmountsFromUnitsToFill=(e,{unitsToFill:t,totalSize:n})=>{const r=KS.BigNumber.from(t);if(r.lte(0))throw new Error("Units to fill must be greater than 1");const i=(0,YS.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:$S(e.startAmount,r,n).toString(),endAmount:$S(e.endAmount,r,n).toString()}))),consideration:e.parameters.consideration.map((e=>Object.assign(Object.assign({},e),{startAmount:$S(e.startAmount,r,n).toString(),endAmount:$S(e.endAmount,r,n).toString()})))}),signature:e.signature}};jS.generateRandomSalt=e=>e?`0x${Buffer.from((0,XS.concat)([(0,XS.keccak256)((0,XS.toUtf8Bytes)(e)).slice(0,10),Uint8Array.from(Array(20).fill(0)),(0,XS.randomBytes)(8)])).toString("hex")}`:`0x${Buffer.from((0,XS.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},M={value:S},P=[...(0,r.getApprovalActions)(N,b,h),{type:"exchange",transactionMethods:(0,c.getTransactionMethods)(a.connect(h),"fulfillBasicOrder",[x,M],g)}];return{actions:P,executeAllActions:()=>(0,c.executeAllActions)(P)}},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))),M=N.filter((({itemType:e})=>(0,s.isCriteriaItem)(e))),P=x.length>0||M.length>0;if(x.length!==f.length||M.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)||P||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"}),P?(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)}}}(qS);var eN=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 tN=dC,nN=fC,rN=pC,iN=MC,aN=PC,oN=BC,sN=DC,uN=ek,cN=dk,lN=qS,dN=VC(),fN=jS,pN=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=oN.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=nN.ethers.utils.keccak256(nN.ethers.utils.toUtf8Bytes(t)),a=nN.ethers.utils.keccak256(nN.ethers.utils.toUtf8Bytes(n)),o=nN.ethers.utils.keccak256(nN.ethers.utils.toUtf8Bytes(r)),s=nN.ethers.utils.keccak256("0x"+e.offer.map((e=>nN.ethers.utils.keccak256("0x"+[i.slice(2),e.itemType.toString().padStart(64,"0"),e.token.slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.identifierOrCriteria).toHexString().slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.startAmount).toHexString().slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.endAmount).toHexString().slice(2).padStart(64,"0")].join("")).slice(2))).join("")),u=nN.ethers.utils.keccak256("0x"+e.consideration.map((e=>nN.ethers.utils.keccak256("0x"+[a.slice(2),e.itemType.toString().padStart(64,"0"),e.token.slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.identifierOrCriteria).toHexString().slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.startAmount).toHexString().slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.endAmount).toHexString().slice(2).padStart(64,"0"),e.recipient.slice(2).padStart(64,"0")].join("")).slice(2))).join(""));return nN.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"),nN.ethers.BigNumber.from(e.startTime).toHexString().slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.endTime).toHexString().slice(2).padStart(64,"0"),e.zoneHash.slice(2),nN.BigNumber.from(e.salt).toHexString().slice(2).padStart(64,"0"),e.conduitKey.slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.counter).toHexString().slice(2).padStart(64,"0")].join(""))};const c=e instanceof nN.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 tN.providers.MulticallProvider(this.provider),this.contract=new nN.Contract(null!==(o=null==t?void 0:t.contractAddress)&&void 0!==o?o:"1.5"===a?oN.CROSS_CHAIN_SEAPORT_V1_5_ADDRESS:oN.CROSS_CHAIN_SEAPORT_V1_4_ADDRESS,aN.SeaportABIv14,this.multicallProvider),this.domainRegistry=new nN.Contract(null!==(s=null==t?void 0:t.domainRegistryAddress)&&void 0!==s?s:oN.DOMAIN_REGISTRY_ADDRESS,iN.DomainRegistryABI,this.multicallProvider),this.config={ascendingAmountFulfillmentBuffer:n,balanceAndApprovalChecksOnOrderCreation:r,conduitKeyToConduit:Object.assign(Object.assign(Object.assign({},oN.KNOWN_CONDUIT_KEYS_TO_CONDUIT),{[oN.NO_CONDUIT]:this.contract.address}),i),seaportVersion:a},this.defaultConduitKey=null!==(u=null==t?void 0:t.defaultConduitKey)&&void 0!==u?u:oN.NO_CONDUIT}createOrder(e,t,n){return eN(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:()=>eN(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,pN.executeAllActions)(u)}}))}createBulkOrders(e,t,n){var r;return eN(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:()=>eN(this,void 0,void 0,(function*(){return yield this.signBulkOrder(u,a)}))},l=[...s,c];return{actions:l,executeAllActions:()=>(0,pN.executeAllActions)(l)}}))}_formatOrder(e,t,n,{conduitKey:r=this.defaultConduitKey,zone:i=nN.ethers.constants.AddressZero,zoneHash:a=nN.ethers.constants.HashZero,startTime:o=Math.floor(Date.now()/1e3).toString(),endTime:s=oN.MAX_INT.toString(),offer:u,consideration:c,counter:l,allowPartialFills:d,restrictedByZone:f,fees:p,domain:h,salt:m}){var y;return eN(this,void 0,void 0,(function*(){const g=u.map(fN.mapInputItemToOfferItem),b=[...c.map((e=>{var n;return Object.assign(Object.assign({},(0,fN.mapInputItemToOfferItem)(e)),{recipient:null!==(n=e.recipient)&&void 0!==n?n:t})}))];if((null==p?void 0:p.length)&&!(0,fN.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(dN.isCurrencyItem),w=(0,fN.totalItemsAmount)(v),T=this.config.conduitKeyToConduit[r],A=this._getOrderTypeFromOrderOptions({allowPartialFills:d,restrictedByZone:f}),E=[...(0,fN.deductFees)(b,p),...v.length&&null!==(y=null==p?void 0:p.map((e=>(0,fN.feeToConsiderationItem)({fee:e,token:v[0].token,baseAmount:w.startAmount,baseEndAmount:w.endAmount}))))&&void 0!==y?y:[]],_=void 0!==m?`0x${nN.BigNumber.from(m).toHexString().slice(2).padStart(64,"0")}`:(0,fN.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,uN.getBalancesAndApprovals)({owner:t,items:g,criterias:[],multicallProvider:this.multicallProvider,operator:T}),i=(0,uN.validateOfferBalancesAndApprovals)({offer:g,criterias:[],balancesAndApprovals:r,throwOnInsufficientBalances:!0,operator:T}),a=(0,sN.getApprovalActions)(i,n,e);R.push(...a)}return{orderComponents:I,approvalActions:R}}))}_getSigner(e){if(this.signer)return this.signer;if(!(this.provider instanceof nN.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?oN.OrderType.PARTIAL_RESTRICTED:oN.OrderType.PARTIAL_OPEN:t?oN.OrderType.FULL_RESTRICTED:oN.OrderType.FULL_OPEN}_getDomainData(){return eN(this,void 0,void 0,(function*(){const{chainId:e}=yield this.provider.getNetwork();return{name:oN.SEAPORT_CONTRACT_NAME,version:"1.5"===this.config.seaportVersion?oN.SEAPORT_CONTRACT_VERSION_V1_5:oN.SEAPORT_CONTRACT_VERSION_V1_4,chainId:e,verifyingContract:this.contract.address}}))}_getMessageToSign(e){return eN(this,void 0,void 0,(function*(){const t=yield this._getDomainData();return JSON.stringify(rN._TypedDataEncoder.getPayload(t,oN.EIP_712_ORDER_TYPE,e))}))}_getBulkMessageToSign(e){return eN(this,void 0,void 0,(function*(){const t=yield this._getDomainData(),n=(0,cN.getBulkOrderTree)(e),r=n.types,i=n.getDataToSign();return JSON.stringify(rN._TypedDataEncoder.getPayload(t,r,{tree:i}))}))}signOrder(e,t){return eN(this,void 0,void 0,(function*(){const n=this._getSigner(t),r=yield this._getDomainData();let i=yield n._signTypedData(r,oN.EIP_712_ORDER_TYPE,e);return 132===i.length&&(i=nN.ethers.utils.splitSignature(i).compact),i}))}signBulkOrder(e,t){return eN(this,void 0,void 0,(function*(){const n=this._getSigner(t),r=yield this._getDomainData(),i=(0,cN.getBulkOrderTree)(e),a=i.types,o={tree:i.getDataToSign()};let s=yield n._signTypedData(r,a,o);132===s.length&&(s=nN.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,pN.getTransactionMethods)(this.contract.connect(r),"cancel",[e],n)}bulkCancelOrders(e,t){const n=this._getSigner(e);return(0,pN.getTransactionMethods)(this.contract.connect(n),"incrementCounter",[],t)}validate(e,t,n){const r=this._getSigner(t);return(0,pN.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=nN.ethers.constants.AddressZero,domain:c,exactApproval:l=!1}){return eN(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,uN.getBalancesAndApprovals)({owner:f,items:p,criterias:n,multicallProvider:this.multicallProvider,operator:g}),(0,uN.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,lN.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,fN.mapInputItemToOfferItem)(e)),{recipient:e.recipient}))),O=u===nN.ethers.constants.AddressZero;return!t&&O&&(0,lN.shouldUseBasicFulfill)(R.parameters,_)?(0,lN.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,lN.fulfillStandardOrder)({order:R,unitsToFill:t,totalFilled:_,totalSize:I.eq(0)?(0,dN.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=nN.ethers.constants.AddressZero,domain:i,exactApproval:a=!1}){return eN(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,uN.getBalancesAndApprovals)({owner:e.parameters.offerer,items:e.parameters.offer,criterias:t,operator:u[n],multicallProvider:this.multicallProvider})))),(0,uN.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,fN.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,lN.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,pN.getTransactionMethods)(this.contract.connect(a),"matchOrders",[e,t,n],i)}setDomain(e,t){const n=this._getSigner(t);return(0,pN.getTransactionMethods)(this.domainRegistry.connect(n),"setDomain",[e])}getNumberOfDomains(e){return eN(this,void 0,void 0,(function*(){return this.domainRegistry.getNumberOfDomains(e)}))}getDomain(e,t){return this.domainRegistry.getDomain(e,t)}getDomains(e,t){return eN(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 hN{config;constructor(e){this.config=e}}class mN 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 yN extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}}class gN{[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 yN("Request aborted"))}}get isCancelled(){return this._isCancelled}}const bN=e=>null!=e,vN=e=>"string"==typeof e,wN=e=>vN(e)&&""!==e,TN=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]),AN=e=>{const t=[],n=(e,r)=>{bN(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("&")}`:""},EN=async(e,t)=>"function"==typeof t?t(e):t,_N=async(e,t,n)=>{const r=await EN(t,e.TOKEN),i=await EN(t,e.USERNAME),a=await EN(t,e.PASSWORD),o=await EN(t,e.HEADERS),s="function"==typeof n?.getHeaders&&n?.getHeaders()||{},u=Object.entries({Accept:"application/json",...o,...t.headers,...s}).filter((([e,t])=>bN(t))).reduce(((e,[t,n])=>({...e,[t]:String(n)})),{});if(wN(r)&&(u.Authorization=`Bearer ${r}`),wN(i)&&wN(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:TN(t.body)?u["Content-Type"]=t.body.type||"application/octet-stream":vN(t.body)?u["Content-Type"]="text/plain":t.body instanceof UR||(u["Content-Type"]="application/json")),u},IN=(e,t)=>new gN((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}${AN(t.query)}`:i})(e,t),o=(e=>{if(e.formData){const t=new UR,n=(e,n)=>{vN(n)||TN(n)?t.append(e,n):t.append(e,JSON.stringify(n))};return Object.entries(e.formData).filter((([e,t])=>bN(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 _N(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(vN(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 mN(e,t,n);if(!t.ok)throw new mN(e,t,"Generic Error")})(t,f),n(f.body)}}catch(e){r(e)}var a}));class RN extends hN{constructor(e){super(e)}request(e){return IN(this.config,e)}}class CN{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 kN{orders;request;constructor(e,t=RN){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 CN(this.request)}}var ON,SN,NN,xN,MN,PN,BN,DN,FN;function LN(e){const t=e.buy.map((e=>{if("ERC20"===e.item_type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.start_amount};if("NATIVE"===e.item_type)return{type:"NATIVE",amount:e.start_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 UN(e){const t=e.buy.map((e=>{if("ERC20"===e.item_type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.start_amount};if("NATIVE"===e.item_type)return{type:"NATIVE",amount:e.start_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 qN(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"}(ON||(ON={})),function(e){(e.reason_code||(e.reason_code={})).FILLED="FILLED"}(SN||(SN={})),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"}(NN||(NN={})),function(e){e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.FILLED="FILLED",e.EXPIRED="EXPIRED",e.CANCELLED="CANCELLED"}(xN||(xN={})),function(e){(e.order_type||(e.order_type={})).FULL_RESTRICTED="FULL_RESTRICTED"}(MN||(MN={})),function(e){e.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",e.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",e.PROTOCOL="PROTOCOL",e.ROYALTY="ROYALTY"}(PN||(PN={})),function(e){e.APPROVAL="APPROVAL",e.FULFILL_ORDER="FULFILL_ORDER",e.CANCEL="CANCEL"}(BN||(BN={})),function(e){e.CREATE_LISTING="CREATE_LISTING",e.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION"}(DN||(DN={})),function(e){e.TRANSACTION="TRANSACTION",e.SIGNABLE="SIGNABLE"}(FN||(FN={}));const jN="1.5",GN={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 HN,zN,VN,WN;function KN(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"}(HN||(HN={})),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"}(VN||(VN={})),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"}(WN||(WN={}));class XN{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:FN.TRANSACTION,purpose:BN.APPROVAL,buildTransaction:KN(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:FN.SIGNABLE,purpose:DN.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:FN.TRANSACTION,buildTransaction:KN(u.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:BN.APPROVAL});const c=o.find((e=>"exchange"===e.type));if(!c)throw new Error("No exchange action found");return s.push({type:FN.TRANSACTION,buildTransaction:KN(c.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:BN.FULFILL_ORDER}),{actions:s,expiration:XN.getExpirationISOTimeFromExtraData(n),order:LN(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:FN.TRANSACTION,buildTransaction:KN(a.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:BN.APPROVAL});const o=r.find((e=>"exchange"===e.type));if(!o)throw new Error("No exchange action found");return i.push({type:FN.TRANSACTION,buildTransaction:KN(o.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:BN.FULFILL_ORDER}),{actions:i,expiration:n.map((e=>XN.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:FN.TRANSACTION,buildTransaction:KN(i,(await this.provider.getNetwork()).chainId),purpose:BN.CANCEL}}mapImmutableOrderToSeaportOrderComponents(e){return function(e,t,n){const r=e.buy.map((t=>{switch(t.item_type){case"NATIVE":return{startAmount:t.start_amount,endAmount:t.start_amount,itemType:zN.NATIVE,recipient:e.account_address,token:ji,identifierOrCriteria:"0"};case"ERC20":return{startAmount:t.start_amount,endAmount:t.start_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:HN.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:GN,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 JN{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",start_amount:t.consideration[0].startAmount,contract_address:t.consideration[0].token}],fees:r.map((e=>({amount:e.amount,fee_type:PN.MAKER_ECOSYSTEM,recipient:e.recipient}))),end_at:new Date(parseInt(`${t.endTime.toString()}000`,10)).toISOString(),protocol_data:{order_type:MN.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 YN{chainName;seaportAddress;orderbookClient;constructor(e,t,n){this.chainName=t,this.seaportAddress=n,this.orderbookClient=new kN({BASE:e})}create(){return new JN(this.orderbookClient.orders,this.chainName,this.seaportAddress)}}class QN{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 ZN{apiClient;seaport;orderbookConfig;constructor(e){const t={...function(e){switch(e){case st.SANDBOX:return{seaportContractAddress:"0x7Fb7Da6De152597830eD16361633e362A2F59410",zoneContractAddress:"0x63441cBfBd15Dd8f5E92598E535661Ac5aCB808E",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 YN(n,r,this.orderbookConfig.seaportContractAddress).create();const i=new QN(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new XN(i,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress)}config(){return this.orderbookConfig}async getListing(e){return{result:LN((await this.apiClient.getListing(e)).result)}}async getTrade(e){return{result:UN((await this.apiClient.getTrade(e)).result)}}async listListings(e){const t=await this.apiClient.listListings(e);return{page:qN(t.page),result:t.result.map(LN)}}async listTrades(e){const t=await this.apiClient.listTrades(e);return{page:qN(t.page),result:t.result.map(UN)}}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:LN((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:PN.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!==xN.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:PN.TAKER_ECOSYSTEM,recipient:e.recipient})))}))));try{return{...await this.seaport.fulfillBulkOrders(n.result.fulfillable_orders,t),fulfillableOrders:n.result.fulfillable_orders.map((e=>LN(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=>LN(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:DN.OFF_CHAIN_CANCELLATION,type:FN.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!==xN.ACTIVE&&e.result.status.name!==xN.INACTIVE&&e.result.status.name!==xN.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 $N=4e5,ex="https://api.sandbox.immutable.com".replace(/\/+$/,"");class tx{basePath;axios;configuration;constructor(e,t=ex,n=Ve){this.basePath=t,this.axios=n,e&&(this.configuration=e,this.basePath=e.basePath||this.basePath)}}class nx extends Error{field;constructor(e,t){super(t),this.field=e,this.name="RequiredError"}}const rx="https://example.com",ix=function(e,t,n){if(null==n)throw new nx(t,`Required parameter ${t} was null or undefined when calling ${e}.`)},ax=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}},ox=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 sx(e,t,n=""){null!=t&&("object"==typeof t?Array.isArray(t)?t.forEach((t=>sx(e,t,n))):Object.keys(t).forEach((r=>sx(e,t[r],`${n}${""!==n?".":""}${r}`))):e.has(n)?e.append(n,t):e.set(n,t))}const ux=function(e,...t){const n=new URLSearchParams(e.search);sx(n,t),e.search=n.toString()},cx=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||""},lx=function(e){return e.pathname+e.search+e.hash},dx=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)}},fx=function(e){return{getActivity:async(t,n,r={})=>{ix("getActivity","chainName",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};ux(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:lx(a),options:s}},listActivities:async(t,n,r,i,a,o,s,u,c,l,d={})=>{ix("listActivities","chainName",t);const f="/v1/chains/{chain_name}/activities".replace("{chain_name}",encodeURIComponent(String(t))),p=new URL(f,rx);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),ux(p,y);let g=h&&h.headers?h.headers:{};return m.headers={...g,...d.headers},{url:lx(p),options:m}}}},px=function(e){const t=fx(e);return{async getActivity(n,r,i){const a=await t.getActivity(n,r,i);return dx(a,Ve,ex,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 dx(p,Ve,ex,e)}}};const hx=function(e){return{listChains:async(t,n,r={})=>{const i=new URL("/v1/chains",rx);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),ux(i,s);let u=a&&a.headers?a.headers:{};return o.headers={...u,...r.headers},{url:lx(i),options:o}}}},mx=function(e){const t=hx(e);return{async listChains(n,r,i){const a=await t.listChains(n,r,i);return dx(a,Ve,ex,e)}}};const yx=function(e){return{getCollection:async(t,n,r={})=>{ix("getCollection","contractAddress",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};ux(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:lx(a),options:s}},listCollections:async(t,n,r,i,a,o={})=>{ix("listCollections","chainName",t);const s="/v1/chains/{chain_name}/collections".replace("{chain_name}",encodeURIComponent(String(t))),u=new URL(s,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}},listCollectionsByNFTOwner:async(t,n,r,i,a={})=>{ix("listCollectionsByNFTOwner","accountAddress",t),ix("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,rx);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),ux(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:lx(s),options:c}},refreshCollectionMetadata:async(t,n,r,i={})=>{ix("refreshCollectionMetadata","contractAddress",t),ix("refreshCollectionMetadata","chainName",n),ix("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,rx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await ax(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",ux(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=cx(r,u,e),{url:lx(o),options:u}}}},gx=function(e){const t=yx(e);return{async getCollection(n,r,i){const a=await t.getCollection(n,r,i);return dx(a,Ve,ex,e)},async listCollections(n,r,i,a,o,s){const u=await t.listCollections(n,r,i,a,o,s);return dx(u,Ve,ex,e)},async listCollectionsByNFTOwner(n,r,i,a,o){const s=await t.listCollectionsByNFTOwner(n,r,i,a,o);return dx(s,Ve,ex,e)},async refreshCollectionMetadata(n,r,i,a){const o=await t.refreshCollectionMetadata(n,r,i,a);return dx(o,Ve,ex,e)}}};const bx=function(e){return{getMetadata:async(t,n,r,i={})=>{ix("getMetadata","chainName",t),ix("getMetadata","contractAddress",n),ix("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,rx);let s;e&&(s=e.baseOptions);const u={method:"GET",...s,...i};ux(o,{});let c=s&&s.headers?s.headers:{};return u.headers={...c,...i.headers},{url:lx(o),options:u}},listMetadata:async(t,n,r,i,a,o={})=>{ix("listMetadata","chainName",t),ix("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,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}},refreshMetadataByID:async(t,n,r,i={})=>{ix("refreshMetadataByID","chainName",t),ix("refreshMetadataByID","contractAddress",n),ix("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,rx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await ax(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",ux(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=cx(r,u,e),{url:lx(o),options:u}},refreshNFTMetadataByTokenID:async(t,n,r,i={})=>{ix("refreshNFTMetadataByTokenID","contractAddress",t),ix("refreshNFTMetadataByTokenID","chainName",n),ix("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,rx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await ax(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",ux(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=cx(r,u,e),{url:lx(o),options:u}}}},vx=function(e){const t=bx(e);return{async getMetadata(n,r,i,a){const o=await t.getMetadata(n,r,i,a);return dx(o,Ve,ex,e)},async listMetadata(n,r,i,a,o,s){const u=await t.listMetadata(n,r,i,a,o,s);return dx(u,Ve,ex,e)},async refreshMetadataByID(n,r,i,a){const o=await t.refreshMetadataByID(n,r,i,a);return dx(o,Ve,ex,e)},async refreshNFTMetadataByTokenID(n,r,i,a){const o=await t.refreshNFTMetadataByTokenID(n,r,i,a);return dx(o,Ve,ex,e)}}};const wx=function(e){return{listNFTOwners:async(t,n,r,i,a,o={})=>{ix("listNFTOwners","contractAddress",t),ix("listNFTOwners","tokenId",n),ix("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,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}},listOwnersByContractAddress:async(t,n,r,i,a,o={})=>{ix("listOwnersByContractAddress","contractAddress",t),ix("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,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}}}},Tx=function(e){const t=wx(e);return{async listNFTOwners(n,r,i,a,o,s){const u=await t.listNFTOwners(n,r,i,a,o,s);return dx(u,Ve,ex,e)},async listOwnersByContractAddress(n,r,i,a,o,s){const u=await t.listOwnersByContractAddress(n,r,i,a,o,s);return dx(u,Ve,ex,e)}}};const Ax=function(e){return{getNFT:async(t,n,r,i={})=>{ix("getNFT","contractAddress",t),ix("getNFT","tokenId",n),ix("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,rx);let s;e&&(s=e.baseOptions);const u={method:"GET",...s,...i};ux(o,{});let c=s&&s.headers?s.headers:{};return u.headers={...c,...i.headers},{url:lx(o),options:u}},listAllNFTOwners:async(t,n,r,i,a={})=>{ix("listAllNFTOwners","chainName",t),ix("listAllNFTOwners","fromUpdatedAt",n);const o="/v1/chains/{chain_name}/nft-owners".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,rx);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),ux(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:lx(s),options:c}},listAllNFTs:async(t,n,r,i,a={})=>{ix("listAllNFTs","chainName",t);const o="/v1/chains/{chain_name}/nfts".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,rx);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),ux(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:lx(s),options:c}},listNFTs:async(t,n,r,i,a,o={})=>{ix("listNFTs","contractAddress",t),ix("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,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}},listNFTsByAccountAddress:async(t,n,r,i,a,o={})=>{ix("listNFTsByAccountAddress","accountAddress",t),ix("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,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}}}},Ex=function(e){const t=Ax(e);return{async getNFT(n,r,i,a){const o=await t.getNFT(n,r,i,a);return dx(o,Ve,ex,e)},async listAllNFTOwners(n,r,i,a,o){const s=await t.listAllNFTOwners(n,r,i,a,o);return dx(s,Ve,ex,e)},async listAllNFTs(n,r,i,a,o){const s=await t.listAllNFTs(n,r,i,a,o);return dx(s,Ve,ex,e)},async listNFTs(n,r,i,a,o,s){const u=await t.listNFTs(n,r,i,a,o,s);return dx(u,Ve,ex,e)},async listNFTsByAccountAddress(n,r,i,a,o,s){const u=await t.listNFTsByAccountAddress(n,r,i,a,o,s);return dx(u,Ve,ex,e)}}};const _x=function(e){return{cancelOrders:async(t,n,r={})=>{ix("cancelOrders","chainName",t),ix("cancelOrders","cancelOrdersRequestBody",n);const i="/v1/chains/{chain_name}/orders/cancel".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,rx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",ux(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=cx(n,s,e),{url:lx(a),options:s}},createListing:async(t,n,r={})=>{ix("createListing","chainName",t),ix("createListing","createListingRequestBody",n);const i="/v1/chains/{chain_name}/orders/listings".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,rx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",ux(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=cx(n,s,e),{url:lx(a),options:s}},fulfillmentData:async(t,n,r={})=>{ix("fulfillmentData","chainName",t),ix("fulfillmentData","fulfillmentDataRequest",n);const i="/v1/chains/{chain_name}/orders/fulfillment-data".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,rx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",ux(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=cx(n,s,e),{url:lx(a),options:s}},getListing:async(t,n,r={})=>{ix("getListing","chainName",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};ux(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:lx(a),options:s}},getTrade:async(t,n,r={})=>{ix("getTrade","chainName",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};ux(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:lx(a),options:s}},listListings:async(t,n,r,i,a,o,s,u,c,l={})=>{ix("listListings","chainName",t);const d="/v1/chains/{chain_name}/orders/listings".replace("{chain_name}",encodeURIComponent(String(t))),f=new URL(d,rx);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),ux(f,m);let y=p&&p.headers?p.headers:{};return h.headers={...y,...l.headers},{url:lx(f),options:h}},listTrades:async(t,n,r,i,a,o,s={})=>{ix("listTrades","chainName",t);const u="/v1/chains/{chain_name}/trades".replace("{chain_name}",encodeURIComponent(String(t))),c=new URL(u,rx);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),ux(c,f);let p=l&&l.headers?l.headers:{};return d.headers={...p,...s.headers},{url:lx(c),options:d}}}},Ix=function(e){const t=_x(e);return{async cancelOrders(n,r,i){const a=await t.cancelOrders(n,r,i);return dx(a,Ve,ex,e)},async createListing(n,r,i){const a=await t.createListing(n,r,i);return dx(a,Ve,ex,e)},async fulfillmentData(n,r,i){const a=await t.fulfillmentData(n,r,i);return dx(a,Ve,ex,e)},async getListing(n,r,i){const a=await t.getListing(n,r,i);return dx(a,Ve,ex,e)},async getTrade(n,r,i){const a=await t.getTrade(n,r,i);return dx(a,Ve,ex,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 dx(f,Ve,ex,e)},async listTrades(n,r,i,a,o,s,u){const c=await t.listTrades(n,r,i,a,o,s,u);return dx(c,Ve,ex,e)}}};const Rx=function(e){return{createCounterfactualAddress:async(t,n,r={})=>{ix("createCounterfactualAddress","chainName",t),ix("createCounterfactualAddress","createCounterfactualAddressRequest",n);const i="/v1/chains/{chain_name}/passport/counterfactual-address".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,rx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};await ox(u,e),u["Content-Type"]="application/json",ux(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=cx(n,s,e),{url:lx(a),options:s}},createCounterfactualAddressDeprecated:async(t,n={})=>{ix("createCounterfactualAddressDeprecated","createCounterfactualAddressRequestDeprecated",t);const r=new URL("/passport-mr/v1/counterfactual-address",rx);let i;e&&(i=e.baseOptions);const a={method:"POST",...i,...n},o={};await ox(o,e),o["Content-Type"]="application/json",ux(r,{});let s=i&&i.headers?i.headers:{};return a.headers={...o,...s,...n.headers},a.data=cx(t,a,e),{url:lx(r),options:a}},getLinkedAddresses:async(t,n,r={})=>{ix("getLinkedAddresses","userId",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r},u={};await ox(u,e),ux(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},{url:lx(a),options:s}},getLinkedAddressesDeprecated:async(t,n={})=>{ix("getLinkedAddressesDeprecated","userId",t);const r="/passport-mr/v1/users/{userId}/linked-addresses".replace("{userId}",encodeURIComponent(String(t))),i=new URL(r,rx);let a;e&&(a=e.baseOptions);const o={method:"GET",...a,...n},s={};await ox(s,e),ux(i,{});let u=a&&a.headers?a.headers:{};return o.headers={...s,...u,...n.headers},{url:lx(i),options:o}}}},Cx=function(e){const t=Rx(e);return{async createCounterfactualAddress(n,r,i){const a=await t.createCounterfactualAddress(n,r,i);return dx(a,Ve,ex,e)},async createCounterfactualAddressDeprecated(n,r){const i=await t.createCounterfactualAddressDeprecated(n,r);return dx(i,Ve,ex,e)},async getLinkedAddresses(n,r,i){const a=await t.getLinkedAddresses(n,r,i);return dx(a,Ve,ex,e)},async getLinkedAddressesDeprecated(n,r){const i=await t.getLinkedAddressesDeprecated(n,r);return dx(i,Ve,ex,e)}}};const kx=function(e){return{getERC20Token:async(t,n,r={})=>{ix("getERC20Token","contractAddress",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};ux(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:lx(a),options:s}},listERC20Tokens:async(t,n,r,i,a={})=>{ix("listERC20Tokens","chainName",t);const o="/v1/chains/{chain_name}/tokens".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,rx);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),ux(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:lx(s),options:c}}}},Ox=function(e){const t=kx(e);return{async getERC20Token(n,r,i){const a=await t.getERC20Token(n,r,i);return dx(a,Ve,ex,e)},async listERC20Tokens(n,r,i,a,o){const s=await t.listERC20Tokens(n,r,i,a,o);return dx(s,Ve,ex,e)}}};var Sx=Object.freeze({__proto__:null,ActiveOrderStatusNameEnum:{Active:"ACTIVE"},ActivitiesApi:class extends tx{getActivity(e,t){return px(this.configuration).getActivity(e.chainName,e.activityId,t).then((e=>e(this.axios,this.basePath)))}listActivities(e,t){return px(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:fx,ActivitiesApiFactory:function(e,t,n){const r=px(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:px,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 tx{listChains(e={},t){return mx(this.configuration).listChains(e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},ChainsApiAxiosParamCreator:hx,ChainsApiFactory:function(e,t,n){const r=mx(e);return{listChains:(e={},i)=>r.listChains(e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},ChainsApiFp:mx,CollectionContractType:{Erc721:"ERC721"},CollectionsApi:class extends tx{getCollection(e,t){return gx(this.configuration).getCollection(e.contractAddress,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listCollections(e,t){return gx(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 gx(this.configuration).listCollectionsByNFTOwner(e.accountAddress,e.chainName,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}refreshCollectionMetadata(e,t){return gx(this.configuration).refreshCollectionMetadata(e.contractAddress,e.chainName,e.refreshCollectionMetadataRequest,t).then((e=>e(this.axios,this.basePath)))}},CollectionsApiAxiosParamCreator:yx,CollectionsApiFactory:function(e,t,n){const r=gx(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:gx,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 tx{getMetadata(e,t){return vx(this.configuration).getMetadata(e.chainName,e.contractAddress,e.metadataId,t).then((e=>e(this.axios,this.basePath)))}listMetadata(e,t){return vx(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 vx(this.configuration).refreshMetadataByID(e.chainName,e.contractAddress,e.refreshMetadataByIDRequest,t).then((e=>e(this.axios,this.basePath)))}refreshNFTMetadataByTokenID(e,t){return vx(this.configuration).refreshNFTMetadataByTokenID(e.contractAddress,e.chainName,e.refreshNFTMetadataByTokenIDRequest,t).then((e=>e(this.axios,this.basePath)))}},MetadataApiAxiosParamCreator:bx,MetadataApiFactory:function(e,t,n){const r=vx(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:vx,NFTContractType:{Erc721:"ERC721"},NativeItemItemTypeEnum:{Native:"NATIVE"},NftOwnersApi:class extends tx{listNFTOwners(e,t){return Tx(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 Tx(this.configuration).listOwnersByContractAddress(e.contractAddress,e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},NftOwnersApiAxiosParamCreator:wx,NftOwnersApiFactory:function(e,t,n){const r=Tx(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:Tx,NftsApi:class extends tx{getNFT(e,t){return Ex(this.configuration).getNFT(e.contractAddress,e.tokenId,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listAllNFTOwners(e,t){return Ex(this.configuration).listAllNFTOwners(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listAllNFTs(e,t){return Ex(this.configuration).listAllNFTs(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listNFTs(e,t){return Ex(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 Ex(this.configuration).listNFTsByAccountAddress(e.accountAddress,e.chainName,e.contractAddress,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},NftsApiAxiosParamCreator:Ax,NftsApiFactory:function(e,t,n){const r=Ex(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:Ex,OrderStatusName:{Pending:"PENDING",Active:"ACTIVE",Inactive:"INACTIVE",Filled:"FILLED",Expired:"EXPIRED",Cancelled:"CANCELLED"},OrdersApi:class extends tx{cancelOrders(e,t){return Ix(this.configuration).cancelOrders(e.chainName,e.cancelOrdersRequestBody,t).then((e=>e(this.axios,this.basePath)))}createListing(e,t){return Ix(this.configuration).createListing(e.chainName,e.createListingRequestBody,t).then((e=>e(this.axios,this.basePath)))}fulfillmentData(e,t){return Ix(this.configuration).fulfillmentData(e.chainName,e.fulfillmentDataRequest,t).then((e=>e(this.axios,this.basePath)))}getListing(e,t){return Ix(this.configuration).getListing(e.chainName,e.listingId,t).then((e=>e(this.axios,this.basePath)))}getTrade(e,t){return Ix(this.configuration).getTrade(e.chainName,e.tradeId,t).then((e=>e(this.axios,this.basePath)))}listListings(e,t){return Ix(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 Ix(this.configuration).listTrades(e.chainName,e.accountAddress,e.pageSize,e.sortBy,e.sortDirection,e.pageCursor,t).then((e=>e(this.axios,this.basePath)))}},OrdersApiAxiosParamCreator:_x,OrdersApiFactory:function(e,t,n){const r=Ix(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:Ix,PassportApi:class extends tx{createCounterfactualAddress(e,t){return Cx(this.configuration).createCounterfactualAddress(e.chainName,e.createCounterfactualAddressRequest,t).then((e=>e(this.axios,this.basePath)))}createCounterfactualAddressDeprecated(e,t){return Cx(this.configuration).createCounterfactualAddressDeprecated(e.createCounterfactualAddressRequestDeprecated,t).then((e=>e(this.axios,this.basePath)))}getLinkedAddresses(e,t){return Cx(this.configuration).getLinkedAddresses(e.userId,e.chainName,t).then((e=>e(this.axios,this.basePath)))}getLinkedAddressesDeprecated(e,t){return Cx(this.configuration).getLinkedAddressesDeprecated(e.userId,t).then((e=>e(this.axios,this.basePath)))}},PassportApiAxiosParamCreator:Rx,PassportApiFactory:function(e,t,n){const r=Cx(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:Cx,PendingOrderStatusNameEnum:{Pending:"PENDING"},ProtocolDataOrderTypeEnum:{FullRestricted:"FULL_RESTRICTED"},SaleFeeTypeEnum:{Royalty:"ROYALTY"},TokenContractType:{Erc20:"ERC20"},TokensApi:class extends tx{getERC20Token(e,t){return Ox(this.configuration).getERC20Token(e.contractAddress,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listERC20Tokens(e,t){return Ox(this.configuration).listERC20Tokens(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},TokensApiAxiosParamCreator:kx,TokensApiFactory:function(e,t,n){const r=Ox(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:Ox});class Nx 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 xx={sdkVersion:"ts-immutable-sdk-multi-rollup-api-client-0.30.0"},Mx=({baseConfig:e,basePath:t,headers:n})=>{if(!t.trim())throw Error("basePath can not be empty");const r={...e,basePath:t,baseOptions:{headers:{...n||{},...xx}}};return new Sx.Configuration(r)};class Px{apiConfig;baseConfig;constructor({baseConfig:e,overrides:t}){if(this.baseConfig=e,t)this.apiConfig=Mx(t);else switch(e.environment){case st.SANDBOX:this.apiConfig=Mx({basePath:"https://api.sandbox.immutable.com",baseConfig:e});break;case st.PRODUCTION:this.apiConfig=Mx({basePath:"https://indexer-mr.imtbl.com",baseConfig:e});break;default:this.apiConfig=Mx({basePath:"https://api.sandbox.immutable.com",baseConfig:e})}}}function Bx(e){if(Ve.isAxiosError(e)&&e.response){const t=e.response.data;return t.code&&t.message?new Nx({code:t.code,message:t.message,details:t.details||null,link:t.link||"",trace_id:t.trace_id||""}):new Nx({code:e.code??e.response?.status.toString()??"unknown_error_code",message:String(e),details:null,link:"",trace_id:""})}return new Nx({code:"unknown_error_code",message:String(e),details:null,link:"",trace_id:""})}class Dx{config;activities;chains;collections;nfts;nftOwners;tokens;metadata;constructor(e){this.config=new Px(e),this.activities=new Sx.ActivitiesApi(this.config.apiConfig),this.chains=new Sx.ChainsApi(this.config.apiConfig),this.collections=new Sx.CollectionsApi(this.config.apiConfig),this.nfts=new Sx.NftsApi(this.config.apiConfig),this.nftOwners=new Sx.NftOwnersApi(this.config.apiConfig),this.tokens=new Sx.TokensApi(this.config.apiConfig),this.metadata=new Sx.MetadataApi(this.config.apiConfig)}async listActivities(e){return await this.activities.listActivities(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async getActivity(e){return await this.activities.getActivity(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listChains(e){return await this.chains.listChains(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listCollections(e){return await this.collections.listCollections(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listCollectionsByNFTOwner(e){return await this.collections.listCollectionsByNFTOwner(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async getCollection(e){return await this.collections.getCollection(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async getNFT(e){return await this.nfts.getNFT(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listNFTs(e){return await this.nfts.listNFTs(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listNFTsByAccountAddress(e){return await this.nfts.listNFTsByAccountAddress(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listAllNFTs(e){return await this.nfts.listAllNFTs(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listNFTOwners(e){return await this.nftOwners.listNFTOwners(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listNFTOwnersByContractAddress(e){return await this.nftOwners.listOwnersByContractAddress(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listAllNFTOwners(e){return await this.nfts.listAllNFTOwners(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listTokens(e){return await this.tokens.listERC20Tokens(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async getToken(e){return await this.tokens.getERC20Token(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async getMetadata(e){return await this.metadata.getMetadata(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listNFTMetadataByContractAddress(e){return await this.metadata.listMetadata(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async refreshCollectionMetadata(e){return await this.collections.refreshCollectionMetadata(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async refreshNFTMetadata(e){return await this.metadata.refreshNFTMetadataByTokenID(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async refreshStackedMetadata(e){return await this.metadata.refreshMetadataByID(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}}async function Fx(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 Lx(e,t){const n=await t.remote.getConfig("dex");return new LR({chainId:e,baseConfig:new ut({environment:t.environment}),overrides:n?.overrides})}function Ux(e){return new ZN({baseConfig:{environment:e.environment}})}function qx(e){return new Dx({baseConfig:{environment:e.environment}})}const jx="0x0000000000000000000000000000000000000001",Gx=18;async function Hx(t,n,r,i){const a=bm(n),o=vm(n),s=await n.remote.getConfig("gasEstimateTokens"),{gasTokenAddress:u,fromAddress:c}=s[a].bridgeToL2Addresses,l=t.get(a);if(!l)throw new Error(`Missing JsonRpcProvider for chain id: ${a}`);try{const s=await async function(e,t){const n=await Dm(e);return n&&t?{estimatedAmount:n.add(n)}:{estimatedAmount:n}}(l,r);s.token=await async function(e,t,n,r){if("NATIVE"===t)return e.networkMap.get(n)?.nativeCurrency;const i=new vl(t,JSON.stringify(tm),r);return{name:await i.name(),symbol:await i.symbol(),decimals:await i.decimals(),address:t}}(n,i??(u||"NATIVE"),a,l);const d=await Fx(a,o,t,n),{bridgeFee:f,bridgeable:p}=await async function(e,t){const n=await e.getFee({token:t});return{bridgeFee:{estimatedAmount:n.feeAmount},bridgeable:n.bridgeable}}(d,c);return{gasEstimateType:e.GasEstimateType.BRIDGE_TO_L2,gasFee:s,bridgeFee:{estimatedAmount:f?.estimatedAmount,token:f?.token},bridgeable:p}}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 Hx(n,r,t.isSpendingCapApprovalRequired,t.tokenAddress);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 Lx(n,t),{swap:o}=await r.getUnsignedSwapTxFromAmountIn(jx,i,a,tr.from(kh("1",Gx)));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??Gx}}}}catch{return{gasEstimateType:e.GasEstimateType.SWAP,gasFee:{}}}}(r);default:throw new lm("Invalid type provided for gasEstimateType",e.CheckoutErrorType.INVALID_GAS_ESTIMATE_TYPE)}}const Vx=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))),Wx=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})}},Kx=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})}},Xx=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})}},Jx=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})}},Yx=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})}},Qx=(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},Zx=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,Xx(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=Qx(i,r);o.set(d,n),s.set(d,Yx(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=Qx(p,l);u.set(m,{type:e.ItemType.ERC721,sufficient:!1,itemRequirement:s,approvalTransaction:void 0}),c.set(m,Jx(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()))}},$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,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))),eM=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)}},tM=async(t,n,r,i)=>{const a=$x(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(eM(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}},nM=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)}},rM=async(t,n,r)=>{const i=[];let a=tr.from(0);for(const e of n)void 0!==e.approvalTransaction&&i.push(nM(t,e.approvalTransaction));if(r.type===e.TransactionOrGasType.TRANSACTION)i.push(nM(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)},iM=(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)}}),aM=async()=>!0,oM=async e=>{const t=iM(e.isDevelopment,e.isProduction);try{return await t.checkDexAvailability()}catch{return!1}};async function sM(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 uM=async(e,t,n,r,i)=>{const a=new Map;try{const o=await Lx(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}},cM=(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}},lM=(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}},dM=(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}},fM=(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},pM=(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)},hM=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 uM(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=dM(f,t.approval);if(!i.sufficient)continue;if(!fM(f,i,t.swap,t.quote.fees,{amount:r.value,address:e}))continue;if(!pM(n.balance,s,e,r.value,i,t.quote.fees))continue;const a=cM(t.approval,t.swap,t.quote.fees);u.push(lM(l,r.value,n,a))}return u},mM=(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))))):[],yM=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{}},gM=async(e,t,n)=>{if(n.bridge){const n=(await e.remote.getConfig("bridge"))?.tokens??[],r=t.get(bm(e));return mM(n,r)}return[]},bM=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 mM(n,r)}return[]})(e,t,n),r.bridge=await gM(e,t,n),r.onRamp=await yM(e,n),r},vM="0x0000000000000000000000000000000000000001",wM=async(e,t)=>(await t.remote.getConfig("imxAddressMapping"))[e]??"",TM=async(t,n)=>{if(""===n)return{l1address:"",l2address:n};if(n===Vh)return{l1address:await wM(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=qx(t),o=(await a.getToken({chainName:r,contractAddress:n})).result.root_contract_address;return null===o?{l1address:"",l2address:n}:{l1address:o,l2address:n}},AM=async(t,n,r,i,a,o)=>{if(a===vM)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 Fx(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)},EM=(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),_M=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)},IM=(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}]}},RM=(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}),CM=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 gM(t,o,i);if(0===d.length)return;const f=await _M(t,n,s);if(!EM(c,f.totalFees))return;const p=await TM(t,a.l2address),{l1address:h}=p;if(""===h)return;if(h===vM){if(!d.find((e=>!("address"in e))))return}else if(!d.find((e=>e.address===h)))return;const m=await AM(t,n,l,r,h,a.amount);let y=f.bridgeFee.estimatedAmount;if(h===vM){const t=c.balances.find((e=>{return!(t=e.token.address)||""===t;var t}));if(f.gasFee.estimatedAmount&&(y=y.add(f.gasFee.estimatedAmount)),!EM(c,y))return;if(t&&t.balance.gte(a.amount.add(y))){const n=IM(m,f.gasFee,f.bridgeFee);return RM(u,t,a,e.ItemType.NATIVE,n)}return}if(y.add(m).add(f.gasFee.estimatedAmount),!EM(c,y))return;const g=c.balances.find((e=>e.token.address===h));if(g&&g.balance.gte(a.amount)){const t=IM(m,f.gasFee,f.bridgeFee);return RM(u,g,a,e.ItemType.ERC20,t)}},kM=(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},OM=(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)},SM=(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)},NM=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=>TM(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 uM(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===vM||e.token.address===c));if(!d)continue;const f=s.quote.amountWithMaxSlippage.value,p=kM(s,o),h=f.add(p),m=OM(i,o),y=SM(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,CM(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 hM(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===vM&&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)},xM=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 yM(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},MM=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 sM(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",bM(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 CM(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 hM(e,t,r,n,i,c,o)})(t,i,c,n,o,s.swap,r)),l.push(xM(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?vM:e.address)),p=s?.swap??[];return i.type!==e.ItemType.NATIVE&&i.type!==e.ItemType.ERC20?[]:await NM(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},PM=async(t,n,r,i)=>{const a=await n.getSigner().getAddress();let o=Vx(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,Wx(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,Kx(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=Zx(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",rM(n,l,i));null!==d&&(o.push(d),o=Vx(o));const f=await Im(t,"Time to run balance checks",tM(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:aM()}),n.swap&&r.push({id:"swap",promise:oM(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",MM(t,a,f,m))}}};var BM;!function(e){e.SUCCESS="SUCCESS",e.FAILED="FAILED"}(BM||(BM={}));const DM=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:BM.FAILED,transactionHash:e.transactionHash,reason:"Approval transaction failed and was reverted"};return{type:BM.SUCCESS}},FM=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:BM.FAILED,transactionHash:e.transactionHash,reason:"Fulfillment transaction failed and was reverted"};return{type:BM.SUCCESS}},LM=async e=>{let t=[];const n=[];for(const t of e)t.type===FN.TRANSACTION&&t.purpose===BN.FULFILL_ORDER&&n.push(t.buildTransaction());return t=await Promise.all(n),t},UM=(e,t)=>{const n=e.amount,r=Math.round(n.percentageDecimal*10**6);return t.mul(tr.from(r)).div(10**6)},qM=(e,t)=>kh(e.amount.token,t),jM=(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=UM(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=qM(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},GM=(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}}},HM=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=$N,u=Ux(t),c=qx(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=jM(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===FN.TRANSACTION&&t.purpose===BN.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(xN.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",LM(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 _=[GM(T,A,w,a)],I=await Im(t,"Total time running smart checkout",PM(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 DM(n,y);if(t.type===BM.FAILED)return{status:e.CheckoutStatus.FAILED,transactionHash:t.transactionHash,reason:t.reason,smartCheckoutResult:I};try{0===g.length&&(g=await LM(b))}catch(t){throw new lm("Error fetching fulfillment transaction",e.CheckoutErrorType.FULFILL_ORDER_LISTING_ERROR,{message:t.message})}const r=await FM(n,g);return r.type===BM.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}},zM=(t,n,r)=>({type:e.ItemType.ERC721,id:t,contractAddress:n,spenderAddress:r}),VM=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=Ux(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=[zM(u.id,u.collectionAddress,o)],p=await Im(t,"Total time running smart checkout",PM(t,n,f,{type:e.TransactionOrGasType.GAS,gasToken:{type:e.GasTokenType.NATIVE,limit:tr.from($N)}}));if(p.sufficient){const t=await(async e=>{let t=[],n=[];const r=[],i=[];for(const t of e)t.type===FN.TRANSACTION&&(t.purpose===BN.APPROVAL&&r.push(t.buildTransaction()),t.purpose===BN.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 DM(n,t.approvalTransactions);if(r.type===BM.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===FN.SIGNABLE&&e.purpose===DN.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=jM(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 WM{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 KM(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 XM=()=>"0.30.0";function JM(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=XM();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 YM={baseConfig:{environment:st.SANDBOX},passport:void 0};e.CHECKOUT_API_BASE_URL=Jh,e.Checkout=class{readOnlyProviders;config;fiatRampService;availability;passport;constructor(e=YM){this.config=new wm(e),this.fiatRampService=new WM(this.config),this.readOnlyProviders=new Map,this.availability=iM(this.config.isDevelopment,this.config.isProduction),this.passport=e.passport}async widgets(t){const n=this,r=new Promise(((r,i)=>{try{JM(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 Pm(this.config,t.provider,{allowUnsupportedProvider:!0}))}async connect(t){const n=await Pm(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 Pm(this.config,e.provider,{allowUnsupportedProvider:!0,allowMistmatchedChainId:!0});return await mm(this.config,t,e.chainId)}async getBalance(e){const t=await Pm(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 Pm(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 Pm(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 Pm(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 Pm(this.config,e.provider);return await HM(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 Pm(this.config,e.provider);return await VM(this.config,t,e.orders)}async cancel(t){console.warn("This endpoint currently only processes the first order in the array.");const n=await Pm(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=Ux(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 FM(n,[i]);return o.type===BM.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 Pm(this.config,t.provider);let r=[];try{r=await KM(n,t.itemRequirements)}catch{throw new lm("Failed to map item requirements",e.CheckoutErrorType.ITEM_REQUIREMENTS_ERROR)}return await PM(this.config,n,r,t.transactionOrGasAmount)}static isWeb3Provider(e){return Mm(e)}async gasEstimate(e){return this.readOnlyProviders=await sM(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,M=c.words,P=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,M[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,P[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)}(Zk)),tO(),nO||(nO=1,function(e,t){var n;e.exports=(n=gk(),qk(),tO(),function(){var e=n,t=e.lib,r=t.Base,i=t.WordArray,a=e.algo,o=a.SHA1,s=a.HMAC,u=a.PBKDF2=r.extend({cfg:r.extend({keySize:4,hasher:o,iterations:1}),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)}(rO)),oO(),cO(),fO(),mO(),bO(),TO(),AO||(AO=1,function(e,t){var n,r;e.exports=(r=gk(),cO(),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)}(EO)),_O||(_O=1,function(e,t){var n;e.exports=(n=gk(),cO(),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)}(IO)),RO||(RO=1,function(e,t){var n;e.exports=(n=gk(),cO(),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)}(CO)),kO||(kO=1,function(e,t){var n;e.exports=(n=gk(),cO(),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)}(OO)),SO||(SO=1,function(e,t){var n;e.exports=(n=gk(),cO(),n.pad.ZeroPadding={pad:function(e,t){var n=4*t;e.clamp(),e.sigBytes+=n-(e.sigBytes%n||n)},unpad:function(e){for(var t=e.words,n=e.sigBytes-1;!(t[n>>>2]>>>24-n%4*8&255);)n--;e.sigBytes=n+1}},n.pad.ZeroPadding)}(NO)),xO||(xO=1,function(e,t){var n;e.exports=(n=gk(),cO(),n.pad.NoPadding={pad:function(){},unpad:function(){}},n.pad.NoPadding)}(MO)),PO||(PO=1,function(e,t){var n,r,i,a;e.exports=(a=gk(),cO(),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)}(BO)),DO||(DO=1,function(e,t){var n;e.exports=(n=gk(),Pk(),Fk(),oO(),cO(),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++)if(o<n)a[o]=t[o];else{var s=a[o-1];o%n?n>6&&o%n==4&&(s=i[s>>>24]<<24|i[s>>>16&255]<<16|i[s>>>8&255]<<8|i[255&s]):(s=i[(s=s<<8|s>>>24)>>>24]<<24|i[s>>>16&255]<<16|i[s>>>8&255]<<8|i[255&s],s^=h[o/n|0]<<24),a[o]=a[o-n]^s}for(var u=this._invKeySchedule=[],c=0;c<r;c++)o=r-c,s=c%4?a[o]:a[o-4],u[c]=c<4||o<=4?s:l[i[s>>>24]]^d[i[s>>>16&255]]^f[i[s>>>8&255]]^p[i[255&s]]}},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)}(FO)),LO||(LO=1,function(e,t){var n;e.exports=(n=gk(),Pk(),Fk(),oO(),cO(),function(){var e=n,t=e.lib,r=t.WordArray,i=t.BlockCipher,a=e.algo,o=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],s=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],u=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],c=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],l=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],d=a.DES=i.extend({_doReset:function(){for(var e=this._key.words,t=[],n=0;n<56;n++){var r=o[n]-1;t[n]=e[r>>>5]>>>31-r%32&1}for(var i=this._subKeys=[],a=0;a<16;a++){var c=i[a]=[],l=u[a];for(n=0;n<24;n++)c[n/6|0]|=t[(s[n]-1+l)%28]<<31-n%6,c[4+(n/6|0)]|=t[28+(s[n+24]-1+l)%28]<<31-n%6;for(c[0]=c[0]<<1|c[0]>>>31,n=1;n<7;n++)c[n]=c[n]>>>4*(n-1)+3;c[7]=c[7]<<5|c[7]>>>27}var d=this._invSubKeys=[];for(n=0;n<16;n++)d[n]=i[15-n]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._subKeys)},decryptBlock:function(e,t){this._doCryptBlock(e,t,this._invSubKeys)},_doCryptBlock:function(e,t,n){this._lBlock=e[t],this._rBlock=e[t+1],f.call(this,4,252645135),f.call(this,16,65535),p.call(this,2,858993459),p.call(this,8,16711935),f.call(this,1,1431655765);for(var r=0;r<16;r++){for(var i=n[r],a=this._lBlock,o=this._rBlock,s=0,u=0;u<8;u++)s|=c[u][((o^i[u])&l[u])>>>0];this._lBlock=o,this._rBlock=a^s}var d=this._lBlock;this._lBlock=this._rBlock,this._rBlock=d,f.call(this,1,1431655765),p.call(this,8,16711935),p.call(this,2,858993459),f.call(this,16,65535),f.call(this,4,252645135),e[t]=this._lBlock,e[t+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function f(e,t){var n=(this._lBlock>>>e^this._rBlock)&t;this._rBlock^=n,this._lBlock^=n<<e}function p(e,t){var n=(this._rBlock>>>e^this._lBlock)&t;this._lBlock^=n,this._rBlock^=n<<e}e.DES=i._createHelper(d);var h=a.TripleDES=i.extend({_doReset:function(){var e=this._key.words;this._des1=d.createEncryptor(r.create(e.slice(0,2))),this._des2=d.createEncryptor(r.create(e.slice(2,4))),this._des3=d.createEncryptor(r.create(e.slice(4,6)))},encryptBlock:function(e,t){this._des1.encryptBlock(e,t),this._des2.decryptBlock(e,t),this._des3.encryptBlock(e,t)},decryptBlock:function(e,t){this._des3.decryptBlock(e,t),this._des2.encryptBlock(e,t),this._des1.decryptBlock(e,t)},keySize:6,ivSize:2,blockSize:2});e.TripleDES=i._createHelper(h)}(),n.TripleDES)}(UO)),qO||(qO=1,function(e,t){var n;e.exports=(n=gk(),Pk(),Fk(),oO(),cO(),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)}(jO)),GO||(GO=1,function(e,t){var n;e.exports=(n=gk(),Pk(),Fk(),oO(),cO(),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)}(HO)),zO||(zO=1,function(e,t){var n;e.exports=(n=gk(),Pk(),Fk(),oO(),cO(),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)}(VO)),n)}(Ek);var WO=Ek.exports,KO=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ak,"__esModule",{value:!0}),Ak.Base=void 0;const XO=hn,JO=KO(WO);class YO{print(){YO.print(this)}bufferIndexOf(e,t,n=!1){if(n)return this.binarySearch(e,t,XO.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 YO.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 YO.linearSearch(e,t,n)}static bufferify(e){if(!XO.Buffer.isBuffer(e)){if("object"==typeof e&&e.words)return XO.Buffer.from(e.toString(JO.default.enc.Hex),"hex");if(YO.isHexString(e))return XO.Buffer.from(e.replace(/^0x/,""),"hex");if("string"==typeof e)return XO.Buffer.from(e);if("bigint"==typeof e)return XO.Buffer.from(e.toString(16),"hex");if(e instanceof Uint8Array)return XO.Buffer.from(e.buffer);if("number"==typeof e){let t=e.toString();return t.length%2&&(t=`0${t}`),XO.Buffer.from(t,"hex")}if(ArrayBuffer.isView(e))return XO.Buffer.from(e.buffer,e.byteOffset,e.byteLength)}return e}bigNumberify(e){return YO.bigNumberify(e)}static bigNumberify(e){if("bigint"==typeof e)return e;if("string"==typeof e)return e.startsWith("0x")&&YO.isHexString(e)?BigInt("0x"+e.replace("0x","").toString()):BigInt(e);if(XO.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 YO.bufferToHex(e,t)}static bufferToHex(e,t=!0){return`${t?"0x":""}${(e||XO.Buffer.alloc(0)).toString("hex")}`}bufferify(e){return YO.bufferify(e)}bufferifyFn(e){return t=>{const n=e(t);return XO.Buffer.isBuffer(n)?n:this.isHexString(n)?XO.Buffer.from(n.replace("0x",""),"hex"):"string"==typeof n?XO.Buffer.from(n):"bigint"==typeof n?XO.Buffer.from(t.toString(16),"hex"):ArrayBuffer.isView(n)?XO.Buffer.from(n.buffer,n.byteOffset,n.byteLength):XO.Buffer.from(e(JO.default.enc.Hex.parse(t.toString("hex"))).toString(JO.default.enc.Hex),"hex")}}isHexString(e){return YO.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")}}Ak.Base=YO,Ak.default=YO;var QO=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(hk,"__esModule",{value:!0}),hk.MerkleTree=void 0;const ZO=hn,$O=QO((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})),eS=QO(bk),tS=QO(Tk),nS=QO(Ak);let rS=class e extends nS.default{constructor(e,t=eS.default,n={}){if(super(),this.duplicateOdd=!1,this.concatenator=ZO.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(!ZO.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(ZO.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([$O.default(n),$O.default(n)])),i=$O.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?[$O.default(i),$O.default(a)]:[i,a],this.sortPairs&&o.sort(ZO.Buffer.compare);let s=this.hashFn(this.concatenator(o));this.isBitcoinTree&&(s=$O.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(ZO.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?ZO.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(ZO.Buffer.from([0])),e}getHexLayersFlat(){return this.getLayersFlat().map((e=>this.bufferToHex(e)))}getLayerCount(){return this.getLayers().length}getRoot(){return 0===this.layers.length?ZO.Buffer.from([]):this.layers[this.layers.length-1][0]||ZO.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===ZO.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:ZO.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=eS.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(ZO.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(ZO.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($O.default(r)),o[a?"unshift":"push"]($O.default(i)),r=this.hashFn(this.concatenator(o)),r=$O.default(this.hashFn(r))):this.sortPairs?-1===ZO.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===ZO.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(ZO.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(ZO.Buffer.compare);o[e]=this.hashFn(this.concatenator(a))}return 0===ZO.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=eS.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 tS.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]}};hk.MerkleTree=rS,"undefined"!=typeof window&&(window.MerkleTree=rS),hk.default=rS;var iS={},aS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(iS,"__esModule",{value:!0}),iS.MerkleMountainRange=void 0;const oS=hn,sS=aS(bk),uS=aS(Ak);class cS extends uS.default{constructor(e=sS.default,t=[],n,r,i){super(),this.root=oS.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(oS.Buffer.concat([this.bufferify(e),t]))}hashBranch(e,t,n){return this.hashBranchFn?this.bufferify(this.hashBranchFn(e,t,n)):this.hashFn(oS.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(oS.Buffer.concat([this.bufferify(n),...t.map(this.bufferify)])):oS.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]}}iS.MerkleMountainRange=cS,"undefined"!=typeof window&&(window.MerkleMountainRange=cS),iS.default=cS;var lS={},dS=ct&&ct.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(lS,"__esModule",{value:!0}),lS.IncrementalMerkleTree=void 0;const fS=dS(Ak),pS=dS(Tk);class hS extends fS.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 pS.default.asTree(e,!0)}}lS.IncrementalMerkleTree=hS,"undefined"!=typeof window&&(window.IncrementalMerkleTree=hS),lS.default=hS;var mS={};Object.defineProperty(mS,"__esModule",{value:!0}),mS.MerkleSumTree=mS.ProofStep=mS.Leaf=mS.Bucket=void 0;const yS=Ak;class gS{constructor(e,t){this.size=BigInt(e),this.hashed=t,this.parent=null,this.left=null,this.right=null}}mS.Bucket=gS;mS.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 gS(BigInt(this.rng[1])-BigInt(this.rng[0]),e)}};class bS{constructor(e,t){this.bucket=e,this.right=t}}mS.ProofStep=bS;class vS extends yS.Base{constructor(e,t){super(),this.leaves=e,this.hashFn=t,vS.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 gS(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 bS(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 gS(BigInt(a.size)+BigInt(e.bucket.size),i);return a.size===e.size&&a.hashed.toString("hex")===e.hashed.toString("hex")}}mS.MerkleSumTree=vS,"undefined"!=typeof window&&(window.MerkleSumTree=vS),mS.default=vS,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(hk);e.MerkleTree=n.default;var r=iS;Object.defineProperty(e,"MerkleMountainRange",{enumerable:!0,get:function(){return r.MerkleMountainRange}});var i=lS;Object.defineProperty(e,"IncrementalMerkleTree",{enumerable:!0,get:function(){return i.IncrementalMerkleTree}});var a=mS;Object.defineProperty(e,"MerkleSumTree",{enumerable:!0,get:function(){return a.MerkleSumTree}}),e.default=n.default}(pk);var wS={};Object.defineProperty(wS,"__esModule",{value:!0}),wS.DefaultGetter=void 0;const TS=pC,AS=new AC.Logger("defaults"),ES={integer:0,address:(0,TS.hexZeroPad)("0x",20),bool:!1,bytes:"0x",string:""},_S=e=>void 0!==e&&(null!=e&&(["string","number"].includes(typeof e)&&BigInt(e)===BigInt(0)||Array.isArray(e)&&e.every(_S)||"object"==typeof e&&Object.values(e).every(_S)||"boolean"==typeof e&&!1===e));class IS{constructor(e){this.types=e,this.defaultValues={};for(const t in e){const e=this.getDefaultValue(t);this.defaultValues[t]=e,_S(e)||AS.throwError(`Got non-empty value for type ${t} in default generator: ${e}`)}}static from(e,t){const{defaultValues:n}=new IS(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,TS.hexZeroPad)("0x",parseInt(n)):(e.match(/^(u?)int(\d*)$/)&&(e="integer"),ES[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)})),{}):AS.throwArgumentError(`unknown type: ${e}`,"type",e)}}wS.DefaultGetter=IS;var RS={};!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)}(RS),Object.defineProperty(fk,"__esModule",{value:!0}),fk.Eip712MerkleTree=void 0;const CS=bC,kS=pC,OS=pk,SS=wS,NS=RS;fk.Eip712MerkleTree=class{get completedSize(){return Math.pow(2,this.depth)}getCompleteElements(){const e=this.elements;return(0,NS.fillArray)([...e],this.completedSize,this.defaultNode)}getCompleteLeaves(){const e=this.elements.map(this.leafHasher);return(0,NS.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,kS.hexConcat)([n,`0x${e.toString(16).padStart(6,"0")}`,kS.defaultAbiCoder.encode([`uint256[${t.length}]`],[t])]))(e,n,t)}getDataToSign(){let e=this.getCompleteElements();for(;e.length>2;)e=(0,NS.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(NS.hexToBuffer),n=(0,NS.bufferToHex)((0,NS.getRoot)(t,!1)),r=(0,kS.keccak256)((0,kS.toUtf8Bytes)(this.encoder._types.BulkOrder));if((0,kS.keccak256)((0,kS.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=CS._TypedDataEncoder.from(e);var o,s;this.encoder=a,this.leafHasher=e=>a.hashStruct(n,e),this.defaultNode=SS.DefaultGetter.from(e,n),this.defaultLeaf=this.leafHasher(this.defaultNode),this.tree=(o=this.getCompleteLeaves(),s=this.defaultLeaf,new OS.MerkleTree(o.map(NS.hexToBuffer),NS.bufferKeccak,{complete:!0,sort:!1,hashLeaves:!1,fillDefaultHash:(0,NS.hexToBuffer)(s)}))}},Object.defineProperty(dk,"__esModule",{value:!0}),dk.getBulkOrderTypeHashes=dk.getBulkOrderTypeHash=dk.getBulkOrderTree=dk.getBulkOrderTreeHeight=void 0;const xS=pC,MS=fk,PS=wS,BS=RS,DS=BC;function FS(e){const t=Object.assign({},DS.EIP_712_BULK_ORDER_TYPE);return t.BulkOrder=[{name:"tree",type:`OrderComponents${"[2]".repeat(e)}`}],t}function LS(e){return Math.max(Math.ceil(Math.log2(e)),1)}function US(e){const t=FS(e),n=xS._TypedDataEncoder.from(t),r=(0,xS.toUtf8Bytes)(n._types.BulkOrder);return(0,xS.keccak256)(r)}dk.getBulkOrderTreeHeight=LS,dk.getBulkOrderTree=function(e,t=0,n=LS(e.length+t)){const r=FS(n),i=PS.DefaultGetter.from(r,"OrderComponents");let a=[...e];return t>0&&(a=[...(0,BS.fillArray)([],t,i),...e]),new MS.Eip712MerkleTree(r,"BulkOrder","OrderComponents",a,n)},dk.getBulkOrderTypeHash=US,dk.getBulkOrderTypeHashes=function(e){const t=[];for(let n=0;n<e;n++)t.push(US(n+1));return t};var qS={},jS={},GS={};Object.defineProperty(GS,"__esModule",{value:!0}),GS.MerkleTree=void 0;const HS=fC,zS=pC,VS=pk,WS=e=>(0,zS.keccak256)(Buffer.from(HS.BigNumber.from(e).toHexString().slice(2).padStart(64,"0"),"hex"));GS.MerkleTree=class{constructor(e){this.tree=new VS.default(e.map(WS),zS.keccak256,{sort:!0})}getProof(e){return this.tree.getHexProof(WS(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 KS=fC,XS=pC,JS=BC,YS=VC(),QS=GS,ZS=(e,t)=>KS.BigNumber.from(e).mul(KS.BigNumber.from(t)).div(JS.ONE_HUNDRED_PERCENT_BP);jS.feeToConsiderationItem=({fee:e,token:t,baseAmount:n,baseEndAmount:r=n})=>({itemType:t===KS.ethers.constants.AddressZero?JS.ItemType.NATIVE:JS.ItemType.ERC20,token:t,identifierOrCriteria:"0",startAmount:ZS(n,e.basisPoints).toString(),endAmount:ZS(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,YS.isCurrencyItem)(e)?KS.BigNumber.from(e.startAmount).sub(ZS(e.startAmount,n)).toString():e.startAmount,endAmount:(0,YS.isCurrencyItem)(e)?KS.BigNumber.from(e.endAmount).sub(ZS(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 QS.MerkleTree(e.identifiers).getRoot();return{itemType:e.itemType===JS.ItemType.ERC721?JS.ItemType.ERC721_WITH_CRITERIA:JS.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!==KS.ethers.constants.AddressZero?JS.ItemType.ERC20:JS.ItemType.NATIVE,token:null!==(s=e.token)&&void 0!==s?s:KS.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(YS.isCurrencyItem);return n.every((({itemType:e,token:t})=>e===n[0].itemType&&t.toLowerCase()===n[0].token.toLowerCase()))};jS.totalItemsAmount=e=>(KS.BigNumber.from(0),KS.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:KS.BigNumber.from(0),endAmount:KS.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(JS.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:ZS(e.startAmount,r).toString(),endAmount:ZS(e.endAmount,r).toString()}))),consideration:e.parameters.consideration.map((e=>Object.assign(Object.assign({},e),{startAmount:ZS(e.startAmount,r).toString(),endAmount:ZS(e.endAmount,r).toString()})))}),signature:e.signature}};const $S=(e,t,n)=>KS.BigNumber.from(e).mul(KS.BigNumber.from(t)).div(n);jS.mapOrderAmountsFromUnitsToFill=(e,{unitsToFill:t,totalSize:n})=>{const r=KS.BigNumber.from(t);if(r.lte(0))throw new Error("Units to fill must be greater than 1");const i=(0,YS.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:$S(e.startAmount,r,n).toString(),endAmount:$S(e.endAmount,r,n).toString()}))),consideration:e.parameters.consideration.map((e=>Object.assign(Object.assign({},e),{startAmount:$S(e.startAmount,r,n).toString(),endAmount:$S(e.endAmount,r,n).toString()})))}),signature:e.signature}};jS.generateRandomSalt=e=>e?`0x${Buffer.from((0,XS.concat)([(0,XS.keccak256)((0,XS.toUtf8Bytes)(e)).slice(0,10),Uint8Array.from(Array(20).fill(0)),(0,XS.randomBytes)(8)])).toString("hex")}`:`0x${Buffer.from((0,XS.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},M={value:S},P=[...(0,r.getApprovalActions)(N,b,h),{type:"exchange",transactionMethods:(0,c.getTransactionMethods)(a.connect(h),"fulfillBasicOrder",[x,M],g)}];return{actions:P,executeAllActions:()=>(0,c.executeAllActions)(P)}},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))),M=N.filter((({itemType:e})=>(0,s.isCriteriaItem)(e))),P=x.length>0||M.length>0;if(x.length!==f.length||M.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)||P||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"}),P?(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)}}}(qS);var eN=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 tN=dC,nN=fC,rN=pC,iN=MC,aN=PC,oN=BC,sN=DC,uN=ek,cN=dk,lN=qS,dN=VC(),fN=jS,pN=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=oN.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=nN.ethers.utils.keccak256(nN.ethers.utils.toUtf8Bytes(t)),a=nN.ethers.utils.keccak256(nN.ethers.utils.toUtf8Bytes(n)),o=nN.ethers.utils.keccak256(nN.ethers.utils.toUtf8Bytes(r)),s=nN.ethers.utils.keccak256("0x"+e.offer.map((e=>nN.ethers.utils.keccak256("0x"+[i.slice(2),e.itemType.toString().padStart(64,"0"),e.token.slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.identifierOrCriteria).toHexString().slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.startAmount).toHexString().slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.endAmount).toHexString().slice(2).padStart(64,"0")].join("")).slice(2))).join("")),u=nN.ethers.utils.keccak256("0x"+e.consideration.map((e=>nN.ethers.utils.keccak256("0x"+[a.slice(2),e.itemType.toString().padStart(64,"0"),e.token.slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.identifierOrCriteria).toHexString().slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.startAmount).toHexString().slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.endAmount).toHexString().slice(2).padStart(64,"0"),e.recipient.slice(2).padStart(64,"0")].join("")).slice(2))).join(""));return nN.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"),nN.ethers.BigNumber.from(e.startTime).toHexString().slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.endTime).toHexString().slice(2).padStart(64,"0"),e.zoneHash.slice(2),nN.BigNumber.from(e.salt).toHexString().slice(2).padStart(64,"0"),e.conduitKey.slice(2).padStart(64,"0"),nN.ethers.BigNumber.from(e.counter).toHexString().slice(2).padStart(64,"0")].join(""))};const c=e instanceof nN.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 tN.providers.MulticallProvider(this.provider),this.contract=new nN.Contract(null!==(o=null==t?void 0:t.contractAddress)&&void 0!==o?o:"1.5"===a?oN.CROSS_CHAIN_SEAPORT_V1_5_ADDRESS:oN.CROSS_CHAIN_SEAPORT_V1_4_ADDRESS,aN.SeaportABIv14,this.multicallProvider),this.domainRegistry=new nN.Contract(null!==(s=null==t?void 0:t.domainRegistryAddress)&&void 0!==s?s:oN.DOMAIN_REGISTRY_ADDRESS,iN.DomainRegistryABI,this.multicallProvider),this.config={ascendingAmountFulfillmentBuffer:n,balanceAndApprovalChecksOnOrderCreation:r,conduitKeyToConduit:Object.assign(Object.assign(Object.assign({},oN.KNOWN_CONDUIT_KEYS_TO_CONDUIT),{[oN.NO_CONDUIT]:this.contract.address}),i),seaportVersion:a},this.defaultConduitKey=null!==(u=null==t?void 0:t.defaultConduitKey)&&void 0!==u?u:oN.NO_CONDUIT}createOrder(e,t,n){return eN(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:()=>eN(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,pN.executeAllActions)(u)}}))}createBulkOrders(e,t,n){var r;return eN(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:()=>eN(this,void 0,void 0,(function*(){return yield this.signBulkOrder(u,a)}))},l=[...s,c];return{actions:l,executeAllActions:()=>(0,pN.executeAllActions)(l)}}))}_formatOrder(e,t,n,{conduitKey:r=this.defaultConduitKey,zone:i=nN.ethers.constants.AddressZero,zoneHash:a=nN.ethers.constants.HashZero,startTime:o=Math.floor(Date.now()/1e3).toString(),endTime:s=oN.MAX_INT.toString(),offer:u,consideration:c,counter:l,allowPartialFills:d,restrictedByZone:f,fees:p,domain:h,salt:m}){var y;return eN(this,void 0,void 0,(function*(){const g=u.map(fN.mapInputItemToOfferItem),b=[...c.map((e=>{var n;return Object.assign(Object.assign({},(0,fN.mapInputItemToOfferItem)(e)),{recipient:null!==(n=e.recipient)&&void 0!==n?n:t})}))];if((null==p?void 0:p.length)&&!(0,fN.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(dN.isCurrencyItem),w=(0,fN.totalItemsAmount)(v),T=this.config.conduitKeyToConduit[r],A=this._getOrderTypeFromOrderOptions({allowPartialFills:d,restrictedByZone:f}),E=[...(0,fN.deductFees)(b,p),...v.length&&null!==(y=null==p?void 0:p.map((e=>(0,fN.feeToConsiderationItem)({fee:e,token:v[0].token,baseAmount:w.startAmount,baseEndAmount:w.endAmount}))))&&void 0!==y?y:[]],_=void 0!==m?`0x${nN.BigNumber.from(m).toHexString().slice(2).padStart(64,"0")}`:(0,fN.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,uN.getBalancesAndApprovals)({owner:t,items:g,criterias:[],multicallProvider:this.multicallProvider,operator:T}),i=(0,uN.validateOfferBalancesAndApprovals)({offer:g,criterias:[],balancesAndApprovals:r,throwOnInsufficientBalances:!0,operator:T}),a=(0,sN.getApprovalActions)(i,n,e);R.push(...a)}return{orderComponents:I,approvalActions:R}}))}_getSigner(e){if(this.signer)return this.signer;if(!(this.provider instanceof nN.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?oN.OrderType.PARTIAL_RESTRICTED:oN.OrderType.PARTIAL_OPEN:t?oN.OrderType.FULL_RESTRICTED:oN.OrderType.FULL_OPEN}_getDomainData(){return eN(this,void 0,void 0,(function*(){const{chainId:e}=yield this.provider.getNetwork();return{name:oN.SEAPORT_CONTRACT_NAME,version:"1.5"===this.config.seaportVersion?oN.SEAPORT_CONTRACT_VERSION_V1_5:oN.SEAPORT_CONTRACT_VERSION_V1_4,chainId:e,verifyingContract:this.contract.address}}))}_getMessageToSign(e){return eN(this,void 0,void 0,(function*(){const t=yield this._getDomainData();return JSON.stringify(rN._TypedDataEncoder.getPayload(t,oN.EIP_712_ORDER_TYPE,e))}))}_getBulkMessageToSign(e){return eN(this,void 0,void 0,(function*(){const t=yield this._getDomainData(),n=(0,cN.getBulkOrderTree)(e),r=n.types,i=n.getDataToSign();return JSON.stringify(rN._TypedDataEncoder.getPayload(t,r,{tree:i}))}))}signOrder(e,t){return eN(this,void 0,void 0,(function*(){const n=this._getSigner(t),r=yield this._getDomainData();let i=yield n._signTypedData(r,oN.EIP_712_ORDER_TYPE,e);return 132===i.length&&(i=nN.ethers.utils.splitSignature(i).compact),i}))}signBulkOrder(e,t){return eN(this,void 0,void 0,(function*(){const n=this._getSigner(t),r=yield this._getDomainData(),i=(0,cN.getBulkOrderTree)(e),a=i.types,o={tree:i.getDataToSign()};let s=yield n._signTypedData(r,a,o);132===s.length&&(s=nN.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,pN.getTransactionMethods)(this.contract.connect(r),"cancel",[e],n)}bulkCancelOrders(e,t){const n=this._getSigner(e);return(0,pN.getTransactionMethods)(this.contract.connect(n),"incrementCounter",[],t)}validate(e,t,n){const r=this._getSigner(t);return(0,pN.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=nN.ethers.constants.AddressZero,domain:c,exactApproval:l=!1}){return eN(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,uN.getBalancesAndApprovals)({owner:f,items:p,criterias:n,multicallProvider:this.multicallProvider,operator:g}),(0,uN.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,lN.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,fN.mapInputItemToOfferItem)(e)),{recipient:e.recipient}))),O=u===nN.ethers.constants.AddressZero;return!t&&O&&(0,lN.shouldUseBasicFulfill)(R.parameters,_)?(0,lN.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,lN.fulfillStandardOrder)({order:R,unitsToFill:t,totalFilled:_,totalSize:I.eq(0)?(0,dN.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=nN.ethers.constants.AddressZero,domain:i,exactApproval:a=!1}){return eN(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,uN.getBalancesAndApprovals)({owner:e.parameters.offerer,items:e.parameters.offer,criterias:t,operator:u[n],multicallProvider:this.multicallProvider})))),(0,uN.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,fN.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,lN.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,pN.getTransactionMethods)(this.contract.connect(a),"matchOrders",[e,t,n],i)}setDomain(e,t){const n=this._getSigner(t);return(0,pN.getTransactionMethods)(this.domainRegistry.connect(n),"setDomain",[e])}getNumberOfDomains(e){return eN(this,void 0,void 0,(function*(){return this.domainRegistry.getNumberOfDomains(e)}))}getDomain(e,t){return this.domainRegistry.getDomain(e,t)}getDomains(e,t){return eN(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 hN{config;constructor(e){this.config=e}}class mN 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 yN extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}}class gN{[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 yN("Request aborted"))}}get isCancelled(){return this._isCancelled}}const bN=e=>null!=e,vN=e=>"string"==typeof e,wN=e=>vN(e)&&""!==e,TN=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]),AN=e=>{const t=[],n=(e,r)=>{bN(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("&")}`:""},EN=async(e,t)=>"function"==typeof t?t(e):t,_N=async(e,t,n)=>{const r=await EN(t,e.TOKEN),i=await EN(t,e.USERNAME),a=await EN(t,e.PASSWORD),o=await EN(t,e.HEADERS),s="function"==typeof n?.getHeaders&&n?.getHeaders()||{},u=Object.entries({Accept:"application/json",...o,...t.headers,...s}).filter((([e,t])=>bN(t))).reduce(((e,[t,n])=>({...e,[t]:String(n)})),{});if(wN(r)&&(u.Authorization=`Bearer ${r}`),wN(i)&&wN(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:TN(t.body)?u["Content-Type"]=t.body.type||"application/octet-stream":vN(t.body)?u["Content-Type"]="text/plain":t.body instanceof UR||(u["Content-Type"]="application/json")),u},IN=(e,t)=>new gN((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}${AN(t.query)}`:i})(e,t),o=(e=>{if(e.formData){const t=new UR,n=(e,n)=>{vN(n)||TN(n)?t.append(e,n):t.append(e,JSON.stringify(n))};return Object.entries(e.formData).filter((([e,t])=>bN(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 _N(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(vN(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 mN(e,t,n);if(!t.ok)throw new mN(e,t,"Generic Error")})(t,f),n(f.body)}}catch(e){r(e)}var a}));class RN extends hN{constructor(e){super(e)}request(e){return IN(this.config,e)}}class CN{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 kN{orders;request;constructor(e,t=RN){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 CN(this.request)}}var ON,SN,NN,xN,MN,PN,BN,DN,FN;function LN(e){const t=e.buy.map((e=>{if("ERC20"===e.item_type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.start_amount};if("NATIVE"===e.item_type)return{type:"NATIVE",amount:e.start_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 UN(e){const t=e.buy.map((e=>{if("ERC20"===e.item_type)return{type:"ERC20",contractAddress:e.contract_address,amount:e.start_amount};if("NATIVE"===e.item_type)return{type:"NATIVE",amount:e.start_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 qN(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"}(ON||(ON={})),function(e){(e.reason_code||(e.reason_code={})).FILLED="FILLED"}(SN||(SN={})),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"}(NN||(NN={})),function(e){e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.FILLED="FILLED",e.EXPIRED="EXPIRED",e.CANCELLED="CANCELLED"}(xN||(xN={})),function(e){(e.order_type||(e.order_type={})).FULL_RESTRICTED="FULL_RESTRICTED"}(MN||(MN={})),function(e){e.MAKER_ECOSYSTEM="MAKER_ECOSYSTEM",e.TAKER_ECOSYSTEM="TAKER_ECOSYSTEM",e.PROTOCOL="PROTOCOL",e.ROYALTY="ROYALTY"}(PN||(PN={})),function(e){e.APPROVAL="APPROVAL",e.FULFILL_ORDER="FULFILL_ORDER",e.CANCEL="CANCEL"}(BN||(BN={})),function(e){e.CREATE_LISTING="CREATE_LISTING",e.OFF_CHAIN_CANCELLATION="OFF_CHAIN_CANCELLATION"}(DN||(DN={})),function(e){e.TRANSACTION="TRANSACTION",e.SIGNABLE="SIGNABLE"}(FN||(FN={}));const jN="1.5",GN={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 HN,zN,VN,WN;function KN(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"}(HN||(HN={})),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"}(VN||(VN={})),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"}(WN||(WN={}));class XN{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:FN.TRANSACTION,purpose:BN.APPROVAL,buildTransaction:KN(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:FN.SIGNABLE,purpose:DN.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:FN.TRANSACTION,buildTransaction:KN(u.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:BN.APPROVAL});const c=o.find((e=>"exchange"===e.type));if(!c)throw new Error("No exchange action found");return s.push({type:FN.TRANSACTION,buildTransaction:KN(c.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:BN.FULFILL_ORDER}),{actions:s,expiration:XN.getExpirationISOTimeFromExtraData(n),order:LN(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:FN.TRANSACTION,buildTransaction:KN(a.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:BN.APPROVAL});const o=r.find((e=>"exchange"===e.type));if(!o)throw new Error("No exchange action found");return i.push({type:FN.TRANSACTION,buildTransaction:KN(o.transactionMethods,(await this.provider.getNetwork()).chainId),purpose:BN.FULFILL_ORDER}),{actions:i,expiration:n.map((e=>XN.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:FN.TRANSACTION,buildTransaction:KN(i,(await this.provider.getNetwork()).chainId),purpose:BN.CANCEL}}mapImmutableOrderToSeaportOrderComponents(e){return function(e,t,n){const r=e.buy.map((t=>{switch(t.item_type){case"NATIVE":return{startAmount:t.start_amount,endAmount:t.start_amount,itemType:zN.NATIVE,recipient:e.account_address,token:ji,identifierOrCriteria:"0"};case"ERC20":return{startAmount:t.start_amount,endAmount:t.start_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:HN.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:GN,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 JN{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",start_amount:t.consideration[0].startAmount,contract_address:t.consideration[0].token}],fees:r.map((e=>({amount:e.amount,fee_type:PN.MAKER_ECOSYSTEM,recipient:e.recipient}))),end_at:new Date(parseInt(`${t.endTime.toString()}000`,10)).toISOString(),protocol_data:{order_type:MN.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 YN{chainName;seaportAddress;orderbookClient;constructor(e,t,n){this.chainName=t,this.seaportAddress=n,this.orderbookClient=new kN({BASE:e})}create(){return new JN(this.orderbookClient.orders,this.chainName,this.seaportAddress)}}class QN{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 ZN{apiClient;seaport;orderbookConfig;constructor(e){const t={...function(e){switch(e){case st.SANDBOX:return{seaportContractAddress:"0x7Fb7Da6De152597830eD16361633e362A2F59410",zoneContractAddress:"0x63441cBfBd15Dd8f5E92598E535661Ac5aCB808E",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 YN(n,r,this.orderbookConfig.seaportContractAddress).create();const i=new QN(this.orderbookConfig.seaportContractAddress,this.orderbookConfig.provider);this.seaport=new XN(i,this.orderbookConfig.provider,this.orderbookConfig.seaportContractAddress,this.orderbookConfig.zoneContractAddress)}config(){return this.orderbookConfig}async getListing(e){return{result:LN((await this.apiClient.getListing(e)).result)}}async getTrade(e){return{result:UN((await this.apiClient.getTrade(e)).result)}}async listListings(e){const t=await this.apiClient.listListings(e);return{page:qN(t.page),result:t.result.map(LN)}}async listTrades(e){const t=await this.apiClient.listTrades(e);return{page:qN(t.page),result:t.result.map(UN)}}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:LN((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:PN.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!==xN.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:PN.TAKER_ECOSYSTEM,recipient:e.recipient})))}))));try{return{...await this.seaport.fulfillBulkOrders(n.result.fulfillable_orders,t),fulfillableOrders:n.result.fulfillable_orders.map((e=>LN(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=>LN(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:DN.OFF_CHAIN_CANCELLATION,type:FN.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!==xN.ACTIVE&&e.result.status.name!==xN.INACTIVE&&e.result.status.name!==xN.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 $N=4e5,ex="https://api.sandbox.immutable.com".replace(/\/+$/,"");class tx{basePath;axios;configuration;constructor(e,t=ex,n=Ve){this.basePath=t,this.axios=n,e&&(this.configuration=e,this.basePath=e.basePath||this.basePath)}}class nx extends Error{field;constructor(e,t){super(t),this.field=e,this.name="RequiredError"}}const rx="https://example.com",ix=function(e,t,n){if(null==n)throw new nx(t,`Required parameter ${t} was null or undefined when calling ${e}.`)},ax=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}},ox=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 sx(e,t,n=""){null!=t&&("object"==typeof t?Array.isArray(t)?t.forEach((t=>sx(e,t,n))):Object.keys(t).forEach((r=>sx(e,t[r],`${n}${""!==n?".":""}${r}`))):e.has(n)?e.append(n,t):e.set(n,t))}const ux=function(e,...t){const n=new URLSearchParams(e.search);sx(n,t),e.search=n.toString()},cx=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||""},lx=function(e){return e.pathname+e.search+e.hash},dx=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)}},fx=function(e){return{getActivity:async(t,n,r={})=>{ix("getActivity","chainName",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};ux(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:lx(a),options:s}},listActivities:async(t,n,r,i,a,o,s,u,c,l,d={})=>{ix("listActivities","chainName",t);const f="/v1/chains/{chain_name}/activities".replace("{chain_name}",encodeURIComponent(String(t))),p=new URL(f,rx);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),ux(p,y);let g=h&&h.headers?h.headers:{};return m.headers={...g,...d.headers},{url:lx(p),options:m}}}},px=function(e){const t=fx(e);return{async getActivity(n,r,i){const a=await t.getActivity(n,r,i);return dx(a,Ve,ex,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 dx(p,Ve,ex,e)}}};const hx=function(e){return{listChains:async(t,n,r={})=>{const i=new URL("/v1/chains",rx);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),ux(i,s);let u=a&&a.headers?a.headers:{};return o.headers={...u,...r.headers},{url:lx(i),options:o}}}},mx=function(e){const t=hx(e);return{async listChains(n,r,i){const a=await t.listChains(n,r,i);return dx(a,Ve,ex,e)}}};const yx=function(e){return{getCollection:async(t,n,r={})=>{ix("getCollection","contractAddress",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};ux(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:lx(a),options:s}},listCollections:async(t,n,r,i,a,o={})=>{ix("listCollections","chainName",t);const s="/v1/chains/{chain_name}/collections".replace("{chain_name}",encodeURIComponent(String(t))),u=new URL(s,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}},listCollectionsByNFTOwner:async(t,n,r,i,a={})=>{ix("listCollectionsByNFTOwner","accountAddress",t),ix("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,rx);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),ux(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:lx(s),options:c}},refreshCollectionMetadata:async(t,n,r,i={})=>{ix("refreshCollectionMetadata","contractAddress",t),ix("refreshCollectionMetadata","chainName",n),ix("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,rx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await ax(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",ux(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=cx(r,u,e),{url:lx(o),options:u}}}},gx=function(e){const t=yx(e);return{async getCollection(n,r,i){const a=await t.getCollection(n,r,i);return dx(a,Ve,ex,e)},async listCollections(n,r,i,a,o,s){const u=await t.listCollections(n,r,i,a,o,s);return dx(u,Ve,ex,e)},async listCollectionsByNFTOwner(n,r,i,a,o){const s=await t.listCollectionsByNFTOwner(n,r,i,a,o);return dx(s,Ve,ex,e)},async refreshCollectionMetadata(n,r,i,a){const o=await t.refreshCollectionMetadata(n,r,i,a);return dx(o,Ve,ex,e)}}};const bx=function(e){return{getMetadata:async(t,n,r,i={})=>{ix("getMetadata","chainName",t),ix("getMetadata","contractAddress",n),ix("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,rx);let s;e&&(s=e.baseOptions);const u={method:"GET",...s,...i};ux(o,{});let c=s&&s.headers?s.headers:{};return u.headers={...c,...i.headers},{url:lx(o),options:u}},listMetadata:async(t,n,r,i,a,o={})=>{ix("listMetadata","chainName",t),ix("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,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}},refreshMetadataByID:async(t,n,r,i={})=>{ix("refreshMetadataByID","chainName",t),ix("refreshMetadataByID","contractAddress",n),ix("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,rx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await ax(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",ux(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=cx(r,u,e),{url:lx(o),options:u}},refreshNFTMetadataByTokenID:async(t,n,r,i={})=>{ix("refreshNFTMetadataByTokenID","contractAddress",t),ix("refreshNFTMetadataByTokenID","chainName",n),ix("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,rx);let s;e&&(s=e.baseOptions);const u={method:"POST",...s,...i},c={};await ax(c,"x-immutable-api-key",e),c["Content-Type"]="application/json",ux(o,{});let l=s&&s.headers?s.headers:{};return u.headers={...c,...l,...i.headers},u.data=cx(r,u,e),{url:lx(o),options:u}}}},vx=function(e){const t=bx(e);return{async getMetadata(n,r,i,a){const o=await t.getMetadata(n,r,i,a);return dx(o,Ve,ex,e)},async listMetadata(n,r,i,a,o,s){const u=await t.listMetadata(n,r,i,a,o,s);return dx(u,Ve,ex,e)},async refreshMetadataByID(n,r,i,a){const o=await t.refreshMetadataByID(n,r,i,a);return dx(o,Ve,ex,e)},async refreshNFTMetadataByTokenID(n,r,i,a){const o=await t.refreshNFTMetadataByTokenID(n,r,i,a);return dx(o,Ve,ex,e)}}};const wx=function(e){return{listNFTOwners:async(t,n,r,i,a,o={})=>{ix("listNFTOwners","contractAddress",t),ix("listNFTOwners","tokenId",n),ix("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,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}},listOwnersByContractAddress:async(t,n,r,i,a,o={})=>{ix("listOwnersByContractAddress","contractAddress",t),ix("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,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}}}},Tx=function(e){const t=wx(e);return{async listNFTOwners(n,r,i,a,o,s){const u=await t.listNFTOwners(n,r,i,a,o,s);return dx(u,Ve,ex,e)},async listOwnersByContractAddress(n,r,i,a,o,s){const u=await t.listOwnersByContractAddress(n,r,i,a,o,s);return dx(u,Ve,ex,e)}}};const Ax=function(e){return{getNFT:async(t,n,r,i={})=>{ix("getNFT","contractAddress",t),ix("getNFT","tokenId",n),ix("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,rx);let s;e&&(s=e.baseOptions);const u={method:"GET",...s,...i};ux(o,{});let c=s&&s.headers?s.headers:{};return u.headers={...c,...i.headers},{url:lx(o),options:u}},listAllNFTOwners:async(t,n,r,i,a={})=>{ix("listAllNFTOwners","chainName",t),ix("listAllNFTOwners","fromUpdatedAt",n);const o="/v1/chains/{chain_name}/nft-owners".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,rx);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),ux(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:lx(s),options:c}},listAllNFTs:async(t,n,r,i,a={})=>{ix("listAllNFTs","chainName",t);const o="/v1/chains/{chain_name}/nfts".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,rx);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),ux(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:lx(s),options:c}},listNFTs:async(t,n,r,i,a,o={})=>{ix("listNFTs","contractAddress",t),ix("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,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}},listNFTsByAccountAddress:async(t,n,r,i,a,o={})=>{ix("listNFTsByAccountAddress","accountAddress",t),ix("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,rx);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),ux(u,d);let f=c&&c.headers?c.headers:{};return l.headers={...f,...o.headers},{url:lx(u),options:l}}}},Ex=function(e){const t=Ax(e);return{async getNFT(n,r,i,a){const o=await t.getNFT(n,r,i,a);return dx(o,Ve,ex,e)},async listAllNFTOwners(n,r,i,a,o){const s=await t.listAllNFTOwners(n,r,i,a,o);return dx(s,Ve,ex,e)},async listAllNFTs(n,r,i,a,o){const s=await t.listAllNFTs(n,r,i,a,o);return dx(s,Ve,ex,e)},async listNFTs(n,r,i,a,o,s){const u=await t.listNFTs(n,r,i,a,o,s);return dx(u,Ve,ex,e)},async listNFTsByAccountAddress(n,r,i,a,o,s){const u=await t.listNFTsByAccountAddress(n,r,i,a,o,s);return dx(u,Ve,ex,e)}}};const _x=function(e){return{cancelOrders:async(t,n,r={})=>{ix("cancelOrders","chainName",t),ix("cancelOrders","cancelOrdersRequestBody",n);const i="/v1/chains/{chain_name}/orders/cancel".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,rx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",ux(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=cx(n,s,e),{url:lx(a),options:s}},createListing:async(t,n,r={})=>{ix("createListing","chainName",t),ix("createListing","createListingRequestBody",n);const i="/v1/chains/{chain_name}/orders/listings".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,rx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",ux(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=cx(n,s,e),{url:lx(a),options:s}},fulfillmentData:async(t,n,r={})=>{ix("fulfillmentData","chainName",t),ix("fulfillmentData","fulfillmentDataRequest",n);const i="/v1/chains/{chain_name}/orders/fulfillment-data".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,rx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};u["Content-Type"]="application/json",ux(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=cx(n,s,e),{url:lx(a),options:s}},getListing:async(t,n,r={})=>{ix("getListing","chainName",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};ux(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:lx(a),options:s}},getTrade:async(t,n,r={})=>{ix("getTrade","chainName",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};ux(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:lx(a),options:s}},listListings:async(t,n,r,i,a,o,s,u,c,l={})=>{ix("listListings","chainName",t);const d="/v1/chains/{chain_name}/orders/listings".replace("{chain_name}",encodeURIComponent(String(t))),f=new URL(d,rx);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),ux(f,m);let y=p&&p.headers?p.headers:{};return h.headers={...y,...l.headers},{url:lx(f),options:h}},listTrades:async(t,n,r,i,a,o,s={})=>{ix("listTrades","chainName",t);const u="/v1/chains/{chain_name}/trades".replace("{chain_name}",encodeURIComponent(String(t))),c=new URL(u,rx);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),ux(c,f);let p=l&&l.headers?l.headers:{};return d.headers={...p,...s.headers},{url:lx(c),options:d}}}},Ix=function(e){const t=_x(e);return{async cancelOrders(n,r,i){const a=await t.cancelOrders(n,r,i);return dx(a,Ve,ex,e)},async createListing(n,r,i){const a=await t.createListing(n,r,i);return dx(a,Ve,ex,e)},async fulfillmentData(n,r,i){const a=await t.fulfillmentData(n,r,i);return dx(a,Ve,ex,e)},async getListing(n,r,i){const a=await t.getListing(n,r,i);return dx(a,Ve,ex,e)},async getTrade(n,r,i){const a=await t.getTrade(n,r,i);return dx(a,Ve,ex,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 dx(f,Ve,ex,e)},async listTrades(n,r,i,a,o,s,u){const c=await t.listTrades(n,r,i,a,o,s,u);return dx(c,Ve,ex,e)}}};const Rx=function(e){return{createCounterfactualAddress:async(t,n,r={})=>{ix("createCounterfactualAddress","chainName",t),ix("createCounterfactualAddress","createCounterfactualAddressRequest",n);const i="/v1/chains/{chain_name}/passport/counterfactual-address".replace("{chain_name}",encodeURIComponent(String(t))),a=new URL(i,rx);let o;e&&(o=e.baseOptions);const s={method:"POST",...o,...r},u={};await ox(u,e),u["Content-Type"]="application/json",ux(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},s.data=cx(n,s,e),{url:lx(a),options:s}},createCounterfactualAddressDeprecated:async(t,n={})=>{ix("createCounterfactualAddressDeprecated","createCounterfactualAddressRequestDeprecated",t);const r=new URL("/passport-mr/v1/counterfactual-address",rx);let i;e&&(i=e.baseOptions);const a={method:"POST",...i,...n},o={};await ox(o,e),o["Content-Type"]="application/json",ux(r,{});let s=i&&i.headers?i.headers:{};return a.headers={...o,...s,...n.headers},a.data=cx(t,a,e),{url:lx(r),options:a}},getLinkedAddresses:async(t,n,r={})=>{ix("getLinkedAddresses","userId",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r},u={};await ox(u,e),ux(a,{});let c=o&&o.headers?o.headers:{};return s.headers={...u,...c,...r.headers},{url:lx(a),options:s}},getLinkedAddressesDeprecated:async(t,n={})=>{ix("getLinkedAddressesDeprecated","userId",t);const r="/passport-mr/v1/users/{userId}/linked-addresses".replace("{userId}",encodeURIComponent(String(t))),i=new URL(r,rx);let a;e&&(a=e.baseOptions);const o={method:"GET",...a,...n},s={};await ox(s,e),ux(i,{});let u=a&&a.headers?a.headers:{};return o.headers={...s,...u,...n.headers},{url:lx(i),options:o}}}},Cx=function(e){const t=Rx(e);return{async createCounterfactualAddress(n,r,i){const a=await t.createCounterfactualAddress(n,r,i);return dx(a,Ve,ex,e)},async createCounterfactualAddressDeprecated(n,r){const i=await t.createCounterfactualAddressDeprecated(n,r);return dx(i,Ve,ex,e)},async getLinkedAddresses(n,r,i){const a=await t.getLinkedAddresses(n,r,i);return dx(a,Ve,ex,e)},async getLinkedAddressesDeprecated(n,r){const i=await t.getLinkedAddressesDeprecated(n,r);return dx(i,Ve,ex,e)}}};const kx=function(e){return{getERC20Token:async(t,n,r={})=>{ix("getERC20Token","contractAddress",t),ix("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,rx);let o;e&&(o=e.baseOptions);const s={method:"GET",...o,...r};ux(a,{});let u=o&&o.headers?o.headers:{};return s.headers={...u,...r.headers},{url:lx(a),options:s}},listERC20Tokens:async(t,n,r,i,a={})=>{ix("listERC20Tokens","chainName",t);const o="/v1/chains/{chain_name}/tokens".replace("{chain_name}",encodeURIComponent(String(t))),s=new URL(o,rx);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),ux(s,l);let d=u&&u.headers?u.headers:{};return c.headers={...d,...a.headers},{url:lx(s),options:c}}}},Ox=function(e){const t=kx(e);return{async getERC20Token(n,r,i){const a=await t.getERC20Token(n,r,i);return dx(a,Ve,ex,e)},async listERC20Tokens(n,r,i,a,o){const s=await t.listERC20Tokens(n,r,i,a,o);return dx(s,Ve,ex,e)}}};var Sx=Object.freeze({__proto__:null,ActiveOrderStatusNameEnum:{Active:"ACTIVE"},ActivitiesApi:class extends tx{getActivity(e,t){return px(this.configuration).getActivity(e.chainName,e.activityId,t).then((e=>e(this.axios,this.basePath)))}listActivities(e,t){return px(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:fx,ActivitiesApiFactory:function(e,t,n){const r=px(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:px,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 tx{listChains(e={},t){return mx(this.configuration).listChains(e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},ChainsApiAxiosParamCreator:hx,ChainsApiFactory:function(e,t,n){const r=mx(e);return{listChains:(e={},i)=>r.listChains(e.pageCursor,e.pageSize,i).then((e=>e(n,t)))}},ChainsApiFp:mx,CollectionContractType:{Erc721:"ERC721"},CollectionsApi:class extends tx{getCollection(e,t){return gx(this.configuration).getCollection(e.contractAddress,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listCollections(e,t){return gx(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 gx(this.configuration).listCollectionsByNFTOwner(e.accountAddress,e.chainName,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}refreshCollectionMetadata(e,t){return gx(this.configuration).refreshCollectionMetadata(e.contractAddress,e.chainName,e.refreshCollectionMetadataRequest,t).then((e=>e(this.axios,this.basePath)))}},CollectionsApiAxiosParamCreator:yx,CollectionsApiFactory:function(e,t,n){const r=gx(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:gx,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 tx{getMetadata(e,t){return vx(this.configuration).getMetadata(e.chainName,e.contractAddress,e.metadataId,t).then((e=>e(this.axios,this.basePath)))}listMetadata(e,t){return vx(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 vx(this.configuration).refreshMetadataByID(e.chainName,e.contractAddress,e.refreshMetadataByIDRequest,t).then((e=>e(this.axios,this.basePath)))}refreshNFTMetadataByTokenID(e,t){return vx(this.configuration).refreshNFTMetadataByTokenID(e.contractAddress,e.chainName,e.refreshNFTMetadataByTokenIDRequest,t).then((e=>e(this.axios,this.basePath)))}},MetadataApiAxiosParamCreator:bx,MetadataApiFactory:function(e,t,n){const r=vx(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:vx,NFTContractType:{Erc721:"ERC721"},NativeItemItemTypeEnum:{Native:"NATIVE"},NftOwnersApi:class extends tx{listNFTOwners(e,t){return Tx(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 Tx(this.configuration).listOwnersByContractAddress(e.contractAddress,e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},NftOwnersApiAxiosParamCreator:wx,NftOwnersApiFactory:function(e,t,n){const r=Tx(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:Tx,NftsApi:class extends tx{getNFT(e,t){return Ex(this.configuration).getNFT(e.contractAddress,e.tokenId,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listAllNFTOwners(e,t){return Ex(this.configuration).listAllNFTOwners(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listAllNFTs(e,t){return Ex(this.configuration).listAllNFTs(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}listNFTs(e,t){return Ex(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 Ex(this.configuration).listNFTsByAccountAddress(e.accountAddress,e.chainName,e.contractAddress,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},NftsApiAxiosParamCreator:Ax,NftsApiFactory:function(e,t,n){const r=Ex(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:Ex,OrderStatusName:{Pending:"PENDING",Active:"ACTIVE",Inactive:"INACTIVE",Filled:"FILLED",Expired:"EXPIRED",Cancelled:"CANCELLED"},OrdersApi:class extends tx{cancelOrders(e,t){return Ix(this.configuration).cancelOrders(e.chainName,e.cancelOrdersRequestBody,t).then((e=>e(this.axios,this.basePath)))}createListing(e,t){return Ix(this.configuration).createListing(e.chainName,e.createListingRequestBody,t).then((e=>e(this.axios,this.basePath)))}fulfillmentData(e,t){return Ix(this.configuration).fulfillmentData(e.chainName,e.fulfillmentDataRequest,t).then((e=>e(this.axios,this.basePath)))}getListing(e,t){return Ix(this.configuration).getListing(e.chainName,e.listingId,t).then((e=>e(this.axios,this.basePath)))}getTrade(e,t){return Ix(this.configuration).getTrade(e.chainName,e.tradeId,t).then((e=>e(this.axios,this.basePath)))}listListings(e,t){return Ix(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 Ix(this.configuration).listTrades(e.chainName,e.accountAddress,e.pageSize,e.sortBy,e.sortDirection,e.pageCursor,t).then((e=>e(this.axios,this.basePath)))}},OrdersApiAxiosParamCreator:_x,OrdersApiFactory:function(e,t,n){const r=Ix(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:Ix,PassportApi:class extends tx{createCounterfactualAddress(e,t){return Cx(this.configuration).createCounterfactualAddress(e.chainName,e.createCounterfactualAddressRequest,t).then((e=>e(this.axios,this.basePath)))}createCounterfactualAddressDeprecated(e,t){return Cx(this.configuration).createCounterfactualAddressDeprecated(e.createCounterfactualAddressRequestDeprecated,t).then((e=>e(this.axios,this.basePath)))}getLinkedAddresses(e,t){return Cx(this.configuration).getLinkedAddresses(e.userId,e.chainName,t).then((e=>e(this.axios,this.basePath)))}getLinkedAddressesDeprecated(e,t){return Cx(this.configuration).getLinkedAddressesDeprecated(e.userId,t).then((e=>e(this.axios,this.basePath)))}},PassportApiAxiosParamCreator:Rx,PassportApiFactory:function(e,t,n){const r=Cx(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:Cx,PendingOrderStatusNameEnum:{Pending:"PENDING"},ProtocolDataOrderTypeEnum:{FullRestricted:"FULL_RESTRICTED"},SaleFeeTypeEnum:{Royalty:"ROYALTY"},TokenContractType:{Erc20:"ERC20"},TokensApi:class extends tx{getERC20Token(e,t){return Ox(this.configuration).getERC20Token(e.contractAddress,e.chainName,t).then((e=>e(this.axios,this.basePath)))}listERC20Tokens(e,t){return Ox(this.configuration).listERC20Tokens(e.chainName,e.fromUpdatedAt,e.pageCursor,e.pageSize,t).then((e=>e(this.axios,this.basePath)))}},TokensApiAxiosParamCreator:kx,TokensApiFactory:function(e,t,n){const r=Ox(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:Ox});class Nx 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 xx={sdkVersion:"ts-immutable-sdk-multi-rollup-api-client-0.30.1"},Mx=({baseConfig:e,basePath:t,headers:n})=>{if(!t.trim())throw Error("basePath can not be empty");const r={...e,basePath:t,baseOptions:{headers:{...n||{},...xx}}};return new Sx.Configuration(r)};class Px{apiConfig;baseConfig;constructor({baseConfig:e,overrides:t}){if(this.baseConfig=e,t)this.apiConfig=Mx(t);else switch(e.environment){case st.SANDBOX:this.apiConfig=Mx({basePath:"https://api.sandbox.immutable.com",baseConfig:e});break;case st.PRODUCTION:this.apiConfig=Mx({basePath:"https://indexer-mr.imtbl.com",baseConfig:e});break;default:this.apiConfig=Mx({basePath:"https://api.sandbox.immutable.com",baseConfig:e})}}}function Bx(e){if(Ve.isAxiosError(e)&&e.response){const t=e.response.data;return t.code&&t.message?new Nx({code:t.code,message:t.message,details:t.details||null,link:t.link||"",trace_id:t.trace_id||""}):new Nx({code:e.code??e.response?.status.toString()??"unknown_error_code",message:String(e),details:null,link:"",trace_id:""})}return new Nx({code:"unknown_error_code",message:String(e),details:null,link:"",trace_id:""})}class Dx{config;activities;chains;collections;nfts;nftOwners;tokens;metadata;constructor(e){this.config=new Px(e),this.activities=new Sx.ActivitiesApi(this.config.apiConfig),this.chains=new Sx.ChainsApi(this.config.apiConfig),this.collections=new Sx.CollectionsApi(this.config.apiConfig),this.nfts=new Sx.NftsApi(this.config.apiConfig),this.nftOwners=new Sx.NftOwnersApi(this.config.apiConfig),this.tokens=new Sx.TokensApi(this.config.apiConfig),this.metadata=new Sx.MetadataApi(this.config.apiConfig)}async listActivities(e){return await this.activities.listActivities(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async getActivity(e){return await this.activities.getActivity(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listChains(e){return await this.chains.listChains(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listCollections(e){return await this.collections.listCollections(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listCollectionsByNFTOwner(e){return await this.collections.listCollectionsByNFTOwner(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async getCollection(e){return await this.collections.getCollection(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async getNFT(e){return await this.nfts.getNFT(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listNFTs(e){return await this.nfts.listNFTs(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listNFTsByAccountAddress(e){return await this.nfts.listNFTsByAccountAddress(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listAllNFTs(e){return await this.nfts.listAllNFTs(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listNFTOwners(e){return await this.nftOwners.listNFTOwners(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listNFTOwnersByContractAddress(e){return await this.nftOwners.listOwnersByContractAddress(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listAllNFTOwners(e){return await this.nfts.listAllNFTOwners(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listTokens(e){return await this.tokens.listERC20Tokens(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async getToken(e){return await this.tokens.getERC20Token(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async getMetadata(e){return await this.metadata.getMetadata(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async listNFTMetadataByContractAddress(e){return await this.metadata.listMetadata(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async refreshCollectionMetadata(e){return await this.collections.refreshCollectionMetadata(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async refreshNFTMetadata(e){return await this.metadata.refreshNFTMetadataByTokenID(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}async refreshStackedMetadata(e){return await this.metadata.refreshMetadataByID(e).then((e=>e.data)).catch((e=>{throw Bx(e)}))}}async function Fx(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 Lx(e,t){const n=await t.remote.getConfig("dex");return new LR({chainId:e,baseConfig:new ut({environment:t.environment}),overrides:n?.overrides})}function Ux(e){return new ZN({baseConfig:{environment:e.environment}})}function qx(e){return new Dx({baseConfig:{environment:e.environment}})}const jx="0x0000000000000000000000000000000000000001",Gx=18;async function Hx(t,n,r,i){const a=bm(n),o=vm(n),s=await n.remote.getConfig("gasEstimateTokens"),{gasTokenAddress:u,fromAddress:c}=s[a].bridgeToL2Addresses,l=t.get(a);if(!l)throw new Error(`Missing JsonRpcProvider for chain id: ${a}`);try{const s=await async function(e,t){const n=await Dm(e);return n&&t?{estimatedAmount:n.add(n)}:{estimatedAmount:n}}(l,r);s.token=await async function(e,t,n,r){if("NATIVE"===t)return e.networkMap.get(n)?.nativeCurrency;const i=new vl(t,JSON.stringify(tm),r);return{name:await i.name(),symbol:await i.symbol(),decimals:await i.decimals(),address:t}}(n,i??(u||"NATIVE"),a,l);const d=await Fx(a,o,t,n),{bridgeFee:f,bridgeable:p}=await async function(e,t){const n=await e.getFee({token:t});return{bridgeFee:{estimatedAmount:n.feeAmount},bridgeable:n.bridgeable}}(d,c);return{gasEstimateType:e.GasEstimateType.BRIDGE_TO_L2,gasFee:s,bridgeFee:{estimatedAmount:f?.estimatedAmount,token:f?.token},bridgeable:p}}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 Hx(n,r,t.isSpendingCapApprovalRequired,t.tokenAddress);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 Lx(n,t),{swap:o}=await r.getUnsignedSwapTxFromAmountIn(jx,i,a,tr.from(kh("1",Gx)));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??Gx}}}}catch{return{gasEstimateType:e.GasEstimateType.SWAP,gasFee:{}}}}(r);default:throw new lm("Invalid type provided for gasEstimateType",e.CheckoutErrorType.INVALID_GAS_ESTIMATE_TYPE)}}const Vx=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))),Wx=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})}},Kx=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})}},Xx=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})}},Jx=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})}},Yx=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})}},Qx=(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},Zx=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,Xx(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=Qx(i,r);o.set(d,n),s.set(d,Yx(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=Qx(p,l);u.set(m,{type:e.ItemType.ERC721,sufficient:!1,itemRequirement:s,approvalTransaction:void 0}),c.set(m,Jx(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()))}},$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,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))),eM=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)}},tM=async(t,n,r,i)=>{const a=$x(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(eM(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}},nM=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)}},rM=async(t,n,r)=>{const i=[];let a=tr.from(0);for(const e of n)void 0!==e.approvalTransaction&&i.push(nM(t,e.approvalTransaction));if(r.type===e.TransactionOrGasType.TRANSACTION)i.push(nM(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)},iM=(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)}}),aM=async()=>!0,oM=async e=>{const t=iM(e.isDevelopment,e.isProduction);try{return await t.checkDexAvailability()}catch{return!1}};async function sM(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 uM=async(e,t,n,r,i)=>{const a=new Map;try{const o=await Lx(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}},cM=(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}},lM=(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}},dM=(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}},fM=(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},pM=(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)},hM=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 uM(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=dM(f,t.approval);if(!i.sufficient)continue;if(!fM(f,i,t.swap,t.quote.fees,{amount:r.value,address:e}))continue;if(!pM(n.balance,s,e,r.value,i,t.quote.fees))continue;const a=cM(t.approval,t.swap,t.quote.fees);u.push(lM(l,r.value,n,a))}return u},mM=(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))))):[],yM=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{}},gM=async(e,t,n)=>{if(n.bridge){const n=(await e.remote.getConfig("bridge"))?.tokens??[],r=t.get(bm(e));return mM(n,r)}return[]},bM=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 mM(n,r)}return[]})(e,t,n),r.bridge=await gM(e,t,n),r.onRamp=await yM(e,n),r},vM="0x0000000000000000000000000000000000000001",wM=async(e,t)=>(await t.remote.getConfig("imxAddressMapping"))[e]??"",TM=async(t,n)=>{if(""===n)return{l1address:"",l2address:n};if(n===Vh)return{l1address:await wM(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=qx(t),o=(await a.getToken({chainName:r,contractAddress:n})).result.root_contract_address;return null===o?{l1address:"",l2address:n}:{l1address:o,l2address:n}},AM=async(t,n,r,i,a,o)=>{if(a===vM)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 Fx(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)},EM=(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),_M=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)},IM=(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}]}},RM=(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}),CM=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 gM(t,o,i);if(0===d.length)return;const f=await _M(t,n,s);if(!EM(c,f.totalFees))return;const p=await TM(t,a.l2address),{l1address:h}=p;if(""===h)return;if(h===vM){if(!d.find((e=>!("address"in e))))return}else if(!d.find((e=>e.address===h)))return;const m=await AM(t,n,l,r,h,a.amount);let y=f.bridgeFee.estimatedAmount;if(h===vM){const t=c.balances.find((e=>{return!(t=e.token.address)||""===t;var t}));if(f.gasFee.estimatedAmount&&(y=y.add(f.gasFee.estimatedAmount)),!EM(c,y))return;if(t&&t.balance.gte(a.amount.add(y))){const n=IM(m,f.gasFee,f.bridgeFee);return RM(u,t,a,e.ItemType.NATIVE,n)}return}if(y.add(m).add(f.gasFee.estimatedAmount),!EM(c,y))return;const g=c.balances.find((e=>e.token.address===h));if(g&&g.balance.gte(a.amount)){const t=IM(m,f.gasFee,f.bridgeFee);return RM(u,g,a,e.ItemType.ERC20,t)}},kM=(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},OM=(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)},SM=(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)},NM=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=>TM(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 uM(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===vM||e.token.address===c));if(!d)continue;const f=s.quote.amountWithMaxSlippage.value,p=kM(s,o),h=f.add(p),m=OM(i,o),y=SM(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,CM(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 hM(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===vM&&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)},xM=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 yM(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},MM=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 sM(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",bM(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 CM(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 hM(e,t,r,n,i,c,o)})(t,i,c,n,o,s.swap,r)),l.push(xM(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?vM:e.address)),p=s?.swap??[];return i.type!==e.ItemType.NATIVE&&i.type!==e.ItemType.ERC20?[]:await NM(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},PM=async(t,n,r,i)=>{const a=await n.getSigner().getAddress();let o=Vx(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,Wx(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,Kx(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=Zx(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",rM(n,l,i));null!==d&&(o.push(d),o=Vx(o));const f=await Im(t,"Time to run balance checks",tM(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:aM()}),n.swap&&r.push({id:"swap",promise:oM(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",MM(t,a,f,m))}}};var BM;!function(e){e.SUCCESS="SUCCESS",e.FAILED="FAILED"}(BM||(BM={}));const DM=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:BM.FAILED,transactionHash:e.transactionHash,reason:"Approval transaction failed and was reverted"};return{type:BM.SUCCESS}},FM=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:BM.FAILED,transactionHash:e.transactionHash,reason:"Fulfillment transaction failed and was reverted"};return{type:BM.SUCCESS}},LM=async e=>{let t=[];const n=[];for(const t of e)t.type===FN.TRANSACTION&&t.purpose===BN.FULFILL_ORDER&&n.push(t.buildTransaction());return t=await Promise.all(n),t},UM=(e,t)=>{const n=e.amount,r=Math.round(n.percentageDecimal*10**6);return t.mul(tr.from(r)).div(10**6)},qM=(e,t)=>kh(e.amount.token,t),jM=(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=UM(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=qM(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},GM=(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}}},HM=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=$N,u=Ux(t),c=qx(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=jM(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===FN.TRANSACTION&&t.purpose===BN.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(xN.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",LM(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 _=[GM(T,A,w,a)],I=await Im(t,"Total time running smart checkout",PM(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 DM(n,y);if(t.type===BM.FAILED)return{status:e.CheckoutStatus.FAILED,transactionHash:t.transactionHash,reason:t.reason,smartCheckoutResult:I};try{0===g.length&&(g=await LM(b))}catch(t){throw new lm("Error fetching fulfillment transaction",e.CheckoutErrorType.FULFILL_ORDER_LISTING_ERROR,{message:t.message})}const r=await FM(n,g);return r.type===BM.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}},zM=(t,n,r)=>({type:e.ItemType.ERC721,id:t,contractAddress:n,spenderAddress:r}),VM=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=Ux(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=[zM(u.id,u.collectionAddress,o)],p=await Im(t,"Total time running smart checkout",PM(t,n,f,{type:e.TransactionOrGasType.GAS,gasToken:{type:e.GasTokenType.NATIVE,limit:tr.from($N)}}));if(p.sufficient){const t=await(async e=>{let t=[],n=[];const r=[],i=[];for(const t of e)t.type===FN.TRANSACTION&&(t.purpose===BN.APPROVAL&&r.push(t.buildTransaction()),t.purpose===BN.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 DM(n,t.approvalTransactions);if(r.type===BM.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===FN.SIGNABLE&&e.purpose===DN.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=jM(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 WM{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 KM(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 XM=()=>"0.30.1";function JM(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=XM();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 YM={baseConfig:{environment:st.SANDBOX},passport:void 0};e.CHECKOUT_API_BASE_URL=Jh,e.Checkout=class{readOnlyProviders;config;fiatRampService;availability;passport;constructor(e=YM){this.config=new wm(e),this.fiatRampService=new WM(this.config),this.readOnlyProviders=new Map,this.availability=iM(this.config.isDevelopment,this.config.isProduction),this.passport=e.passport}async widgets(t){const n=this,r=new Promise(((r,i)=>{try{JM(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 Pm(this.config,t.provider,{allowUnsupportedProvider:!0}))}async connect(t){const n=await Pm(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 Pm(this.config,e.provider,{allowUnsupportedProvider:!0,allowMistmatchedChainId:!0});return await mm(this.config,t,e.chainId)}async getBalance(e){const t=await Pm(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 Pm(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 Pm(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 Pm(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 Pm(this.config,e.provider);return await HM(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 Pm(this.config,e.provider);return await VM(this.config,t,e.orders)}async cancel(t){console.warn("This endpoint currently only processes the first order in the array.");const n=await Pm(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=Ux(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 FM(n,[i]);return o.type===BM.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 Pm(this.config,t.provider);let r=[];try{r=await KM(n,t.itemRequirements)}catch{throw new lm("Failed to map item requirements",e.CheckoutErrorType.ITEM_REQUIREMENTS_ERROR)}return await PM(this.config,n,r,t.transactionOrGasAmount)}static isWeb3Provider(e){return Mm(e)}async gasEstimate(e){return this.readOnlyProviders=await sM(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}));
|