mnee
Version:
Legacy package for interacting with MNEE USD stablecoin. Includes experimental features.
1 lines • 67.8 kB
JavaScript
var e=require("@bsv/sdk");function r(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}}),r.default=e,r}var t=/*#__PURE__*/r(require("bip39"));function n(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=Array(r);t<r;t++)n[t]=e[t];return n}function i(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return n(e,r);var t={}.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?n(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){t&&(e=t);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function o(){return o=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},o.apply(null,arguments)}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}function a(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(a=function(){return!!e})()}function u(e,r){return u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,r){return e.__proto__=r,e},u(e,r)}function c(e){var r="function"==typeof Map?new Map:void 0;return c=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(r){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(e))return r.get(e);r.set(e,t)}function t(){return function(e,r,t){if(a())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,r);var i=new(e.bind.apply(e,n));return t&&u(i,t.prototype),i}(e,arguments,s(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),u(t,e)},c(e)}function f(e){var r=new Error(e);return r.stack=void 0,r}var d=/*#__PURE__*/function(){function r(){}var t=r.prototype;return t.lock=function(r,t){var n=[];if("string"==typeof r){var i=e.Utils.fromBase58Check(r);if(0!==i.prefix[0]&&111!==i.prefix[0])throw f("only P2PKH is supported");n=i.data}else n=r;var o=new e.LockingScript;return o.writeOpCode(e.OP.OP_DUP).writeOpCode(e.OP.OP_HASH160).writeBin(n).writeOpCode(e.OP.OP_EQUALVERIFY).writeOpCode(e.OP.OP_CHECKSIGVERIFY).writeBin(t.encode(!0)).writeOpCode(e.OP.OP_CHECKSIG),o},t.userUnlock=function(r,t,n,i,o){return void 0===t&&(t="all"),void 0===n&&(n=!1),{sign:function(s,a){try{var u,c,d,l=e.TransactionSignature.SIGHASH_FORKID;"all"===t&&(l|=e.TransactionSignature.SIGHASH_ALL),"none"===t&&(l|=e.TransactionSignature.SIGHASH_NONE),"single"===t&&(l|=e.TransactionSignature.SIGHASH_SINGLE),n&&(l|=e.TransactionSignature.SIGHASH_ANYONECANPAY);var h=s.inputs[a],v=s.inputs.filter(function(e,r){return r!==a}),m=h.sourceTXID?h.sourceTXID:null==(u=h.sourceTransaction)?void 0:u.id("hex");if(!m)throw f("The input sourceTXID or sourceTransaction is required for transaction signing.");if(i||(i=null==(c=h.sourceTransaction)?void 0:c.outputs[h.sourceOutputIndex].satoshis),!i)throw f("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(o||(o=null==(d=h.sourceTransaction)?void 0:d.outputs[h.sourceOutputIndex].lockingScript),!o)throw f("The lockingScript or input sourceTransaction is required for transaction signing.");var p=e.TransactionSignature.format({sourceTXID:m,sourceOutputIndex:h.sourceOutputIndex,sourceSatoshis:i,transactionVersion:s.version,otherInputs:v,inputIndex:a,outputs:s.outputs,inputSequence:h.sequence||4294967295,subscript:o,lockTime:s.lockTime,scope:l}),g=r.sign(e.Hash.sha256(p)),y=new e.TransactionSignature(g.r,g.s,l),P=new e.UnlockingScript;return P.writeBin(y.toChecksigFormat()),P.writeBin(r.toPublicKey().encode(!0)),Promise.resolve(P)}catch(e){return Promise.reject(e)}},estimateLength:function(){return Promise.resolve(182)}}},t.unlock=function(r,t,n,i,o,s){return void 0===n&&(n="all"),void 0===i&&(i=!1),{sign:function(a,u){try{var c,d,l,h=e.TransactionSignature.SIGHASH_FORKID;"all"===n&&(h|=e.TransactionSignature.SIGHASH_ALL),"none"===n&&(h|=e.TransactionSignature.SIGHASH_NONE),"single"===n&&(h|=e.TransactionSignature.SIGHASH_SINGLE),i&&(h|=e.TransactionSignature.SIGHASH_ANYONECANPAY);var v=a.inputs[u],m=a.inputs.filter(function(e,r){return r!==u}),p=v.sourceTXID?v.sourceTXID:null==(c=v.sourceTransaction)?void 0:c.id("hex");if(!p)throw f("The input sourceTXID or sourceTransaction is required for transaction signing.");if(o||(o=null==(d=v.sourceTransaction)?void 0:d.outputs[v.sourceOutputIndex].satoshis),!o)throw f("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(s||(s=null==(l=v.sourceTransaction)?void 0:l.outputs[v.sourceOutputIndex].lockingScript),!s)throw f("The lockingScript or input sourceTransaction is required for transaction signing.");var g=e.TransactionSignature.format({sourceTXID:p,sourceOutputIndex:v.sourceOutputIndex,sourceSatoshis:o,transactionVersion:a.version,otherInputs:m,inputIndex:u,outputs:a.outputs,inputSequence:v.sequence||4294967295,subscript:s,lockTime:a.lockTime,scope:h}),y=r.sign(e.Hash.sha256(g)),P=new e.TransactionSignature(y.r,y.s,h),w=new e.UnlockingScript;return w.writeBin(P.toChecksigFormat()),w.writeScript(t),Promise.resolve(w)}catch(e){return Promise.reject(e)}},estimateLength:function(){return Promise.resolve(182)}}},r}(),l=function(e){return Buffer.from(e).toString("hex")},h=function(r,t,n,i){void 0===i&&(i=!1);var o="";if(void 0!==(null==t?void 0:t.dataB64)&&void 0!==(null==t?void 0:t.contentType)){var s=l("ord"),a=Buffer.from(t.dataB64,"base64").toString("hex").trim();if(!a)throw f("Invalid file data");var u=l(t.contentType);if(!u)throw f("Invalid media type");o="OP_0 OP_IF "+s+" OP_1 "+u+" OP_0 "+a+" OP_ENDIF"}var c=(o?o+" "+(i?"OP_CODESEPARATOR ":""):"")+r.toASM();if(n&&(!n.app||!n.type))throw f("MAP.app and MAP.type are required fields");if(null!=n&&n.app&&null!=n&&n.type){c=(c?c+" ":"")+"OP_RETURN "+l("1PuQa7K62MiKCtssSLKy1kh56WWU7MtUR5")+" "+l("SET");for(var d=0,h=Object.entries(n);d<h.length;d++){var v=h[d],m=v[0],p=v[1];"cmd"!==m&&(c=c+" "+l(m)+" "+l(p))}}return e.LockingScript.fromASM(c)},v=1e-5,m="ae59f3b898ec61acbdb6cc7a245fabeded0c094bf046f35206a3aec60ef88127_0",p="1inHbiwj2jrEcZPiSYnfgJ8FmS1Bmk4Dh",g="833a7720966a2a435db28d967385e8aa7284b6150ebb39482cc5228b73e1703f_0",y="1AZNdbFYBDFTAEgzZMfPzANxyNrpGJZAUY",P=function(r){for(var t,n,i,o=0;o<r.chunks.length;o++){var s,a=r.chunks[o];o>=2&&3===(null==(s=a.data)?void 0:s.length)&&"ord"==e.Utils.toUTF8(a.data)&&r.chunks[o-1].op==e.OP.OP_IF&&r.chunks[o-2].op==e.OP.OP_FALSE&&(i=o+1)}if(void 0!==i){for(var u={file:{hash:"",size:0,type:""},fields:{}},c=i;c<r.chunks.length;c+=2){var f,d,l=r.chunks[c];if(l.op==e.OP.OP_ENDIF)break;if(l.op>e.OP.OP_16)return;var h=r.chunks[c+1];if(h.op>e.OP.OP_PUSHDATA4)return;if(null==(f=l.data)||!f.length){var v=0;switch(l.op>e.OP.OP_PUSHDATA4&&l.op<=e.OP.OP_16?v=l.op-80:null!=(d=l.data)&&d.length&&(v=l.data[0]),v){case 0:if(u.file.size=(null==(t=h.data)?void 0:t.length)||0,null==(n=h.data)||!n.length)break;u.file.hash=e.Utils.toBase64(e.Hash.sha256(h.data)),u.file.content=h.data;break;case 1:u.file.type=Buffer.from(h.data||[]).toString()}}}return u}},w=function(r){return r.map(function(r){for(var t=r.chunks,n=0;n<=t.length-4;n++){var i,o,s;if(t.length>n+6&&t[0+n].op===e.OP.OP_DUP&&t[1+n].op===e.OP.OP_HASH160&&20===(null==(i=t[2+n].data)?void 0:i.length)&&t[3+n].op===e.OP.OP_EQUALVERIFY&&t[4+n].op===e.OP.OP_CHECKSIGVERIFY&&33===(null==(o=t[5+n].data)?void 0:o.length)&&t[6+n].op===e.OP.OP_CHECKSIG)return{cosigner:e.Utils.toHex(t[5+n].data||[]),address:e.Utils.toBase58Check(t[2+n].data||[],[0])};if(t[0+n].op===e.OP.OP_DUP&&t[1+n].op===e.OP.OP_HASH160&&20===(null==(s=t[2+n].data)?void 0:s.length)&&t[3+n].op===e.OP.OP_EQUALVERIFY&&t[4+n].op===e.OP.OP_CHECKSIG)return{cosigner:"",address:e.Utils.toBase58Check(t[2+n].data||[],[0])}}}).filter(function(e){return void 0!==e})},b=function(r,t,n){var i=r.senders.includes(t)?"send":"receive",o=r.height>0?"confirmed":"unconfirmed";if(!r.rawtx)return null;var s=e.Utils.toArray(r.rawtx,"base64"),a=e.Utils.toHex(s),u=e.Transaction.fromHex(a).outputs.map(function(e){return e.lockingScript}),c=w(u),f=u.map(P),d=c.map(function(e){return e.address}),l=d.indexOf(n.feeAddress),h=r.senders[0],v=0,m=new Map;f.forEach(function(r,i){var o,s=null==r||null==(o=r.file)?void 0:o.content;if(s){var a=e.Utils.toUTF8(s);if(a){var u;try{u=JSON.parse(a)}catch(e){return void console.error("Failed to parse inscription JSON:",e)}if("bsv-20"===u.p&&u.id===n.tokenId){var c=parseInt(u.amt,10);if(!Number.isNaN(c))if(l!==i||h!==t){var f=d[i],p=m.get(f)||0;m.set(f,p+c)}else v+=c}}}});var p=m.get(t)||0;if("send"===i){var g=m.get(h)||0;m.set(h,g-p)}var y=[],b=(y="receive"===i?[{address:h,amount:p}]:Array.from(m.entries()).map(function(e){return{address:e[0],amount:e[1]}}).filter(function(e){return e.address!==t&&e.address!==n.feeAddress&&e.amount>0})).reduce(function(e,r){return e+r.amount},0);return{txid:r.txid,height:r.height,type:i,status:o,amount:b,fee:v,score:r.score,counterparties:y}},A=function(r){try{var t=e.Utils.fromBase58Check(r),n=t.prefix[0];if("number"!=typeof n||![0].includes(n))throw f("Invalid address prefix: "+n);if(20!==t.data.length)throw f("Invalid address payload length: "+t.data.length);return!0}catch(e){return!1}},I=function(r){try{return{isValid:!0,privateKey:e.PrivateKey.fromWif(r)}}catch(e){if(e instanceof Error){var t=e.message.toLowerCase();if(t.includes("invalid base58 character"))return{isValid:!1,error:"Invalid WIF key: contains invalid characters"};if(t.includes("invalid checksum"))return{isValid:!1,error:"Invalid WIF key: checksum verification failed"};if(t.includes("expected base58 string"))return{isValid:!1,error:"Invalid WIF key: must be a valid base58 encoded string"}}return{isValid:!1,error:"Invalid WIF key provided"}}},S=/*#__PURE__*/function(e){function r(r){var t;return(t=e.call(this,r.message)||this).code=void 0,t.hostname=void 0,t.originalError=void 0,t.name="NetworkError",t.code=r.code,t.hostname=r.hostname,t.originalError=r.originalError,t}var t,n;return n=e,(t=r).prototype=Object.create(n.prototype),t.prototype.constructor=t,u(t,n),r}(/*#__PURE__*/c(Error));function T(e){var r,t,n;if(!e)return!1;var i=["ENOTFOUND","ECONNREFUSED","ETIMEDOUT","ECONNRESET","ENETUNREACH","EHOSTUNREACH","EPIPE","ECONNABORTED"];return!!i.includes(e.code)||!(!e.cause||!i.includes(null==(r=e.cause)?void 0:r.code))||!!(null!=(t=e.message)&&t.includes("fetch failed")||null!=(n=e.message)&&n.includes("getaddrinfo"))}function x(e,r){if(T(e)){var t=function(e){if(e.cause&&e.cause.code){var r=e.cause,t="Network connection failed";switch(r.code){case"ENOTFOUND":t="Unable to connect to MNEE network. Please check your internet connection.";break;case"ECONNREFUSED":t="Connection refused by MNEE server. The service may be temporarily unavailable.";break;case"ETIMEDOUT":t="Request timed out. Please check your internet connection and try again.";break;case"ECONNRESET":t="Connection was reset. Please try again.";break;case"ENETUNREACH":case"EHOSTUNREACH":t="Network unreachable. Please check your internet connection.";break;default:t="Network error: "+r.code+". Please check your connection and try again."}return new S({code:r.code,message:t,hostname:r.hostname,originalError:e})}if(e.code){var n="Network error occurred";switch(e.code){case"ENOTFOUND":n="Unable to connect to MNEE network. Please check your internet connection.";break;case"ECONNREFUSED":n="Connection refused by MNEE server. The service may be temporarily unavailable.";break;case"ETIMEDOUT":n="Request timed out. Please check your internet connection and try again.";break;default:n="Network error: "+e.code+". Please check your connection and try again."}return new S({code:e.code,message:n,hostname:e.hostname,originalError:e})}return new S({code:"NETWORK_ERROR",message:"Network error occurred. Please check your internet connection and try again.",originalError:e})}(e);return console.error("Network error during "+r+": "+t.message),t.message}console.error("Failed to "+r+":",e)}var O=["parseOptions"];function k(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}const E="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function C(e,r,t){if(!e.s){if(t instanceof N){if(!t.s)return void(t.o=C.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(C.bind(null,e,r),C.bind(null,e,2));e.s=r,e.v=t;var n=e.o;n&&n(e)}}var N=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(r,t){var n=new e,i=this.s;if(i){var o=1&i?r:t;if(o){try{C(n,1,o(this.v))}catch(e){C(n,2,e)}return n}return this}return this.o=function(e){try{var i=e.v;1&e.s?C(n,1,r?r(i):i):t?C(n,1,t(i)):C(n,2,i)}catch(e){C(n,2,e)}},n},e}();function H(e){return e instanceof N&&1&e.s}var j=/*#__PURE__*/function(){function e(e){this.service=void 0,this.service=e}var r=e.prototype;return r.getUtxos=function(e,r){void 0===r&&(r={});try{var t=this;if(!Array.isArray(e))throw f("Input must be an array of addresses");var n=[];return Promise.resolve(t.processBatch(e,function(e){try{for(var o,s=[],a=[],u=i(e);!(o=u()).done;){var c=o.value;c&&"string"==typeof c&&""!==c.trim()?/^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$|^bc1[a-z0-9]{39,59}$/.test(c)?s.push(c):(a.push(c),n.push({items:[c],error:{message:"Invalid address format: "+c},retryCount:0})):(a.push(c),n.push({items:[c],error:{message:"Invalid address: empty or not a string"},retryCount:0}))}if(!r.continueOnError&&a.length>0)throw new Error(n[0].error.message);return 0===s.length?Promise.resolve([]):Promise.resolve(t.service.getUtxos(s)).then(function(r){return e.map(function(e){return{address:e,utxos:s.includes(e)?r.filter(function(r){return r.owners.includes(e)}):[]}})})}catch(e){return Promise.reject(e)}},r)).then(function(e){return o({},e,{errors:[].concat(e.errors,n),totalErrors:e.errors.length+n.length})})}catch(e){return Promise.reject(e)}},r.getBalances=function(e,r){void 0===r&&(r={});try{var t=this;if(!Array.isArray(e))throw f("Input must be an array of addresses");return Promise.resolve(t.processBatch(e,function(e){try{return Promise.resolve(t.service.getBalances(e))}catch(e){return Promise.reject(e)}},r))}catch(e){return Promise.reject(e)}},r.getTxHistories=function(e,r){void 0===r&&(r={});try{var t=this;if(!Array.isArray(e))throw f("Input must be an array of address history parameters");return Promise.resolve(t.processBatch(e,function(e){try{return Promise.resolve(t.service.getRecentTxHistories(e))}catch(e){return Promise.reject(e)}},r,function(e){return e.address}))}catch(e){return Promise.reject(e)}},r.parseTx=function(e,r){void 0===r&&(r={});try{var t=this;if(!Array.isArray(e))throw f("Input must be an array of transaction IDs");var n=r.parseOptions,i=function(e,r){if(null==e)return{};var t={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(-1!==r.indexOf(n))continue;t[n]=e[n]}return t}(r,O),s=[];return Promise.resolve(t.processBatch(e,function(e){try{return Promise.resolve(Promise.allSettled(e.map(function(e){try{if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid transaction ID: empty or not a string");if(!/^[a-fA-F0-9]{64}$/.test(e))throw new Error("Invalid transaction ID format: "+e);return Promise.resolve(t.service.parseTx(e,n)).then(function(r){return{txid:e,parsed:r}})}catch(e){return Promise.reject(e)}}))).then(function(r){var t=[];if(r.forEach(function(r,n){var o=e[n];if("fulfilled"===r.status)t.push(r.value);else{var a=r.reason instanceof Error?r.reason.message:String(r.reason);s.push({items:[o],error:{message:a},retryCount:i.maxRetries||3})}}),!i.continueOnError&&s.length>0)throw new Error(s[0].error.message);return t})}catch(e){return Promise.reject(e)}},i)).then(function(e){return o({},e,{errors:[].concat(e.errors,s),totalErrors:e.errors.length+s.length})})}catch(e){return Promise.reject(e)}},r.processBatch=function(e,r,t,n){try{var i=this,o=t.chunkSize,s=void 0===o?20:o,a=t.continueOnError,u=void 0!==a&&a,c=t.onProgress,f=t.maxRetries,d=void 0===f?3:f,l=t.retryDelay,h=void 0===l?1e3:l,v=t.requestsPerSecond,m=void 0===v?3:v,p=s>0?s:20,g=m>0?m:3,y=Math.ceil(1e3/g),P=Math.max(1,Math.floor(g)),w=new M(P,y);if(0===e.length)return Promise.resolve({results:[],errors:[],totalProcessed:0,totalErrors:0});var b=[],A=[],I=0,S=i.chunkArray(e,p),T=S.length,x=S.map(function(e){try{return Promise.resolve(k(function(){return Promise.resolve(i.processWithRetry(function(){return r(e)},d,h,w)).then(function(e){return b.push.apply(b,e),I++,c&&c(I,T,A.length),e})},function(t){function o(){if(b.push.apply(b,s),a.length>0){var e=a.map(function(e){var r=e.item;return n?n(r):r}),r=a[0].error;A.push({items:e,error:{message:r.message,code:r.code},retryCount:d})}return I++,c&&c(I,T,A.length),s}if(!u)throw t;var s=[],a=[],f=function(e,r){if("function"==typeof e[E]){var t,n,i,o=function(e){try{for(;!(t=s.next()).done;)if((e=r(t.value))&&e.then){if(!H(e))return void e.then(o,i||(i=C.bind(null,n=new N,2)));e=e.v}n?C(n,1,e):n=e}catch(e){C(n||(n=new N),2,e)}},s=e[E]();if(o(),s.return){var a=function(e){try{t.done||s.return()}catch(e){}return e};if(n&&n.then)return n.then(a,function(e){throw a(e)});a()}return n}if(!("length"in e))throw new TypeError("Object is not iterable");for(var u=[],c=0;c<e.length;c++)u.push(e[c]);return function(e,r){var t,n,i=-1;return function o(s){try{for(;++i<e.length;)if((s=r(i))&&s.then){if(!H(s))return void s.then(o,n||(n=C.bind(null,t=new N,2)));s=s.v}t?C(t,1,s):t=s}catch(e){C(t||(t=new N),2,e)}}(),t}(u,function(e){return r(u[e])})}(e,function(e){var t=k(function(){return Promise.resolve(i.processWithRetry(function(){return r([e])},d,h,w)).then(function(e){e.length>0&&s.push.apply(s,e)})},function(r){var t=r instanceof Error?r:new Error(String(r));a.push({item:e,error:t})});if(t&&t.then)return t.then(function(){})});return f&&f.then?f.then(o):o()}))}catch(e){return Promise.reject(e)}});return Promise.resolve(Promise.all(x)).then(function(){return{results:b,errors:A,totalProcessed:I,totalErrors:A.length}})}catch(e){return Promise.reject(e)}},r.processWithRetry=function(e,r,t,n){try{var i,o,s=function(e){if(i)return e;throw o||new Error("Max retries exceeded")},a=this,u=0,c=function(e,r,t){for(var n;;){var i=e();if(H(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!H(o)){n=1;break}o=o.s}if(r){var s=r();if(s&&s.then&&!H(s)){n=2;break}}}var a=new N,u=C.bind(null,a,2);return(0===n?i.then(f):1===n?o.then(c):s.then(d)).then(void 0,u),a;function c(n){o=n;do{if(r&&(s=r())&&s.then&&!H(s))return void s.then(d).then(void 0,u);if(!(i=e())||H(i)&&!i.v)return void C(a,1,o);if(i.then)return void i.then(f).then(void 0,u);H(o=t())&&(o=o.v)}while(!o||!o.then);o.then(c).then(void 0,u)}function f(e){e?(o=t())&&o.then?o.then(c).then(void 0,u):c(o):C(a,1,o)}function d(){(i=e())?i.then?i.then(f).then(void 0,u):f(i):C(a,1,o)}}(function(){return!i&&u<r},function(){return u++},function(){return k(function(){return Promise.resolve(n.execute(e)).then(function(e){return i=1,e})},function(e){o=e;var n=function(){if(u<r-1)return Promise.resolve(a.delay(t*(u+1))).then(function(){})}();return n&&n.then?n.then(function(){}):void 0})});return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},r.chunkArray=function(e,r){for(var t=[],n=Math.max(1,r),i=0;i<e.length;i+=n)t.push(e.slice(i,i+n));return t},r.delay=function(e){return new Promise(function(r){return setTimeout(r,e)})},e}(),M=/*#__PURE__*/function(){function e(e,r){this.maxConcurrent=void 0,this.minDelay=void 0,this.queue=[],this.running=0,this.maxConcurrent=e,this.minDelay=r}var r=e.prototype;return r.execute=function(e){try{var r=this;return Promise.resolve(r.waitForSlot()).then(function(){return function(t,n){try{var i=function(){r.running++;var t=Date.now();return Promise.resolve(e()).then(function(e){var n=Date.now()-t,i=function(){if(n<r.minDelay)return Promise.resolve(r.delay(r.minDelay-n)).then(function(){})}();return i&&i.then?i.then(function(){return e}):e})}()}catch(e){return n(!0,e)}return i&&i.then?i.then(n.bind(null,!1),n.bind(null,!0)):n(!1,i)}(0,function(e,t){if(r.running--,r.processQueue(),e)throw t;return t})})}catch(e){return Promise.reject(e)}},r.waitForSlot=function(){var e=this;return this.running<this.maxConcurrent?Promise.resolve():new Promise(function(r){e.queue.push(r)})},r.processQueue=function(){if(this.queue.length>0&&this.running<this.maxConcurrent){var e=this.queue.shift();e&&e()}},r.delay=function(e){return new Promise(function(r){return setTimeout(r,e)})},e}();function U(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}function _(e,r,t){if(!e.s){if(t instanceof F){if(!t.s)return void(t.o=_.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(_.bind(null,e,r),_.bind(null,e,2));e.s=r,e.v=t;var n=e.o;n&&n(e)}}var F=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(r,t){var n=new e,i=this.s;if(i){var o=1&i?r:t;if(o){try{_(n,1,o(this.v))}catch(e){_(n,2,e)}return n}return this}return this.o=function(e){try{var i=e.v;1&e.s?_(n,1,r?r(i):i):t?_(n,1,t(i)):_(n,2,i)}catch(e){_(n,2,e)}},n},e}();function D(e){return e instanceof F&&1&e.s}function R(e,r,t){for(var n;;){var i=e();if(D(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!D(o)){n=1;break}o=o.s}if(r){var s=r();if(s&&s.then&&!D(s)){n=2;break}}}var a=new F,u=_.bind(null,a,2);return(0===n?i.then(f):1===n?o.then(c):s.then(d)).then(void 0,u),a;function c(n){o=n;do{if(r&&(s=r())&&s.then&&!D(s))return void s.then(d).then(void 0,u);if(!(i=e())||D(i)&&!i.v)return void _(a,1,o);if(i.then)return void i.then(f).then(void 0,u);D(o=t())&&(o=o.v)}while(!o||!o.then);o.then(c).then(void 0,u)}function f(e){e?(o=t())&&o.then?o.then(c).then(void 0,u):c(o):_(a,1,o)}function d(){(i=e())?i.then?i.then(f).then(void 0,u):f(i):_(a,1,o)}}var K="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function B(e,r,t){var n,i,o=-1;return function s(a){try{for(;++o<e.length&&(!t||!t());)if((a=r(o))&&a.then){if(!D(a))return void a.then(s,i||(i=_.bind(null,n=new F,2)));a=a.v}n?_(n,1,a):n=a}catch(e){_(n||(n=new F),2,e)}}(),n}function q(e,r,t){if("function"==typeof e[K]){var n,i,o,s=function(e){try{for(;!((n=a.next()).done||t&&t());)if((e=r(n.value))&&e.then){if(!D(e))return void e.then(s,o||(o=_.bind(null,i=new F,2)));e=e.v}i?_(i,1,e):i=e}catch(e){_(i||(i=new F),2,e)}},a=e[K]();if(s(),a.return){var u=function(e){try{n.done||a.return()}catch(e){}return e};if(i&&i.then)return i.then(u,function(e){throw u(e)});u()}return i}if(!("length"in e))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<e.length;f++)c.push(e[f]);return B(c,function(e){return r(c[e])},t)}var V=/*#__PURE__*/function(){function r(e){if(this.mneeApiKey=void 0,this.mneeConfig=void 0,this.mneeApi=void 0,"production"!==e.environment&&"sandbox"!==e.environment)throw f('Invalid environment. Must be either "production" or "sandbox"');var r="production"===e.environment;if(""===(null==e?void 0:e.apiKey))throw f("MNEE API key cannot be an empty string");this.mneeApiKey=null!=e&&e.apiKey?e.apiKey:r?"92982ec1c0975f31979da515d46bae9f":"54f1fd1688ba66a58a67675b82feb93e",this.mneeApi=r?"https://proxy-api.mnee.net":"https://sandbox-proxy-api.mnee.net",this.getCosignerConfig().catch(function(){})}var t=r.prototype;return t.getCosignerConfig=function(){try{var e=this;return Promise.resolve(U(function(){return Promise.resolve(fetch(e.mneeApi+"/v1/config?auth_token="+e.mneeApiKey,{method:"GET"})).then(function(r){if(401===r.status||403===r.status)throw f("Invalid API key");if(!r.ok)throw f("HTTP error! status: "+r.status);return Promise.resolve(r.json()).then(function(r){return e.mneeConfig=r,r})})},function(e){throw T(e)&&x(e,"fetch config"),e}))}catch(e){return Promise.reject(e)}},t.toAtomicAmount=function(e){return Math.round(e*Math.pow(10,5))},t.fromAtomicAmount=function(e){return e/Math.pow(10,5)},t.createInscriptionOutput=function(r,t,n){try{var i={p:"bsv-20",op:"transfer",id:n.tokenId,amt:t.toString()};return Promise.resolve({lockingScript:h((new d).lock(r,e.PublicKey.fromString(n.approver)),{dataB64:Buffer.from(JSON.stringify(i)).toString("base64"),contentType:"application/bsv-20"}),satoshis:1})}catch(e){return Promise.reject(e)}},t.getUtxos=function(e,r,t,n){try{var i,o=this;return Promise.resolve(U(function(){function s(s){var a;if(i)return s;function u(e){if(a)return e;throw f("Invalid input type for address")}var c=function(){if(Array.isArray(e)){var i=e.filter(function(e){return"string"==typeof e&&A(e)});if(0===i.length)throw f("No valid Bitcoin addresses provided");var s=e.filter(function(e){return"string"!=typeof e||!A(e)});return s.length>0&&console.warn("[33m"+s.length+" invalid bitcoin addresses will be ignored[0m"),Promise.resolve(fetch(o.mneeApi+"/v2/utxos?auth_token="+o.mneeApiKey+(void 0!==r?"&page="+r:"")+(void 0!==t?"&size="+t:"")+(n?"&order="+n:""),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})).then(function(e){if(401===e.status||403===e.status)throw f("Invalid API key");if(!e.ok)throw f("HTTP error! status: "+e.status);return Promise.resolve(e.json()).then(function(e){var r=["transfer","deploy+mint"],t=e.filter(function(e){return r.includes(e.data.bsv21.op.toLowerCase())});return a=1,t})})}}();return c&&c.then?c.then(u):u(c)}if(!e)throw f("Address is required");var a=function(){if("string"==typeof e){if(!A(e))throw f("Invalid Bitcoin address: "+e);return Promise.resolve(fetch(o.mneeApi+"/v2/utxos?auth_token="+o.mneeApiKey+(void 0!==r?"&page="+r:"")+(void 0!==t?"&size="+t:"")+(n?"&order="+n:""),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify([e])})).then(function(e){if(401===e.status||403===e.status)throw f("Invalid API key");if(!e.ok)throw f("HTTP error! status: "+e.status);return Promise.resolve(e.json()).then(function(e){var r=["transfer","deploy+mint"],t=e.filter(function(e){return r.includes(e.data.bsv21.op.toLowerCase())});return i=1,t})})}}();return a&&a.then?a.then(s):s(a)},function(e){throw T(e)&&x(e,"fetch UTXOs"),e}))}catch(e){return Promise.reject(e)}},t.fetchSourceTransaction=function(r,t){void 0===t&&(t=3);try{var n,i=this,o=0,s=R(function(){return!n&&o<=t},function(){return o++},function(){return U(function(){return Promise.resolve(fetch(i.mneeApi+"/v1/tx/"+r+"?auth_token="+i.mneeApiKey)).then(function(i){function s(){if(200!==i.status)throw f(i.status+" - Failed to fetch rawtx for txid: "+r);return Promise.resolve(i.json()).then(function(r){var t=e.Transaction.fromHex(Buffer.from(r.rawtx,"base64").toString("hex"));return n=1,t})}if(404===i.status)throw f("Transaction not found");if(401===i.status||403===i.status)throw f("Invalid API key");var a=function(){if(429===i.status&&o<t){var e=Math.min(500*Math.pow(2,o),2e3);return Promise.resolve(new Promise(function(r){return setTimeout(r,e)})).then(function(){})}}();return a&&a.then?a.then(s):s()})},function(e){return o===t?(T(e)&&x(e,"fetch transaction"),void(n=1)):Promise.resolve(new Promise(function(e){return setTimeout(e,200)})).then(function(){})})});return Promise.resolve(s&&s.then?s.then(function(e){return n?e:void 0}):n?s:void 0)}catch(e){return Promise.reject(e)}},t.generateSignatures=function(r,t){try{try{var n;switch(r.format){case"beef":n=e.Transaction.fromHexBEEF(r.rawtx);break;case"ef":n=e.Transaction.fromHexEF(r.rawtx);break;default:n=e.Transaction.fromHex(r.rawtx)}var i=r.sigRequests.flatMap(function(r){return[t].map(function(t){var i=e.TransactionSignature.format({sourceTXID:r.prevTxid,sourceOutputIndex:r.outputIndex,sourceSatoshis:r.satoshis,transactionVersion:n.version,otherInputs:n.inputs.filter(function(e,t){return t!==r.inputIndex}),inputIndex:r.inputIndex,outputs:n.outputs,inputSequence:n.inputs[r.inputIndex].sequence||0,subscript:r.script?e.Script.fromHex(r.script):(new e.P2PKH).lock(t.toPublicKey().toAddress()),lockTime:n.lockTime,scope:r.sigHashType||65}),o=t.sign(e.Hash.sha256(i)),s=new e.TransactionSignature(o.r,o.s,r.sigHashType||65);return{sig:e.Utils.toHex(s.toChecksigFormat()),pubKey:t.toPublicKey().toString(),inputIndex:r.inputIndex,sigHashType:r.sigHashType||65,csIdx:r.csIdx}})});return Promise.resolve({sigResponses:i})}catch(e){var o;return T(e)&&x(e,"get signatures"),Promise.resolve({error:{message:null!=(o=e.message)?o:"unknown",cause:e.cause}})}}catch(e){return Promise.reject(e)}},t.getEnoughUtxos=function(e,r){try{var t=function(t){if(!t)throw f("Config not fetched");var o=t.fees.find(function(e){return r>=e.min&&r<=e.max});if(!o)throw f("Fee not found");var s=o.fee,a=r+s;return Promise.resolve(n.getBalance(e)).then(function(r){var t;function o(e){c.sort(function(e,r){return r.data.bsv21.amt-e.data.bsv21.amt});for(var r,t=[],n=0,o=i(c);!(r=o()).done;){var s=r.value;if(t.push(s),(n+=s.data.bsv21.amt)>=a)break}return t}if(r.amount<a)throw f("Insufficient MNEE balance. Max transfer amount: "+n.fromAtomicAmount(r.amount-s));var u=1,c=[],d=0,l=R(function(){return!t&&d<a},void 0,function(){return Promise.resolve(n.getUtxos(e,u,25)).then(function(e){if(0===e.length)throw f("Insufficient MNEE balance. Max transfer amount: "+n.fromAtomicAmount(d-s));c.push.apply(c,e),(d=c.reduce(function(e,r){return e+r.data.bsv21.amt},0))>=a?t=1:u++})});return l&&l.then?l.then(o):o()})},n=this,o=n.mneeConfig;return Promise.resolve(o?t(o):Promise.resolve(n.getCosignerConfig()).then(t))}catch(e){return Promise.reject(e)}},t.getAllUtxos=function(e){try{var r,t=this,n=1,i=[],o=R(function(){return!r},void 0,function(){return Promise.resolve(t.getUtxos(e,n,100)).then(function(e){0!==e.length?(i.push.apply(i,e),n++):r=1})});return Promise.resolve(o&&o.then?o.then(function(){return i}):i)}catch(e){return Promise.reject(e)}},t.transfer=function(r,t,n){try{var o=this;return Promise.resolve(U(function(){function s(s){if(!s)throw f("Config not fetched");var a=function(e,r){var t=I(r),n=t.privateKey;if(0===e.length)return{isValid:!1,error:"Empty transfer options provided. Please provide at least one recipient."};if(!t.isValid)return{isValid:!1,error:t.error||"Invalid WIF key provided"};if(!n)return{isValid:!1,error:"Private key not found"};for(var o,s=0,a=i(e);!(o=a()).done;){var u=o.value;if(!A(u.address))return{isValid:!1,error:"Invalid recipient address: "+u.address};if("number"!=typeof u.amount||isNaN(u.amount)||!isFinite(u.amount))return{isValid:!1,error:"Invalid amount for "+u.address+": amount must be a valid number"};if(u.amount<v)return{isValid:!1,error:"Invalid amount for "+u.address+": minimum transfer amount is "+v+" MNEE"};s+=u.amount}return s<=0?{isValid:!1,error:"Invalid amount: total must be greater than 0"}:{isValid:!0,totalAmount:s,privateKey:n}}(r,t),u=a.totalAmount,c=a.privateKey;if(!a.isValid)throw f(a.error||"Invalid transfer options");if(!c)throw f("Private key not found");if(!u)throw f("Invalid amount");var d=o.toAtomicAmount(u),l=c.toAddress();return Promise.resolve(o.getEnoughUtxos(l,d)).then(function(t){var i;function a(e){function t(){function e(){function e(){for(var e=new Map,r=0;r<h.inputs.length;r++)e.set(r,c);return Promise.resolve(o.signAllInputs(h,e)).then(function(e){if(e.error)throw f(e.error);var r=h.toHex();return!1===(null==n?void 0:n.broadcast)?{rawtx:r}:Promise.resolve(o.submitRawTx(r,n)).then(function(e){var r=e.ticketId;if(!r)throw f("Failed to broadcast transaction");return{ticketId:r}})})}var r=v-d-u,t=function(){if(r>0){var e=h.addOutput;return Promise.resolve(o.createInscriptionOutput(m,r,s)).then(function(r){e.call(h,r)})}}();return t&&t.then?t.then(e):e()}var r=function(){if(u>0){var e=h.addOutput;return Promise.resolve(o.createInscriptionOutput(s.feeAddress,u,s)).then(function(r){e.call(h,r)})}}();return r&&r.then?r.then(e):e()}var i=q(r,function(e){var r=h.addOutput;return Promise.resolve(o.createInscriptionOutput(e.address,o.toAtomicAmount(e.amount),s)).then(function(e){r.call(h,e)})});return i&&i.then?i.then(t):t()}var u=void 0!==r.find(function(e){return e.address===s.burnAddress})?0:null==(i=s.fees.find(function(e){return d>=e.min&&d<=e.max}))?void 0:i.fee;if(void 0===u)throw f("Fee ranges inadequate");var h=new e.Transaction(1,[],[],0),v=0,m="",p=R(function(){return v<d+u},void 0,function(){function r(r){return Promise.resolve(o.fetchSourceTransaction(n.txid)).then(function(r){if(!r)throw f("Failed to fetch source transaction: "+n.txid+"_"+n.vout);m=m||n.owners[0],h.addInput({sourceTXID:n.txid,sourceOutputIndex:n.vout,sourceTransaction:r,unlockingScript:new e.UnlockingScript}),v+=n.data.bsv21.amt})}var n=t.shift(),i=function(){if(!n)return Promise.resolve(o.getBalance(l)).then(function(e){throw f("Insufficient MNEE balance. Max transfer amount is "+o.fromAtomicAmount(e.amount-u))})}();return i&&i.then?i.then(r):r()});return p&&p.then?p.then(a):a()})}var a=o.mneeConfig;return a?s(a):Promise.resolve(o.getCosignerConfig()).then(s)},function(e){throw T(e)&&x(e,"transfer tokens"),e}))}catch(e){return Promise.reject(e)}},t.submitRawTx=function(r,t){void 0===t&&(t={broadcast:!0,callbackUrl:void 0});try{var n=this;return Promise.resolve(U(function(){var i,s,a,u;if(!1!==(null==(i=t)?void 0:i.broadcast)&&(t=o({},t,{broadcast:!0})),null!=(s=t)&&s.callbackUrl&&!1===(null==(a=t)?void 0:a.broadcast))throw f("Callback URL cannot be provided when broadcast is false");if(!r)throw f("Raw transaction is required");var c=e.Transaction.fromHex(r);if(null==(u=t)||!u.broadcast)return{rawtx:c.toHex()};var d=e.Utils.toBase64(c.toBinary()),l=JSON.stringify(t?{rawtx:d,callback_url:t.callbackUrl}:{rawtx:d});return Promise.resolve(fetch(n.mneeApi+"/v2/transfer?auth_token="+n.mneeApiKey,{method:"POST",headers:{"Content-Type":"application/json"},body:l})).then(function(e){if(!e.ok)throw f("Failed to submit transaction: "+e.status);return Promise.resolve(e.text()).then(function(e){return{ticketId:e}})})},function(e){throw T(e)&&x(e,"submit raw transaction"),e}))}catch(e){return Promise.reject(e)}},t.getTxStatus=function(e){try{var r=this;return Promise.resolve(U(function(){if(!e)throw f("Ticket ID is required");return Promise.resolve(fetch(r.mneeApi+"/v2/ticket?ticketID="+e+"&auth_token="+r.mneeApiKey,{method:"GET",headers:{"Content-Type":"application/json"}})).then(function(e){if(!e.ok)throw f("Failed to get transaction status: "+e.status);return Promise.resolve(e.json())})},function(e){throw T(e)&&x(e,"get transaction status"),e}))}catch(e){return Promise.reject(e)}},t.getBalance=function(e){try{var r=this;if(!A(e))throw f("Invalid Bitcoin address: "+e);return Promise.resolve(U(function(){function t(t){if(!t)throw f("Config not fetched");return Promise.resolve(fetch(r.mneeApi+"/v2/balance?auth_token="+r.mneeApiKey,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify([e])})).then(function(r){if(!r.ok)throw f("Failed to get transaction status: "+r.status);return Promise.resolve(r.json()).then(function(r){return r&&0!==r.length?{address:r[0].address,amount:r[0].amt,decimalAmount:r[0].precised}:{address:e,amount:0,decimalAmount:0}})})}var n=r.mneeConfig;return n?t(n):Promise.resolve(r.getCosignerConfig()).then(t)},function(e){throw T(e)&&x(e,"fetch balance"),e}))}catch(e){return Promise.reject(e)}},t.getBalances=function(e){try{var r=this;if(!Array.isArray(e))throw f("Addresses must be an array");var t=e.filter(function(e){return A(e)});if(0===t.length)throw f("You must pass at least 1 valid address");var n=e.length-t.length;return n>0&&console.warn("[33m"+n+" invalid bitcoin addresses will be ignored[0m"),Promise.resolve(U(function(){function e(e){if(!e)throw f("Config not fetched");return Promise.resolve(fetch(r.mneeApi+"/v2/balance?auth_token="+r.mneeApiKey,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).then(function(e){if(!e.ok)throw f("Failed to get transaction status: "+e.status);return Promise.resolve(e.json()).then(function(e){if(!e||0===e.length)return t.map(function(e){return{address:e,amount:0,decimalAmount:0}});var r=new Map;return e.forEach(function(e){r.set(e.address,{address:e.address,amount:e.amt,decimalAmount:e.precised})}),t.map(function(e){return r.has(e)?r.get(e):{address:e,amount:0,decimalAmount:0}})})})}var n=r.mneeConfig;return n?e(n):Promise.resolve(r.getCosignerConfig()).then(e)},function(e){throw T(e)&&x(e,"fetch balances"),e}))}catch(e){return Promise.reject(e)}},t.processMneeValidation=function(r,t,n){var o=this;try{var s=r.id("hex")===t.tokenId.split("_")[0],a=r.outputs.map(function(e){return e.lockingScript}),u=w(a),c=r.outputs.map(function(r,t){var n,i=u[t],o=P(r.lockingScript),s=null;if(null!=o&&null!=(n=o.file)&&n.content)try{var a=e.Utils.toUTF8(o.file.content);a&&(s=JSON.parse(a))}catch(e){}return{index:t,address:null==i?void 0:i.address,cosigner:null==i?void 0:i.cosigner,inscription:s}}),d=c.some(function(e){return e.cosigner===t.approver});if(c.find(function(e){return""!==e.cosigner&&e.cosigner!==t.approver}))throw f("Invalid cosigner detected");var l=c.filter(function(e){if(!e.inscription)return!1;var r=e.inscription;if("bsv-20"!==r.p)return!1;if(!s&&r.id!==t.tokenId)throw f("Invalid token ID: "+r.id);var n=parseInt(r.amt,10);if(isNaN(n)||n<=0)throw f("Invalid MNEE amount: "+r.amt);return!0});if(0===l.length)throw f("No valid MNEE inscriptions found in transaction");var h=new Set(l.map(function(e){return e.inscription.op})),v=h.has("burn"),m=l.some(function(e){var r;return"transfer"===e.inscription.op&&"redeem"===(null==(r=e.inscription.metadata)?void 0:r.action)}),g=m&&c.some(function(e){return e.address===y||e.address===p});if((h.has("transfer")&&!m||v||m&&!g)&&!d)throw f("Cosigner not found in transaction with transfer/burn/redeem operation");var b=l.filter(function(e){var r=e.inscription;return"transfer"===r.op||"burn"===r.op||"deploy+mint"===r.op});if(n)for(var A,I=[].concat(b),S=function(){var e=A.value,r=I.findIndex(function(r){return r.address===e.address&&r.inscription.amt===o.toAtomicAmount(e.amount).toString()});if(-1===r)throw f("No matching output found for "+e.address+" with amount "+e.amount);I.splice(r,1)},O=i(n);!(A=O()).done;)S();return!0}catch(e){return T(e)&&x(e,"validate Mnee transaction"),!1}},t.validateMneeTx=function(r,t){try{var n=this;return Promise.resolve(U(function(){function i(i){var o;if(!i)throw f("Config not fetched");var s=e.Transaction.fromHex(r);if(!n.processMneeValidation(s,i,t))return!1;var a=s.id("hex")===i.tokenId.split("_")[0],u=function(){if(!a)return Promise.resolve(n.processTransactionInputs(s,i)).then(function(e){var r=n.processTransactionOutputs(s,i);if(e.total!==r.total)return o=1,!1})}();return u&&u.then?u.then(function(e){return!o||e}):!o||u}var o=n.mneeConfig;return o?i(o):Promise.resolve(n.getCosignerConfig()).then(i)},function(e){return T(e)&&x(e,"validate Mnee transaction"),!1}))}catch(e){return Promise.reject(e)}},t.getMneeSyncs=function(e,r,t,n){try{var i=this;return Promise.resolve(U(function(){var o=Array.isArray(e)?e:[e];return Promise.resolve(fetch(i.mneeApi+"/v1/sync?auth_token="+i.mneeApiKey+(r?"&from="+r:"")+(t?"&limit="+t:"")+(n?"&order="+n:""),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).then(function(e){if(401===e.status||403===e.status)throw f("Invalid API key");if(!e.ok)throw f("HTTP error! status: "+e.status);return Promise.resolve(e.json()).then(function(e){return o.map(function(r){var t=e.filter(function(e){return e.senders.includes(r)||e.receivers.includes(r)});return{address:r,syncs:t}})})})},function(e){throw T(e)&&x(e,"fetch syncs"),e}))}catch(e){return Promise.reject(e)}},t.getRecentTxHistory=function(e,r,t,n){try{var o=this;if(!A(e))throw f("Invalid Bitcoin address: "+e);if(void 0!==r&&("number"!=typeof r||r<0||!Number.isFinite(r)))throw f("Invalid fromScore: "+r+". Must be a positive number or 0");if(void 0!==t&&("number"!=typeof t||t<=0||!Number.isInteger(t)))throw f("Invalid limit: "+t+". Must be a positive integer");if(void 0!==n&&"asc"!==n&&"desc"!==n)throw f("Invalid order: "+n+". Must be 'asc' or 'desc'");return Promise.resolve(U(function(){function s(s){if(!s)throw f("Config not fetched");return Promise.resolve(o.getMneeSyncs(e,r,t,n)).then(function(n){var o=n[0].syncs;if(!o||0===o.length)return{address:e,history:[],nextScore:r||0};for(var a,u=[],c=i(o);!(a=c()).done;){var f=b(a.value,e,s);f&&u.push(f)}var d=u.length>0?u[u.length-1].score:r||0;return t&&u.length>t?{address:e,history:u.slice(0,t),nextScore:d}:{address:e,history:u,nextScore:d}})}var a=o.mneeConfig;return a?s(a):Promise.resolve(o.getCosignerConfig()).then(s)},function(e){throw T(e)&&x(e,"fetch transaction history"),e}))}catch(e){return Promise.reject(e)}},t.getRecentTxHistories=function(e){try{var r=this;if(!Array.isArray(e))throw f("Parameters must be an array");if(0===e.length)throw f("You must pass at least 1 address parameter");var t=e.filter(function(e){return e&&e.address&&A(e.address)});if(0===t.length)throw f("You must pass at least 1 valid address");var n=e.length-t.length;n>0&&console.warn("[33m"+n+" invalid bitcoin addresses will be ignored[0m");for(var o,s=i(t);!(o=s()).done;){var a=o.value;if(void 0!==a.fromScore&&("number"!=typeof a.fromScore||a.fromScore<0||!Number.isFinite(a.fromScore)))throw f("Invalid fromScore for address "+a.address+": "+a.fromScore+". Must be a positive number or 0");if(void 0!==a.limit&&("number"!=typeof a.limit||a.limit<=0||!Number.isInteger(a.limit)))throw f("Invalid limit for address "+a.address+": "+a.limit+". Must be a positive integer");if(void 0!==a.order&&"asc"!==a.order&&"desc"!==a.order)throw f("Invalid order for address "+a.address+": "+a.order+". Must be 'asc' or 'desc'")}return Promise.resolve(U(function(){function e(e){if(!e)throw f("Config not fetched");var n={};t.forEach(function(e){var r=(e.fromScore||0)+":"+(e.limit||100)+":"+(e.order||"default");n[r]||(n[r]=[]),n[r].push(e)});var o=Object.entries(n).map(function(t){var n=t[0],o=t[1];try{var s=n.split(":"),a=s[1],u=s[2],c=Number(s[0]),f=Number(a),d="default"===u?void 0:u,l=o.map(function(e){return e.address});return Promise.resolve(r.getMneeSyncs(l,c,f,d)).then(function(r){return r.map(function(r){var t=r.address,n=r.syncs,s=o.find(function(e){return e.address===t});if(!n||0===n.length)return{address:t,history:[],nextScore:(null==s?void 0:s.fromScore)||0};for(var a,u=[],c=new Set,f=i(n);!(a=f()).done;){var d=b(a.value,t,e);d&&!c.has(d.txid)&&(c.add(d.txid),u.push(d))}var l=u.length>0?u[u.length-1].score:(null==s?void 0:s.fromScore)||0,h=null==s?void 0:s.limit;return h&&u.length>h?{address:t,history:u.slice(0,h),nextScore:l}:{address:t,history:u,nextScore:l}})})}catch(e){return Promise.reject(e)}});return Promise.resolve(Promise.all(o)).then(function(e){return e.flat()})}var n=r.mneeConfig;return n?e(n):Promise.resolve(r.getCosignerConfig()).then(e)},function(e){throw T(e)&&x(e,"fetch transaction histories"),e}))}catch(e){return Promise.reject(e)}},t.parseInscriptionData=function(r){try{var t,n=P(r),i=null==n||null==(t=n.file)?void 0:t.content;if(!i)return null;var o=e.Utils.toUTF8(i);return o?JSON.parse(o):null}catch(e){return T(e)&&x(e,"parse inscription data"),null}},t.determineEnvironment=function(e,r,t,n){return e===m.split("_")[0]?"production":e===g.split("_")[0]?"sandbox":r===m&&"020a177d6a5e6f3a8689acd2e313bd1cf0dcf5a243d1cc67b7218602aee9e04b2f"===t?"production":r===g&&"02bed35e894cc41cc9879b4002ad03d33533b615c1b476068c8dd6822a09f93f6c"===t?"sandbox":""===t&&n===p?"production":"sandbox"},t.determineTransactionType=function(e,r,t,n,i){return"burn"===e?"burn":"deploy+mint"===e||r===n?t===i.split("_")[0]?"deploy":"mint":r===p||r===y?"mint":"transfer"},t.processTransactionInputs=function(e,r){try{var t,n,o=this,s=e.id("hex"),a=new Array(e.inputs.length),u=BigInt(0),c=new M(3,334),f=e.inputs.map(function(e,r){try{return Promise.resolve(e.sourceTXID?U(function(){return Promise.resolve(c.execute(function(){return o.fetchSourceTransaction(e.sourceTXID)})).then(function(e){return{index:r,sourceTx:e}})},function(e){return T(e)&&x(e,"fetch source transaction"),{index:r,sourceTx:null}}):{index:r,sourceTx:null})}catch(e){return Promise.reject(e)}});return Promise.resolve(Promise.all(f)).then(function(c){for(var f,d=i(c);!(f=d()).done;){var l=f.value,h=l.index,v=l.sourceTx,m=e.inputs[h];if(v&&m.sourceTXID){var p=v.outputs[m.sourceOutputIndex],g=w([p.lockingScript])[0],y=o.parseInscriptionData(p.lockingScript),P={address:null==g?void 0:g.address,amount:y?parseInt(y.amt):0,satoshis:Number(p.satoshis),inscription:y,cosigner:g};a[h]=P,y&&g&&(u+=BigInt(y.amt),t||(t=o.determineEnvironment(s,y.id,g.cosigner||"",g.address||"")),n||(n=o.determineTransactionType(y.op,g.address||"",s,r.mintAddress,r.tokenId)))}else a[h]={address:void 0,amount:0,satoshis:0,inscription:null,cosigner:void 0}}return{inputs:a,total:u,environment:t,type:n}})}catch(e){return Promise.reject(e)}},t.processTransactionOutputs=function(e,r){for(var t,n,i=e.id("hex"),o=[],s=BigInt(0),a=0;a<e.outputs.length;a++){var u=e.outputs[a],c=w([u.lockingScript])[0],f=this.parseInscriptionData(u.lockingScript),d={address:null==c?void 0:c.address,amount:f?parseInt(f.amt):0,satoshis:Number(u.satoshis),inscription:f,cosigner:c};if(o.push(d),f&&c){s+=BigInt(f.amt),t=this.determineEnvironment(i,f.id,c.cosigner||"",c.address||"");var l=this.determineTransactionType(f.op,c.address||"",i,r.mintAddress,r.tokenId);"burn"===l||"deploy"===l?n=l:n||(n=l)}}return{outputs:o,total:s,environment:t,type:n}},t.validateTransaction=function(e,r,t,n,i){return!!this.processMneeValidation(r,e)&&("deploy"===t||n===i)},t.buildParseResponse=function(e,r,t,n,i,s,a,u){var c={txid:e,environment:r,type:t,inputs:n.inputs.filter(function(e){return e.inscription&&e.address}).map(function(e){return{address:e.address,amount:e.amount}}),outputs:i.outputs.filter(function(e){return e.inscription&&e.address}).map(function(e){return{address:e.address,amount:e.amount}}),isValid:s,inputTotal:n.total.toString(),outputTotal:i.total.toString()};return null!=u&&u.includeRaw?o({},c,{raw:{txHex:a.toHex(),inputs:a.inputs.map(function(e,r){var t,i=n.inputs[r];return{txid:e.sourceTXID||"",vout:e.sourceOutputIndex,scriptSig:(null==(t=e.unlockingScript)?void 0:t.toHex())||"",sequence:e.sequence||4294967295,address:null==i?void 0:i.address,satoshis:(null==i?void 0:i.satoshis)||0,tokenData:null!=i&&i.inscription?{amount:i.amount}:void 0}}),outputs:a.outputs.map(function(e,r){var t=i.outputs[r];return{value:Number(e.satoshis),scriptPubKey:e.lockingScript.toHex(),address:null==t?void 0:t.address,tokenData:null!=t&&t.inscription?{amount:t.amount}:void 0}})}}):c},t.parseTransaction=function(e,r,t){try{var n=this,i=e.id("hex");return Promise.resolve(n.processTransactionInputs(e,r)).then(function(o){var s=n.processTransactionOutputs(e,r),a=s.environment||o.environment||"sandbox",u=s.type||o.type||"transfer";"transfer"===u&&o.inputs.some(function(e){return e.inscription&&(e.address===p||e.address===y)})&&(u="mint"),"transfer"!==u&&"mint"!==u||s.outputs.some(function(e){var r;return"redeem"===(null==(r=e.inscription)||null==(r=r.metadata)?void 0:r.action)})&&(u="redeem"),0===o.inputs.filter(function(e){return e.inscription}).length&&o.inputs.length>0&&(u="deploy");var c=n.validateTransaction(r,e,u,o.total,s.total);return n.buildParseResponse(i,a,u,o,s,c,e,t)})}catch(e){return Promise.reject(e)}},t.parseTx=function(e,r){try{var t=function(t){if(!t)throw f("Config not fetched");return Promise.resolve(n.fetchSourceTransaction(e)).then(function(e){if(!e)throw f("Failed to fetch transaction");return Promise.resolve(n.parseTransaction(e,t,r))})},n=this;if(!e||"string"!=typeof e||""===e.trim()||!/^[a-fA-F0-9]{64}$/.test(e))throw f("A valid transaction ID is required");var i=n.mneeConfig;return Promise.resolve(i?t(i):Promise.resolve(n.getCosignerConfig()).then(t))}catch(e){return Promise.reject(e)}},t.parseTxFromRawTx=function(r,t){try{var n=function(e){if(!e)throw f("Config not fetched");return Promise.resolve(i.parseTransaction(o,e,t))},i=this;if(!r||"string"!=typeof r||""===r.trim())throw f("A valid raw transaction is required");if(!function(r){try{return e.Transaction.fromHex(r),!0}catch(e){return!1}}(r))throw f("Invalid raw transaction hex");var o=e.Transaction.fromHex(r),s=i.mneeConfig;return Promise.resolve(s?n(s):Promise.resolve(i.getCosignerConfig()).then(n))}catch(e){return Promise.reject(e)}},t.parseInscription=function(e){return P(e)},t.parseCosignerScripts=function(e){return w(e)},t.validateUniqueInputs=function(e){for(var r,t=new Set,n=i(e);!(r=n()).done;){var o=r.value,s=o.txid+":"+o.vout;if(t.has(s))return{error:"Duplicate input detected: "+s+". Each UTXO can only be spent once."};t.add(s)}return{}},t.addInputsToTransaction=function(r,t,n){try{var i,o=function(e){return i?e:{tokensIn:a}},s=this,a=0,u=B(t,function(o){var u=t[o];return Promise.resolve(s.fetchSourceTransaction(u.txid)).then(function(t){if(!t)return i=1,{tokensIn:0,error:"Failed to fetch source transaction: "+u.txid+"_"+u.vout};var c=t.outputs[u.vout];if(!c)return i=1,{tokensIn:0,error:"Output "+u.vout+" not found in transaction "+u.txid};var f=s.parseInscriptionData(c.lockingScript);if(!f)return i=1,{tokensIn:0,error:"No inscription found in output "+u.txid+":"+u.vout};var d=parseInt(f.amt);a+=d,n.set(o,e.PrivateKey.fromWif(u.wif)),r.addInput({sourceTXID:u.txid,sourceOutputIndex:u.vout,sourceTransaction:t,unlockingScript:new e.UnlockingScript}