mnee
Version:
A simple package for interacting with the MNEE USD
3 lines (2 loc) • 26.9 kB
JavaScript
var r=require("@bsv/sdk");function e(r,e){(null==e||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function t(r,t){var n="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(n)return(n=n.call(r)).next.bind(n);if(Array.isArray(r)||(n=function(r,t){if(r){if("string"==typeof r)return e(r,t);var n={}.toString.call(r).slice(8,-1);return"Object"===n&&r.constructor&&(n=r.constructor.name),"Map"===n||"Set"===n?Array.from(r):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?e(r,t):void 0}}(r))||t&&r&&"number"==typeof r.length){n&&(r=n);var o=0;return function(){return o>=r.length?{done:!0}:{done:!1,value:r[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n=/*#__PURE__*/function(){function e(){}var t=e.prototype;return t.lock=function(e,t){var n=[];if("string"==typeof e){var o=r.Utils.fromBase58Check(e);if(0!==o.prefix[0]&&111!==o.prefix[0])throw new Error("only P2PKH is supported");n=o.data}else n=e;var i=new r.LockingScript;return i.writeOpCode(r.OP.OP_DUP).writeOpCode(r.OP.OP_HASH160).writeBin(n).writeOpCode(r.OP.OP_EQUALVERIFY).writeOpCode(r.OP.OP_CHECKSIGVERIFY).writeBin(t.encode(!0)).writeOpCode(r.OP.OP_CHECKSIG),i},t.userUnlock=function(e,t,n,o,i){return void 0===t&&(t="all"),void 0===n&&(n=!1),{sign:function(s,a){try{var u,c,f,d=r.TransactionSignature.SIGHASH_FORKID;"all"===t&&(d|=r.TransactionSignature.SIGHASH_ALL),"none"===t&&(d|=r.TransactionSignature.SIGHASH_NONE),"single"===t&&(d|=r.TransactionSignature.SIGHASH_SINGLE),n&&(d|=r.TransactionSignature.SIGHASH_ANYONECANPAY);var l=s.inputs[a],h=s.inputs.filter(function(r,e){return e!==a}),v=l.sourceTXID?l.sourceTXID:null==(u=l.sourceTransaction)?void 0:u.id("hex");if(!v)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(o||(o=null==(c=l.sourceTransaction)?void 0:c.outputs[l.sourceOutputIndex].satoshis),!o)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(i||(i=null==(f=l.sourceTransaction)?void 0:f.outputs[l.sourceOutputIndex].lockingScript),!i)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");var p=r.TransactionSignature.format({sourceTXID:v,sourceOutputIndex:l.sourceOutputIndex,sourceSatoshis:o,transactionVersion:s.version,otherInputs:h,inputIndex:a,outputs:s.outputs,inputSequence:l.sequence||4294967295,subscript:i,lockTime:s.lockTime,scope:d}),m=e.sign(r.Hash.sha256(p)),g=new r.TransactionSignature(m.r,m.s,d),P=new r.UnlockingScript;return P.writeBin(g.toChecksigFormat()),P.writeBin(e.toPublicKey().encode(!0)),Promise.resolve(P)}catch(r){return Promise.reject(r)}},estimateLength:function(){return Promise.resolve(182)}}},t.unlock=function(e,t,n,o,i,s){return void 0===n&&(n="all"),void 0===o&&(o=!1),{sign:function(a,u){try{var c,f,d,l=r.TransactionSignature.SIGHASH_FORKID;"all"===n&&(l|=r.TransactionSignature.SIGHASH_ALL),"none"===n&&(l|=r.TransactionSignature.SIGHASH_NONE),"single"===n&&(l|=r.TransactionSignature.SIGHASH_SINGLE),o&&(l|=r.TransactionSignature.SIGHASH_ANYONECANPAY);var h=a.inputs[u],v=a.inputs.filter(function(r,e){return e!==u}),p=h.sourceTXID?h.sourceTXID:null==(c=h.sourceTransaction)?void 0:c.id("hex");if(!p)throw new Error("The input sourceTXID or sourceTransaction is required for transaction signing.");if(i||(i=null==(f=h.sourceTransaction)?void 0:f.outputs[h.sourceOutputIndex].satoshis),!i)throw new Error("The sourceSatoshis or input sourceTransaction is required for transaction signing.");if(s||(s=null==(d=h.sourceTransaction)?void 0:d.outputs[h.sourceOutputIndex].lockingScript),!s)throw new Error("The lockingScript or input sourceTransaction is required for transaction signing.");var m=r.TransactionSignature.format({sourceTXID:p,sourceOutputIndex:h.sourceOutputIndex,sourceSatoshis:i,transactionVersion:a.version,otherInputs:v,inputIndex:u,outputs:a.outputs,inputSequence:h.sequence||4294967295,subscript:s,lockTime:a.lockTime,scope:l}),g=e.sign(r.Hash.sha256(m)),P=new r.TransactionSignature(g.r,g.s,l),y=new r.UnlockingScript;return y.writeBin(P.toChecksigFormat()),y.writeScript(t),Promise.resolve(y)}catch(r){return Promise.reject(r)}},estimateLength:function(){return Promise.resolve(182)}}},e}(),o=function(r){return Buffer.from(r).toString("hex")},i=function(e,t,n,i){void 0===i&&(i=!1);var s="";if(void 0!==(null==t?void 0:t.dataB64)&&void 0!==(null==t?void 0:t.contentType)){var a=o("ord"),u=Buffer.from(t.dataB64,"base64").toString("hex").trim();if(!u)throw new Error("Invalid file data");var c=o(t.contentType);if(!c)throw new Error("Invalid media type");s="OP_0 OP_IF "+a+" OP_1 "+c+" OP_0 "+u+" OP_ENDIF"}var f=(s?s+" "+(i?"OP_CODESEPARATOR ":""):"")+e.toASM();if(n&&(!n.app||!n.type))throw new Error("MAP.app and MAP.type are required fields");if(null!=n&&n.app&&null!=n&&n.type){f=(f?f+" ":"")+"OP_RETURN "+o("1PuQa7K62MiKCtssSLKy1kh56WWU7MtUR5")+" "+o("SET");for(var d=0,l=Object.entries(n);d<l.length;d++){var h=l[d],v=h[0],p=h[1];"cmd"!==v&&(f=f+" "+o(v)+" "+o(p))}}return r.LockingScript.fromASM(f)},s=function(e){for(var t,n,o,i=0;i<e.chunks.length;i++){var s,a=e.chunks[i];i>=2&&3===(null==(s=a.data)?void 0:s.length)&&"ord"==r.Utils.toUTF8(a.data)&&e.chunks[i-1].op==r.OP.OP_IF&&e.chunks[i-2].op==r.OP.OP_FALSE&&(o=i+1)}if(void 0!==o){for(var u={file:{hash:"",size:0,type:""},fields:{}},c=o;c<e.chunks.length;c+=2){var f,d,l=e.chunks[c];if(l.op==r.OP.OP_ENDIF)break;if(l.op>r.OP.OP_16)return;var h=e.chunks[c+1];if(h.op>r.OP.OP_PUSHDATA4)return;if(null==(f=l.data)||!f.length){var v=0;switch(l.op>r.OP.OP_PUSHDATA4&&l.op<=r.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=r.Utils.toBase64(r.Hash.sha256(h.data)),u.file.content=h.data;break;case 1:u.file.type=Buffer.from(h.data||[]).toString()}}}return u}},a=function(e){return e.map(function(e){for(var t=e.chunks,n=0;n<=t.length-4;n++){var o,i,s;if(t.length>n+6&&t[0+n].op===r.OP.OP_DUP&&t[1+n].op===r.OP.OP_HASH160&&20===(null==(o=t[2+n].data)?void 0:o.length)&&t[3+n].op===r.OP.OP_EQUALVERIFY&&t[4+n].op===r.OP.OP_CHECKSIGVERIFY&&33===(null==(i=t[5+n].data)?void 0:i.length)&&t[6+n].op===r.OP.OP_CHECKSIG)return{cosigner:r.Utils.toHex(t[5+n].data||[]),address:r.Utils.toBase58Check(t[2+n].data||[],[0])};if(t[0+n].op===r.OP.OP_DUP&&t[1+n].op===r.OP.OP_HASH160&&20===(null==(s=t[2+n].data)?void 0:s.length)&&t[3+n].op===r.OP.OP_EQUALVERIFY&&t[4+n].op===r.OP.OP_CHECKSIG)return{cosigner:"",address:r.Utils.toBase58Check(t[2+n].data||[],[0])}}})},u=function(e,t,n){var o=e.senders.includes(t)?"send":"receive",i=e.height>0?"confirmed":"unconfirmed";if(!e.rawtx)return null;var u=r.Utils.toArray(e.rawtx,"base64"),c=r.Utils.toHex(u),f=r.Transaction.fromHex(c).outputs.map(function(r){return r.lockingScript}),d=a(f),l=f.map(s),h=d.map(function(r){return r.address}),v=h.indexOf(n.feeAddress),p=e.senders[0],m=0,g=new Map;l.forEach(function(e,o){var i,s=null==e||null==(i=e.file)?void 0:i.content;if(s){var a=r.Utils.toUTF8(s);if(a){var u;try{u=JSON.parse(a)}catch(r){return void console.error("Failed to parse inscription JSON:",r)}if("bsv-20"===u.p&&u.id===n.tokenId){var c=parseInt(u.amt,10);if(!Number.isNaN(c))if(v!==o||p!==t){var f=h[o],d=g.get(f)||0;g.set(f,d+c)}else m+=c}}}});var P=g.get(t)||0;if("send"===o){var y=g.get(p)||0;g.set(p,y-P)}var S=[],w=(S="receive"===o?[{address:p,amount:P}]:Array.from(g.entries()).map(function(r){return{address:r[0],amount:r[1]}}).filter(function(r){return r.address!==t&&r.address!==n.feeAddress&&r.amount>0})).reduce(function(r,e){return r+e.amount},0);return{txid:e.txid,height:e.height,type:o,status:i,amount:w,fee:m,score:e.score,counterparties:S}},c="ae59f3b898ec61acbdb6cc7a245fabeded0c094bf046f35206a3aec60ef88127_0",f="020a177d6a5e6f3a8689acd2e313bd1cf0dcf5a243d1cc67b7218602aee9e04b2f",d="1inHbiwj2jrEcZPiSYnfgJ8FmS1Bmk4Dh",l="833a7720966a2a435db28d967385e8aa7284b6150ebb39482cc5228b73e1703f_0",h="55cde0733049a226fdb6abc387ee9dcd036e859f7cbc69ab90050c0435139f00_0",v="833a7720966a2a435db28d967385e8aa7284b6150ebb39482cc5228b73e1703f_0";function p(r,e){try{var t=r()}catch(r){return e(r)}return t&&t.then?t.then(void 0,e):t}function m(r,e,t){if(!r.s){if(t instanceof g){if(!t.s)return void(t.o=m.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(m.bind(null,r,e),m.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var g=/*#__PURE__*/function(){function r(){}return r.prototype.then=function(e,t){var n=new r,o=this.s;if(o){var i=1&o?e:t;if(i){try{m(n,1,i(this.v))}catch(r){m(n,2,r)}return n}return this}return this.o=function(r){try{var o=r.v;1&r.s?m(n,1,e?e(o):o):t?m(n,1,t(o)):m(n,2,o)}catch(r){m(n,2,r)}},n},r}();function P(r){return r instanceof g&&1&r.s}var y="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function S(r,e,t){if("function"==typeof r[y]){var n,o,i,s=function(r){try{for(;!((n=a.next()).done||t&&t());)if((r=e(n.value))&&r.then){if(!P(r))return void r.then(s,i||(i=m.bind(null,o=new g,2)));r=r.v}o?m(o,1,r):o=r}catch(r){m(o||(o=new g),2,r)}},a=r[y]();if(s(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(o&&o.then)return o.then(u,function(r){throw u(r)});u()}return o}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,o,i=-1;return function s(a){try{for(;++i<r.length&&(!t||!t());)if((a=e(i))&&a.then){if(!P(a))return void a.then(s,o||(o=m.bind(null,n=new g,2)));a=a.v}n?m(n,1,a):n=a}catch(r){m(n||(n=new g),2,r)}}(),n}(c,function(r){return e(c[r])},t)}var w=/*#__PURE__*/function(){function e(r){if(this.mneeApiKey=void 0,this.mneeConfig=void 0,this.mneeApi=void 0,"production"!==r.environment&&"sandbox"!==r.environment)throw new Error('Invalid environment. Must be either "production" or "sandbox"');var e="production"===r.environment;this.mneeApiKey=null!=r&&r.apiKey?r.apiKey:e?"92982ec1c0975f31979da515d46bae9f":"54f1fd1688ba66a58a67675b82feb93e",this.mneeApi=e?"https://proxy-api.mnee.net":"https://sandbox-proxy-api.mnee.net",this.getCosignerConfig()}var o=e.prototype;return o.getCosignerConfig=function(){try{var r=this;return Promise.resolve(p(function(){return Promise.resolve(fetch(r.mneeApi+"/v1/config?auth_token="+r.mneeApiKey,{method:"GET"})).then(function(e){if(!e.ok)throw new Error("HTTP error! status: "+e.status);return Promise.resolve(e.json()).then(function(e){return r.mneeConfig=e,e})})},function(r){console.error("Failed to fetch config:",r)}))}catch(r){return Promise.reject(r)}},o.toAtomicAmount=function(r){if(!this.mneeConfig)throw new Error("Config not fetched");return Math.round(r*Math.pow(10,this.mneeConfig.decimals))},o.fromAtomicAmount=function(r){if(!this.mneeConfig)throw new Error("Config not fetched");return r/Math.pow(10,this.mneeConfig.decimals)},o.createInscription=function(e,t,o){try{var s={p:"bsv-20",op:"transfer",id:o.tokenId,amt:t.toString()};return Promise.resolve({lockingScript:i((new n).lock(e,r.PublicKey.fromString(o.approver)),{dataB64:Buffer.from(JSON.stringify(s)).toString("base64"),contentType:"application/bsv-20"}),satoshis:1})}catch(r){return Promise.reject(r)}},o.getUtxos=function(r,e){void 0===e&&(e=["transfer","deploy+mint"]);try{var t=this;return Promise.resolve(p(function(){var n=Array.isArray(r)?r:[r];return Promise.resolve(fetch(t.mneeApi+"/v1/utxos?auth_token="+t.mneeApiKey,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).then(function(r){if(!r.ok)throw new Error("HTTP error! status: "+r.status);return Promise.resolve(r.json()).then(function(r){return e.length?r.filter(function(r){return e.includes(r.data.bsv21.op.toLowerCase())}):r})})},function(r){return console.error("Failed to fetch UTXOs:",r),[]}))}catch(r){return Promise.reject(r)}},o.fetchRawTx=function(e){try{return Promise.resolve(fetch(this.mneeApi+"/v1/tx/"+e+"?auth_token="+this.mneeApiKey)).then(function(t){if(404===t.status)throw new Error("Transaction not found");if(200!==t.status)throw new Error(t.status+" - Failed to fetch rawtx for txid: "+e);return Promise.resolve(t.json()).then(function(e){return r.Transaction.fromHex(Buffer.from(e.rawtx,"base64").toString("hex"))})})}catch(r){return Promise.reject(r)}},o.getSignatures=function(e,t){try{try{var n;switch(e.format){case"beef":n=r.Transaction.fromHexBEEF(e.rawtx);break;case"ef":n=r.Transaction.fromHexEF(e.rawtx);break;default:n=r.Transaction.fromHex(e.rawtx)}var o=e.sigRequests.flatMap(function(e){return[t].map(function(t){var o=r.TransactionSignature.format({sourceTXID:e.prevTxid,sourceOutputIndex:e.outputIndex,sourceSatoshis:e.satoshis,transactionVersion:n.version,otherInputs:n.inputs.filter(function(r,t){return t!==e.inputIndex}),inputIndex:e.inputIndex,outputs:n.outputs,inputSequence:n.inputs[e.inputIndex].sequence||0,subscript:e.script?r.Script.fromHex(e.script):(new r.P2PKH).lock(t.toPublicKey().toAddress()),lockTime:n.lockTime,scope:e.sigHashType||65}),i=t.sign(r.Hash.sha256(o)),s=new r.TransactionSignature(i.r,i.s,e.sigHashType||65);return{sig:r.Utils.toHex(s.toChecksigFormat()),pubKey:t.toPublicKey().toString(),inputIndex:e.inputIndex,sigHashType:e.sigHashType||65,csIdx:e.csIdx}})});return Promise.resolve({sigResponses:o})}catch(r){var i;return console.error("getSignatures error",r),Promise.resolve({error:{message:null!=(i=r.message)?i:"unknown",cause:r.cause}})}}catch(r){return Promise.reject(r)}},o.transfer=function(e,n){try{var o=this;return Promise.resolve(p(function(){function i(i){if(!i)throw new Error("Config not fetched");var s=e.reduce(function(r,e){return r+e.amount},0);if(s<=0)return{error:"Invalid amount"};var a=o.toAtomicAmount(s),u=r.PrivateKey.fromWif(n),c=u.toAddress();return Promise.resolve(o.getUtxos(c)).then(function(n){var s,c;function f(n){if(c)return n;function s(){function e(){function e(){var e=l.inputs.map(function(e,t){var n,o;if(!e.sourceTXID)throw new Error("Source TXID is undefined");return{prevTxid:e.sourceTXID,outputIndex:e.sourceOutputIndex,inputIndex:t,address:v[t],script:null==(n=e.sourceTransaction)?void 0:n.outputs[e.sourceOutputIndex].lockingScript.toHex(),satoshis:(null==(o=e.sourceTransaction)?void 0:o.outputs[e.sourceOutputIndex].satoshis)||1,sigHashType:r.TransactionSignature.SIGHASH_ALL|r.TransactionSignature.SIGHASH_ANYONECANPAY|r.TransactionSignature.SIGHASH_FORKID}}),n=l.toHex();return Promise.resolve(o.getSignatures({rawtx:n,sigRequests:e},u)).then(function(e){if(null==e||!e.sigResponses)return{error:"Failed to get signatures"};for(var n,i=t(e.sigResponses);!(n=i()).done;){var s=n.value;l.inputs[s.inputIndex].unlockingScript=(new r.Script).writeBin(r.Utils.toArray(s.sig,"hex")).writeBin(r.Utils.toArray(s.pubKey,"hex"))}var a=r.Utils.toBase64(l.toBinary());return Promise.resolve(fetch(o.mneeApi+"/v1/transfer?auth_token="+o.mneeApiKey,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rawtx:a})})).then(function(e){if(!e.ok)throw new Error("HTTP error! status: "+e.status);return Promise.resolve(e.json()).then(function(e){var t=e.rawtx;if(!t)return{error:"Failed to broadcast transaction"};var n=r.Utils.toArray(t,"base64");return{txid:r.Transaction.fromBinary(n).id("hex"),rawtx:r.Utils.toHex(n)}})})})}var n=h-a-d,s=function(){if(n>0){var r=l.addOutput;return Promise.resolve(o.createInscription(p,n,i)).then(function(e){r.call(l,e)})}}();return s&&s.then?s.then(e):e()}var n=function(){if(d>0){var r=l.addOutput;return Promise.resolve(o.createInscription(i.feeAddress,d,i)).then(function(e){r.call(l,e)})}}();return n&&n.then?n.then(e):e()}var f=S(e,function(r){var e=l.addOutput;return Promise.resolve(o.createInscription(r.address,o.toAtomicAmount(r.amount),i)).then(function(r){e.call(l,r)})});return f&&f.then?f.then(s):s()}if(n.reduce(function(r,e){return r+(e.data.bsv21.amt||0)},0)<a)return{error:"Insufficient MNEE balance"};var d=void 0!==e.find(function(r){return r.address===i.burnAddress})?0:null==(s=i.fees.find(function(r){return a>=r.min&&a<=r.max}))?void 0:s.fee;if(void 0===d)return{error:"Fee ranges inadequate"};var l=new r.Transaction(1,[],[],0),h=0,v=[],p="",y=function(r,e,t){for(var n;;){var o=r();if(P(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!P(i)){n=1;break}i=i.s}}var s=new g,a=m.bind(null,s,2);return(0===n?o.then(c):1===n?i.then(u):(void 0).then(function(){(o=r())?o.then?o.then(c).then(void 0,a):c(o):m(s,1,i)})).then(void 0,a),s;function u(e){i=e;do{if(!(o=r())||P(o)&&!o.v)return void m(s,1,i);if(o.then)return void o.then(c).then(void 0,a);P(i=t())&&(i=i.v)}while(!i||!i.then);i.then(u).then(void 0,a)}function c(r){r?(i=t())&&i.then?i.then(u).then(void 0,a):u(i):m(s,1,i)}}(function(){return!c&&h<a+d},0,function(){var e=n.shift();return e?Promise.resolve(o.fetchRawTx(e.txid)).then(function(t){if(!t)return c=1,{error:"Failed to fetch source transaction"};v.push(e.owners[0]),p=p||e.owners[0],l.addInput({sourceTXID:e.txid,sourceOutputIndex:e.vout,sourceTransaction:t,unlockingScript:new r.UnlockingScript}),h+=e.data.bsv21.amt}):(c=1,{error:"Insufficient MNEE balance"})});return y&&y.then?y.then(f):f(y)})}var s=o.mneeConfig;return s?i(s):Promise.resolve(o.getCosignerConfig()).then(i)},function(r){var e="Transaction submission failed";return r instanceof Error&&(e=r.message,r.message.includes("HTTP error")&&console.error("HTTP error details:",r)),console.error("Failed to transfer tokens:",e),{error:e}}))}catch(r){return Promise.reject(r)}},o.getBalance=function(r){try{var e=this;return Promise.resolve(p(function(){function t(t){if(!t)throw new Error("Config not fetched");return Promise.resolve(e.getUtxos(r)).then(function(t){var n=t.reduce(function(r,e){return"transfer"===e.data.bsv21.op&&(r+=e.data.bsv21.amt),r},0),o=e.fromAtomicAmount(n);return{address:r,amount:n,decimalAmount:o}})}var n=e.mneeConfig;return n?t(n):Promise.resolve(e.getCosignerConfig()).then(t)},function(e){return console.error("Failed to fetch balance:",e),{address:r,amount:0,decimalAmount:0}}))}catch(r){return Promise.reject(r)}},o.getBalances=function(r){try{var e=this;return Promise.resolve(p(function(){function t(t){if(!t)throw new Error("Config not fetched");return Promise.resolve(e.getUtxos(r)).then(function(t){return r.map(function(r){var n=t.filter(function(e){return e.owners.includes(r)}).reduce(function(r,e){return"transfer"===e.data.bsv21.op&&(r+=e.data.bsv21.amt),r},0);return{address:r,amount:n,decimalAmount:e.fromAtomicAmount(n)}})})}var n=e.mneeConfig;return n?t(n):Promise.resolve(e.getCosignerConfig()).then(t)},function(e){return console.error("Failed to fetch balances:",e),r.map(function(r){return{address:r,amount:0,decimalAmount:0}})}))}catch(r){return Promise.reject(r)}},o.validateMneeTx=function(e,t){try{var n=this;return Promise.resolve(p(function(){function o(o){if(!o)throw new Error("Config not fetched");var i=r.Transaction.fromHex(e),u=i.outputs.map(function(r){return r.lockingScript}),c=a(u);return t?t.forEach(function(e,t){var a,u=e.address,f=e.amount;if(!c.find(function(r){return(null==r?void 0:r.cosigner)===o.approver}))throw new Error("Cosigner not found for address: "+u+" at index: "+t);if(!c.find(function(r){return(null==r?void 0:r.address)===u}))throw new Error("Address not found in script for address: "+u+" at index: "+t);var d=s(i.outputs[t].lockingScript),l=null==d||null==(a=d.file)?void 0:a.content;if(!l)throw new Error("Invalid inscription content");var h=r.Utils.toUTF8(l);if(!h)throw new Error("Invalid inscription content");var v=JSON.parse(h);if("bsv-20"!==v.p)throw new Error("Invalid bsv 20 protocol: "+v.p);if("transfer"!==v.op)throw new Error("Invalid operation: "+v.op);if(v.id!==o.tokenId)throw new Error("Invalid token id: "+v.id);if(v.amt!==n.toAtomicAmount(f).toString())throw new Error("Invalid amount: "+v.amt)}):c.forEach(function(r){if(""!==(null==r?void 0:r.cosigner)&&(null==r?void 0:r.cosigner)!==o.approver)throw new Error("Invalid or missing cosigner")}),!0}var i=n.mneeConfig;return i?o(i):Promise.resolve(n.getCosignerConfig()).then(o)},function(r){return console.error(r),!1}))}catch(r){return Promise.reject(r)}},o.getMneeSyncs=function(r,e,t){void 0===e&&(e=0),void 0===t&&(t=100);try{var n=this;return Promise.resolve(p(function(){var o=Array.isArray(r)?r:[r];return Promise.resolve(fetch(n.mneeApi+"/v1/sync?auth_token="+n.mneeApiKey+"&from="+e+"&limit="+t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).then(function(r){if(!r.ok)throw new Error("HTTP error! status: "+r.status);return Promise.resolve(r.json()).then(function(r){return o.map(function(e){var t=r.filter(function(r){return r.senders.includes(e)||r.receivers.includes(e)});return{address:e,syncs:t}})})})},function(e){return console.error("Failed to fetch syncs:",e),Array.isArray(r)?r.map(function(r){return{address:r,syncs:[]}}):[{address:r,syncs:[]}]}))}catch(r){return Promise.reject(r)}},o.getRecentTxHistory=function(r,e,n){try{var o=this;return Promise.resolve(p(function(){function i(i){if(!i)throw new Error("Config not fetched");return Promise.resolve(o.getMneeSyncs(r,e,n)).then(function(o){var s=o[0].syncs;if(!s||0===s.length)return{address:r,history:[],nextScore:e||0};for(var a,c=[],f=t(s);!(a=f()).done;){var d=u(a.value,r,i);d&&c.push(d)}var l=c.length>0?c[c.length-1].score:e||0;return n&&c.length>n?{address:r,history:c.slice(0,n),nextScore:l}:{address:r,history:c,nextScore:l}})}var s=o.mneeConfig;return s?i(s):Promise.resolve(o.getCosignerConfig()).then(i)},function(t){return console.error("Failed to fetch tx history:",t),{address:r,history:[],nextScore:e||0}}))}catch(r){return Promise.reject(r)}},o.getRecentTxHistories=function(r){try{var e=this;return Promise.resolve(p(function(){function n(n){if(!n)throw new Error("Config not fetched");var o={};r.forEach(function(r){var e=(r.fromScore||0)+":"+(r.limit||100);o[e]||(o[e]=[]),o[e].push(r)});var i=Object.entries(o).map(function(r){var o=r[0],i=r[1];try{var s=o.split(":").map(Number),a=s[0],c=s[1],f=i.map(function(r){return r.address});return Promise.resolve(e.getMneeSyncs(f,a,c)).then(function(r){return r.map(function(r){var e=r.address,o=r.syncs,s=i.find(function(r){return r.address===e});if(!o||0===o.length)return{address:e,history:[],nextScore:(null==s?void 0:s.fromScore)||0};for(var a,c=[],f=t(o);!(a=f()).done;){var d=u(a.value,e,n);d&&c.push(d)}var l=c.length>0?c[c.length-1].score:(null==s?void 0:s.fromScore)||0,h=null==s?void 0:s.limit;return h&&c.length>h?{address:e,history:c.slice(0,h),nextScore:l}:{address:e,history:c,nextScore:l}})})}catch(r){return Promise.reject(r)}});return Promise.resolve(Promise.all(i)).then(function(r){return r.flat()})}var o=e.mneeConfig;return o?n(o):Promise.resolve(e.getCosignerConfig()).then(n)},function(e){return console.error("Failed to fetch tx histories:",e),r.map(function(r){return{address:r.address,history:[],nextScore:r.fromScore||0}})}))}catch(r){return Promise.reject(r)}},o.parseTransaction=function(e,n){try{var o=function(){for(var e,n=t(p);!(e=n()).done;){var o,i=e.value,m=a([i])[0],S=s(i),b=null==S||null==(o=S.file)?void 0:o.content;if(b){var A=r.Utils.toUTF8(b);if(A){var I=JSON.parse(A);I&&("burn"===I.op&&(x="burn"),"deploy+mint"===I.op&&(x="deploy"),I.id===c&&m.cosigner===f||(T=""===m.cosigner&&m.address===d?"production":"sandbox"),w+=BigInt(I.amt),P.push({address:m.address,amount:parseInt(I.amt)}))}}}if("deploy"!==x&&y!==w)throw new Error("Inputs and outputs are not equal");return u===c.split("_")[0]?T="production":[l,h,v].some(function(r){return u===r.split("_")[0]})&&(T="sandbox"),{txid:u,environment:T,type:x,inputs:g,outputs:P}},i=this,u=e.id("hex"),p=e.outputs.map(function(r){return r.lockingScript}),m=e.inputs.map(function(r){return{txid:r.sourceTXID,vout:r.sourceOutputIndex}}),g=[],P=[],y=0n,w=0n,T="production",x="transfer",b=S(m,function(e){if(e.txid)return Promise.resolve(i.fetchRawTx(e.txid)).then(function(t){var o,i=t.outputs[e.vout],l=a([i.lockingScript])[0];(null==l?void 0:l.address)===n.mintAddress&&(x=u===n.tokenId.split("_")[0]?"deploy":"mint");var h=s(i.lockingScript),v=null==h||null==(o=h.file)?void 0:o.content;if(v){var p=r.Utils.toUTF8(v);if(p){var m=JSON.parse(p);if(m){var P=l.address===d;m.id===c&&l.cosigner===f||(""===l.cosigner&&"deploy+mint"===m.op&&P?(T="production",x="mint"):T="sandbox"),"transfer"===x&&(P||"1A1QNEkLuvAALsmG4Me3iubP8zb5C6jpv5"===l.address||"1BW7cejD27vDLiHsbK1Hvf1y4JTKvC1Yue"===l.address||"1AZNdbFYBDFTAEgzZMfPzANxyNrpGJZAUY"===l.address)&&(x="mint"),y+=BigInt(m.amt),g.push({address:l.address,amount:parseInt(m.amt)})}}}})});return Promise.resolve(b&&b.then?b.then(o):o())}catch(r){return Promise.reject(r)}},o.parseTx=function(r){try{var e=function(e){if(!e)throw new Error("Config not fetched");return Promise.resolve(t.fetchRawTx(r)).then(function(r){if(!r)throw new Error("Failed to fetch transaction");return Promise.resolve(t.parseTransaction(r,e))})},t=this,n=t.mneeConfig;return Promise.resolve(n?e(n):Promise.resolve(t.getCosignerConfig()).then(e))}catch(r){return Promise.reject(r)}},o.parseTxFromRawTx=function(e){try{var t=function(r){if(!r)throw new Error("Config not fetched");return Promise.resolve(n.parseTransaction(o,r))},n=this,o=r.Transaction.fromHex(e),i=n.mneeConfig;return Promise.resolve(i?t(i):Promise.resolve(n.getCosignerConfig()).then(t))}catch(r){return Promise.reject(r)}},e}();module.exports=/*#__PURE__*/function(){function r(r){this.service=void 0,this.service=new w(r)}var e=r.prototype;return e.validateMneeTx=function(r,e){try{return Promise.resolve(this.service.validateMneeTx(r,e))}catch(r){return Promise.reject(r)}},e.toAtomicAmount=function(r){return this.service.toAtomicAmount(r)},e.fromAtomicAmount=function(r){return this.service.fromAtomicAmount(r)},e.config=function(){try{return Promise.resolve(this.service.getCosignerConfig())}catch(r){return Promise.reject(r)}},e.balance=function(r){try{return Promise.resolve(this.service.getBalance(r))}catch(r){return Promise.reject(r)}},e.balances=function(r){try{return Promise.resolve(this.service.getBalances(r))}catch(r){return Promise.reject(r)}},e.transfer=function(r,e){try{return Promise.resolve(this.service.transfer(r,e))}catch(r){return Promise.reject(r)}},e.recentTxHistory=function(r,e,t){try{return Promise.resolve(this.service.getRecentTxHistory(r,e,t))}catch(r){return Promise.reject(r)}},e.recentTxHistories=function(r){try{return Promise.resolve(this.service.getRecentTxHistories(r))}catch(r){return Promise.reject(r)}},e.parseTx=function(r){try{return Promise.resolve(this.service.parseTx(r))}catch(r){return Promise.reject(r)}},e.parseTxFromRawTx=function(r){try{return Promise.resolve(this.service.parseTxFromRawTx(r))}catch(r){return Promise.reject(r)}},r}();
//# sourceMappingURL=index.cjs.map