@wishknish/knishio-client-js 0.4.40 → 0.4.41
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/client.umd.js +1 -1
- package/package.json +1 -1
- package/src/Meta.js +4 -16
- package/src/libraries/check.js +21 -21
package/dist/client.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("js-sha3"),require("big-integer"),require("@stablelib/base64"),require("get-random-values"),require("big-integer/BigInteger"),require("buffer"),require("base-x"),require("tweetnacl"),require("tweetnacl-sealedbox-js"),require("@stablelib/utf8"),require("@apollo/client/core"),require("isomorphic-fetch"),require("@apollo/client/cache"),require("@apollo/client/link/error"),require("laravel-echo"),require("socket.io-client"),require("graphql")):"function"==typeof define&&define.amd?define(["exports","js-sha3","big-integer","@stablelib/base64","get-random-values","big-integer/BigInteger","buffer","base-x","tweetnacl","tweetnacl-sealedbox-js","@stablelib/utf8","@apollo/client/core","isomorphic-fetch","@apollo/client/cache","@apollo/client/link/error","laravel-echo","socket.io-client","graphql"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).KnishIO={},e.jsSha3,e.bigInt,e.base64,e.getRandomValues,e.bigIntB,e.buffer,e.baseX,e.tweetnacl,e.tweetnaclSealedboxJs,e.utf8,e.core,e.fetch,e.cache,e.error,e.Echo,e.io,e.graphql)}(this,(function(e,t,s,n,a,i,r,l,o,u,c,h,d,p,m,y,g,b){"use strict";function k(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var _=k(s),f=k(a),w=k(i),$=k(l),I=k(d),S=k(y),A=k(g);class x{static toHex(e,t){const s=(e,t)=>{const s=t?["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]:["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];return s[Math.floor(e/16)]+s[e%16]},n=Object.assign({grouping:0,rowlength:0,uppercase:!1},t||{});let a="",i=0,r=0;for(let t=0;t<e.length&&(a+=s(e[t],n.uppercase),t!==e.length-1);++t)n.grouping>0&&++i===n.grouping&&(i=0,n.rowlength>0&&++r===n.rowlength?(r=0,a+="\n"):a+=" ");return a}static toUint8Array(e){let t=e.toLowerCase().replace(/\s/g,"");t.length%2==1&&(t=`0${t}`);let s=new Uint8Array(Math.floor(t.length/2)),n=-1;for(let e=0;e<t.length;++e){let a=t[e],i=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(a);if(-1===i)throw Error("unexpected character");-1===n?n=16*i:(s[Math.floor(e/2)]=n+i,n=-1)}return s}}function T(e,t){const s=Math.ceil(e.length/t),n=[];for(let a=0,i=0;a<s;++a,i+=t)n[a]=e.substr(i,t);return n}function v(e=256,t="abcdef0123456789"){let s=new Uint8Array(e);return s=f.default(s),s=s.map((e=>t.charCodeAt(e%t.length))),String.fromCharCode.apply(null,s)}function q(e,t,s,n,a){if(n=n||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡",a=a||n,t>n.length||s>a.length)return console.warn("Strings::charsetBaseConvert() - Can't convert",e,"to base",s,"greater than symbol table length. src-table:",n.length,"dest-table:",a.length),!1;let i=_.default(0);for(let s=0;s<e.length;s++)i=i.multiply(t).add(n.indexOf(e.charAt(s)));if(i.lesser(0))return 0;let r=i.mod(s),l=a.charAt(r),o=i.divide(s);for(;!o.equals(0);)r=o.mod(s),o=o.divide(s),l=a.charAt(r)+l;return l}function M(e){return n.encode(x.toUint8Array(e))}function C(e){return x.toHex(n.decode(e),{})}function W(e){return/^[A-F0-9]+$/i.test(e)}function H(e,t){let s,n,a,i=[Array,Date,Number,String,Boolean],r=Object.prototype.toString;for(t=t||[],s=0;s<t.length;s+=2)e===t[s]&&(n=t[s+1]);if(!n&&e&&"object"==typeof e){for(n={},s=0;s<i.length;s++)r.call(e)===r.call(a=new i[s](e))&&(n=s?a:[]);for(s in t.push(e,n),e)t.hasOwnProperty.call(e,s)&&(n[s]=H(e[s],t))}return n||e}function B(...e){return[].concat(...e.map(((t,s)=>{const n=e.slice(0);n.splice(s,1);const a=[...new Set([].concat(...n))];return t.filter((e=>!a.includes(e)))})))}String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}),String.prototype.toCamelCase||(String.prototype.toCamelCase=function(){return this.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g,((e,t)=>t.toUpperCase()))}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,(e=>`_${e.toLowerCase()}`))});class U{constructor({meta:e}){this.meta=e,this.createdAt=+new Date}static normalizeMeta(e){const t=[];for(const s in e)e.hasOwnProperty(s)&&null!==e[s]&&t.push({key:s,value:e[s].toString()});return t}static aggregateMeta(e){let t={};if(Array.isArray(e))for(let s of e)t[s.key]=s.value;else t=e;return t}static policy(e,t){const s={conditions:"policy",rule:e.rule||[],callback:e.callback||{}};if(t)for(const[e,n]of Object.entries(t||{}))if(null!==n&&["read","write"].includes(e)){s.callback[e]={};for(const[t,a]of Object.entries(n))s.callback[e][t]=a}s.callback=U.__defaultPolicy(s.callback,e);for(const e of["conditions","rule","callback"])s[e]=Array.isArray(s[e])||"[object Object]"===Object.prototype.toString.call(s[e])?JSON.stringify(s[e]):s[e],"conditions"===e&&"[object String]"===Object.prototype.toString.call(s[e])&&(s[e]=JSON.stringify(s[e]));return s}static __defaultPolicy(e,t){const s=H(e),n=Array.from(s).filter((e=>"read"===e.action)),a=Array.from(s).filter((e=>"write"===e.action)),i=Object.keys(t||{});for(const[e,t]of Object.entries({read:n,write:a})){const n=t.map((e=>e.key));s[e]||(s[e]={});for(const t of B(i,n))s[e][t]||(s[e][t]="write"!==e||["characters","pubkey"].includes(t)?["all"]:["self"])}return s}}class j{constructor({position:e=null,walletAddress:t=null,isotope:s=null,token:n=null,value:a=null,batchId:i=null,metaType:r=null,metaId:l=null,meta:o=null,otsFragment:u=null,index:c=null}){this.position=e,this.walletAddress=t,this.isotope=s,this.token=n,this.value=null!==a?String(a):null,this.batchId=i,this.metaType=r,this.metaId=l,this.meta=o?U.normalizeMeta(o):[],this.index=c,this.otsFragment=u,this.createdAt=String(+new Date)}static get create(){return{C({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="C",new j(arguments[0])},I({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="I",new j(arguments[0])},M({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="M",new j(arguments[0])},T({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="T",new j(arguments[0])},U({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="U",new j(arguments[0])},V({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="V",new j(arguments[0])},R({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="R",new j(arguments[0])}}}static get hashSchema(){return new Map([["position",null],["walletAddress",null],["isotope",null],["token",null],["value",null],["batchId",null],["metaType",null],["metaId",null],["meta",null],["createdAt",null]])}aggregatedMeta(){return U.aggregateMeta(this.meta)}static jsonToObject(e){const t=Object.assign(new j({}),JSON.parse(e)),s=Object.keys(new j({}));for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t}static molecularHashSchema(e){const t=j.hashSchema;for(const s in e)e.hasOwnProperty(s)&&t.has(s)&&t.set(s,e[s]);return t}static hashAtoms({atoms:e,output:s="base17"}){const n=t.shake256.create(256),a=e.length,i=j.sortAtoms(e);for(const e of i){const t=j.molecularHashSchema(e);n.update(String(a));for(const e of t.keys()){const s=t.get(e);if(null!==s||["position","walletAddress"].includes(e))if("meta"!==e)n.update(null===s?"":String(s));else for(const e of s)void 0!==e.value&&null!==e.value&&(n.update(String(e.key)),n.update(String(e.value)))}}switch(s){case"hex":return n.hex();case"array":return n.array();default:return q(n.hex(),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static sortAtoms(e){const t=[...e];return t.sort(((e,t)=>e.index===t.index?0:e.index<t.index?-1:1)),t}}class O{static encode(e){return n.encode(e)}static decode(e){return r.Buffer.from(n.decode(e))}encode(e){return O.encode(e)}decode(e){return O.decode(e)}}class R{constructor(e={}){this.$options=Object.assign({characters:"GMP"},e),this.$encoder=$.default(this[this.$options.characters]||this.GMP)}encode(e){return this.$encoder.encode(r.Buffer.from(e))}decode(e){return this.$encoder.decode(e)}get GMP(){return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"}get BITCOIN(){return"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}get FLICKR(){return"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}get RIPPLE(){return"rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"}get IPFS(){return"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}}class E{constructor(e={}){this.$options=Object.assign({characters:"BASE64"},e),this.$encoder=new R,["BASE64"].includes(this.$options.characters)?this.$encoder=new O:["BASE2","BASE8","BASE11","BASE36","BASE62","BASE67"].includes(this.$options.characters)?this.$encoder=$.default(this[this.$options.characters]):["BITCOIN","FLICKR","RIPPLE","IPFS"].includes(this.$options.characters)&&(this.$encoder=new R(this.$options))}encode(e){return this.$encoder.encode(r.Buffer.from(e))}decode(e){return this.$encoder.decode(e)}get BASE2(){return"01"}get BASE8(){return"01234567"}get BASE11(){return"0123456789a"}get BASE36(){return"0123456789abcdefghijklmnopqrstuvwxyz"}get BASE62(){return"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}get BASE67(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"}}class K{constructor(e=null){this.base=new E({characters:e||"BASE64"})}encrypt(e,t){return this.encode(u.seal(c.encode(JSON.stringify(e)),this.decode(t)))}decrypt(e,t,s){try{return JSON.parse(c.decode(u.open(this.decode(e),this.decode(s),this.decode(t))))}catch(e){return null}}generatePrivateKey(e){const s=t.shake256.create(8*o.box.secretKeyLength);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}generatePublicKey(e){const t=o.box.keyPair.fromSecretKey(this.decode(e));return this.encode(t.publicKey)}shortHash(e){const s=t.shake256.create(64);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}decode(e){return this.base.decode(e)}encode(e){return this.base.encode(e)}}function Q(e=null,s=2048){if(console.info(`Crypto::generateSecret() - Computing new secret${e?" from existing seed":""}...`),e){const n=t.shake256.create(2*s);return n.update(e),n.hex()}return v(s)}function P(e){console.info("Crypto::generateBundleHash() - Computing wallet bundle from secret...");const s=t.shake256.create(256);return s.update(e),s.hex()}function N({molecularHash:e=null,index:t=null}){return null!==e&&null!==t?P(String(e)+String(t)):v(64)}function F(e=64){return v(e,"abcdef0123456789")}function V(e,t,s=null){return new K(s).encrypt(e,t)}function D(e,t,s,n=null){return new K(n).decrypt(e,t,s)}function J(e,t=null){return new K(t).generatePrivateKey(e)}function L(e,t=null){return new K(t).generatePublicKey(e)}function z(e,t=null){return new K(t).shortHash(e)}class G{constructor({secret:e=null,token:t="USER",position:s=null,batchId:n=null,characters:a=null}){this.token=t,this.balance=0,this.molecules={},this.key=null,this.address=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.bundle=e?P(e):null,this.batchId=n,this.position=s,this.characters=a||"BASE64",e&&(this.position=this.position||F(),this.prepareKeys(e))}static create({secretOrBundle:e,token:t,batchId:s=null,characters:n=null}){let a=G.isBundleHash(e)?null:e,i=a?P(a):e,r=a?F():null,l=new G({secret:a,token:t,position:r,batchId:s,characters:n});return l.bundle=i,l}static isBundleHash(e){return"string"==typeof e&&(64===e.length&&W(e))}static getTokenUnits(e){let t=[];return e.forEach((e=>{t.push({id:e.shift(),name:e.shift(),metas:e})})),t}hasTokenUnits(){return!!this.tokenUnits&&this.tokenUnits.length>0}tokenUnitsJson(){if(this.hasTokenUnits()){const e=[];return this.tokenUnits.forEach((t=>{e.push([t.id,t.name].concat(t.metas))})),JSON.stringify(e)}return null}splitUnits(e,t,s=null){if(0===e.length)return;let n=[],a=[];this.tokenUnits.forEach((t=>{e.includes(t.id)?n.push(t):a.push(t)})),this.tokenUnits=n,null!==s&&(s.tokenUnits=n),t.tokenUnits=a}isShadow(){return!(void 0!==this.position&&null!==this.position||void 0!==this.address&&null!==this.address)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:N({}))}prepareKeys(e){null===this.key&&null===this.address&&(this.key=G.generatePrivateKey({secret:e,token:this.token,position:this.position}),this.address=G.generatePublicKey(this.key),this.getMyEncPrivateKey(),this.getMyEncPublicKey())}getMyEncPrivateKey(){return null===this.privkey&&null!==this.key&&(this.privkey=J(this.key,this.characters)),this.privkey}getMyEncPublicKey(){const e=this.getMyEncPrivateKey();return!this.pubkey&&e&&(this.pubkey=L(e,this.characters)),this.pubkey}encryptMyMessage(e){const t={};for(let s=1,n=arguments.length;s<n;s++)t[z(arguments[s],this.characters)]=V(e,arguments[s],this.characters);return t}decryptMyMessage(e){const t=this.getMyEncPublicKey();let s=e;return null!==e&&"object"==typeof e&&"[object Object]"===Object.prototype.toString.call(e)&&(s=e[z(t,this.characters)]||""),D(s,this.getMyEncPrivateKey(),t,this.characters)}decryptBinary(e){const t=this.decryptMyMessage(e);return new E({characters:"BASE64"}).decode(t)}encryptBinary(e){const t=Array.from(arguments).slice(1),s=new E({characters:"BASE64"}).encode(e);return this.encryptMyMessage(s,...t)}encryptString({data:e,publicKeys:t}){if(e){const s=this.getMyEncPublicKey();"string"==typeof t&&(t=[t]);const n=this.encryptMyMessage(e,s,...t);return btoa(JSON.stringify(n))}}decryptString({data:e,fallbackValue:t=null}){if(e)try{const s=JSON.parse(atob(e));return this.decryptMyMessage(s)||t}catch(s){return console.error(s),t||e}}static generatePrivateKey({secret:e,token:s,position:n}){const a=w.default(e,16).add(w.default(n,16)),i=t.shake256.create(8192);return i.update(a.toString(16)),s&&i.update(s),t.shake256.create(8192).update(i.hex()).hex()}static generatePublicKey(e){const s=T(e,128),n=t.shake256.create(8192);for(const e in s){let a=s[e];for(let e=1;e<=16;e++)a=t.shake256.create(512).update(a).hex();n.update(a)}return t.shake256.create(256).update(n.hex()).hex()}}class Z extends TypeError{constructor(e=null,t=null,s=null){if(super(e,t,s),null===e)throw new this(`Unknown ${this.constructor.name}`);this.name="BaseException"}toString(){return`${this.name}: ${this.message}.\nStack:\n${this.stack}`}}class X extends Z{constructor(e="There is an atom without an index",t=null,s=null){super(e,t,s),this.name="AtomIndexException"}}class Y extends Z{constructor(e="The molecule does not contain atoms",t=null,s=null){super(e,t,s),this.name="AtomsMissingException"}}class ee extends Z{constructor(e="The molecular hash does not match",t=null,s=null){super(e,t,s),this.name="MolecularHashMismatchException"}}class te extends Z{constructor(e="The molecular hash is missing",t=null,s=null){super(e,t,s),this.name="MolecularHashMissingException"}}class se extends Z{constructor(e="OTS malformed",t=null,s=null){super(e,t,s),this.name="SignatureMalformedException"}}class ne extends Z{constructor(e="One-time signature (OTS) does not match!",t=null,s=null){super(e,t,s),this.name="SignatureMismatchException"}}class ae extends Z{constructor(e="Insufficient balance to make transfer",t=null,s=null){super(e,t,s),this.name="TransferBalanceException"}}class ie extends Z{constructor(e="Token transfer atoms are malformed",t=null,s=null){super(e,t,s),this.name="TransferMalformedException"}}class re extends Z{constructor(e="Token slugs for wallets in transfer do not match!",t=null,s=null){super(e,t,s),this.name="TransferMismatchedException"}}class le extends Z{constructor(e="Invalid remainder provided",t=null,s=null){super(e,t,s),this.name="TransferRemainderException"}}class oe extends Z{constructor(e="Sender and recipient(s) cannot be the same",t=null,s=null){super(e,t,s),this.name="TransferToSelfException"}}class ue extends Z{constructor(e="Token transfer atoms are unbalanced",t=null,s=null){super(e,t,s),this.name="TransferUnbalancedException"}}class ce extends Z{constructor(e="Empty meta data.",t=null,s=null){super(e,t,s),this.name="MetaMissingException"}}class he extends Z{constructor(e="Wrong type of token for this isotope",t=null,s=null){super(e,t,s),this.name="WrongTokenTypeException"}}class de extends Z{constructor(e="Incorrect BatchId",t=null,s=null){super(e,t,s),this.name="BatchIdException"}}class pe extends Z{constructor(e="",t=null,s=null){super(e,t,s),this.name="KnishIOInvalidPolicyException"}}class me{static continuId(e){me.missing(e);if("USER"===e.atoms[0].token&&me.isotopeFilter("I",e.atoms).length<1)throw new Y("Check::continuId() - Molecule is missing required ContinuID Atom!");return!0}static batchId(e){if(e.atoms.length>0){const t=e.atoms[0];if("V"===t.isotope&&null!==t.batchId){const s=me.isotopeFilter("V",e.atoms),n=s[s.length-1];if(t.batchId!==n.batchId)throw new de;for(const e of s)if(null===e.batchId)throw new de}return!0}throw new de}static isotopeI(e){me.missing(e);for(let t of me.isotopeFilter("I",e.atoms)){if("USER"!==t.token)throw new he(`Check::isotopeI() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0===t.index)throw new X(`Check::isotopeI() - Isotope "${t.isotope}" Atoms must have a non-zero index!`)}return!0}static isotopeU(e){me.missing(e);for(let t of me.isotopeFilter("U",e.atoms)){if("AUTH"!==t.token)throw new he(`Check::isotopeU() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeU() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeM(e){me.missing(e);const t=["readPolicy","writePolicy"];for(let s of me.isotopeFilter("M",e.atoms)){if(s.meta.length<1)throw new ce;if("USER"!==s.token)throw new he(`Check::isotopeM() - "${s.token}" is not a valid Token slug for "${s.isotope}" isotope Atoms!`);const e=U.aggregateMeta(s.meta);for(const s of t){let n=e[s];if(n){n=JSON.parse(n);for(const[s,a]of Object.entries(n))if(!t.includes(s)){if(!Object.keys(e).includes(s))throw new pe(`${s} is missing from the meta.`);for(const e of a)if(!G.isBundleHash(e)&&!["all","self"].includes(e))throw new pe(`${e} does not correspond to the format of the policy.`)}}}}return!0}static isotopeC(e){me.missing(e);for(let t of me.isotopeFilter("C",e.atoms)){if("USER"!==t.token)throw new he(`Check::isotopeC() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeC() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeT(e){me.missing(e);for(let t of me.isotopeFilter("T",e.atoms)){const e=t.aggregatedMeta();if("wallet"===String(t.metaType).toLowerCase())for(let t of["position","bundle"])if(!e.hasOwnProperty(t)||!Boolean(e[t]))throw new ce(`Check::isotopeT() - Required meta field "${t}" is missing!`);for(let t of["token"])if(!e.hasOwnProperty(t)||!Boolean(e[t]))throw new ce(`Check::isotopeT() - Required meta field "${t}" is missing!`);if("USER"!==t.token)throw new he(`Check::isotopeT() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeT() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeR(e){me.missing(e);for(let t of me.isotopeFilter("R",e.atoms)){const e=t.aggregatedMeta();for(let t of["callback","conditions","rule"])if(!e.hasOwnProperty(t))throw new ce(`Check::isotopeR() - Required meta field "${t}" is missing!`);try{JSON.parse(e.conditions),JSON.parse(e.callback)}catch(e){throw new ce("Check::isotopeR() - Condition is formatted incorrectly!")}if("policy"===conditions&&callback.length&&!callback.every((e=>["read","write"].includes(e.action))))throw new ce("Check::isotopeR() - Mixing rules with politics!");if(Array.isArray(conditions)&&conditions.length)for(let e of conditions){const t=Object.keys(e),s=t.filter((e=>-1!==["key","value","comparison"].indexOf(e))),n=t.filter((e=>-1!==["managedBy"].indexOf(e)));if(s.length<3&&n.length)throw new ce("Check::isotopeR() - Required condition field is missing!")}}return!0}static isotopeV(e,t=null){me.missing(e);const s=me.isotopeFilter("V",e.atoms);if(0===s.length)return!0;const n=e.atoms[0];if("V"===n.isotope&&2===s.length){const e=s[s.length-1];if(n.token!==e.token)throw new re;if(e.value<0)throw new ie;return!0}let a=0,i=0;for(let t in e.atoms)if(e.atoms.hasOwnProperty(t)){const s=e.atoms[t];if("V"!==s.isotope)continue;if(i=1*s.value,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');if(s.token!==n.token)throw new re;if(t>0){if(i<0)throw new ie;if(s.walletAddress===n.walletAddress)throw new oe}a+=i}if(a!==i)throw new ue;if(t){if(i=1*n.value,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');const e=1*t.balance+1*i;if(e<0)throw new ae;if(e!==a)throw new le}else if(0!==i)throw new le;return!0}static molecularHash(e){if(me.missing(e),e.molecularHash!==j.hashAtoms({atoms:e.atoms}))throw new ee;return!0}static ots(e){me.missing(e);const s=e.atoms[0].walletAddress,n=me.normalizedHash(e.molecularHash);let a=e.atoms.map((e=>e.otsFragment)).reduce(((e,t)=>e+t));if(2048!==a.length&&(a=C(a),2048!==a.length))throw new se;const i=T(a,128);let r="";for(const e in i){let s=i[e];for(let a=0,i=8+n[e];a<i;a++)s=t.shake256.create(512).update(s).hex();r+=s}const l=t.shake256.create(8192).update(r).hex();if(t.shake256.create(256).update(l).hex()!==s)throw new ne;return!0}static index(e){me.missing(e);for(let t of e.atoms)if(null===t.index)throw new X;return!0}static isotopeFilter(e,t){return(t=t||[]).filter((t=>e===t.isotope))}static normalizedHash(e){return me.normalize(me.enumerate(e))}static enumerate(e){const t={0:-8,1:-7,2:-6,3:-5,4:-4,5:-3,6:-2,7:-1,8:0,9:1,a:2,b:3,c:4,d:5,e:6,f:7,g:8},s=[],n=e.toLowerCase().split("");for(let e=0,a=n.length;e<a;++e){const a=n[e];void 0!==t[a]&&(s[e]=t[a])}return s}static normalize(e){let t=e.reduce(((e,t)=>e+t));const s=t<0;for(;t<0||t>0;)for(const n of Object.keys(e)){if((s?e[n]<8:e[n]>-8)&&(s?(++e[n],++t):(--e[n],--t),0===t))break}return e}static missing(e){if(null===e.molecularHash)throw new te;if(1>e.atoms.length)throw new Y}}class ye extends Z{constructor(e="Insufficient balance for requested transfer",t=null,s=null){super(e,t,s),this.name="BalanceInsufficientException"}}class ge extends Z{constructor(e="Amount cannot be negative!",t=null,s=null){super(e,t,s),this.name="NegativeAmountException"}}class be{constructor({secret:e=null,sourceWallet:t=null,remainderWallet:s=null,cellSlug:n=null}){this.cellSlugOrigin=this.cellSlug=n,this.secret=e,this.sourceWallet=t,this.atoms=[],(s||t)&&(this.remainderWallet=s||G.create({secretOrBundle:e,token:t.token,batchId:t.batchId,characters:t.characters})),this.clear()}static generateNextAtomIndex(e){const t=e.length-1;return t>-1?e[t].index+1:0}continuIdMetaType(){return"walletBundle"}fill(e){for(let t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,this.atoms.push(e),this.atoms=j.sortAtoms(this.atoms),this}finalMetas(e=null,t=null){return e=e||{},(t=t||this.sourceWallet).hasTokenUnits()&&(e.tokenUnits=t.tokenUnitsJson()),e.pubkey=t.pubkey,e.characters=t.characters,e}contextMetas(e=null,t=null){return e=e||{}}replenishTokens({amount:e,token:t,metas:s}){s.action="add";for(let e of["address","position","batchId"])if(void 0===s[e])throw new ce(`Molecule::replenishTokens() - Missing ${e} in meta!`);return this.molecularHash=null,this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,amount:e,batchId:this.sourceWallet.batchId,metaType:"token",metaId:t,meta:this.finalMetas(s),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}addUserRemainderAtom(e){return this.molecularHash=null,this.atoms.push(j.create.I({position:e.position,walletAddress:e.address,token:e.token,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}addPolicyAtom({metaType:e,metaId:t,meta:s={},policy:n={}}){return this.molecularHash=null,this.addAtom(j.create.R({token:"USER",metaType:e,metaId:t,meta:U.policy(this.finalMetas(s),n),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new ge("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new ye;return this.molecularHash=null,this.atoms.push(j.create.V({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:-e,batchId:this.sourceWallet.batchId,meta:this.finalMetas({}),index:this.generateIndex()})),this.atoms.push(j.create.V({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,token:this.sourceWallet.token,value:this.sourceWallet.balance-e,batchId:this.remainderWallet.batchId,metaType:t?"walletBundle":null,metaId:t,meta:this.finalMetas({},this.remainderWallet),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new ye;return this.molecularHash=null,this.atoms.push(j.create.V({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:-t,batchId:this.sourceWallet.batchId,meta:this.finalMetas({}),index:this.generateIndex()})),this.atoms.push(j.create.V({position:e.position,walletAddress:e.address,token:this.sourceWallet.token,value:t,batchId:e.batchId,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms.push(j.create.V({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,token:this.sourceWallet.token,value:this.sourceWallet.balance-t,batchId:this.remainderWallet.batchId,metaType:"walletBundle",metaId:this.sourceWallet.bundle,meta:this.finalMetas({},this.remainderWallet),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}initWalletCreation(e){this.molecularHash=null;const t={address:e.address,token:e.token,bundle:e.bundle,position:e.position,amount:0,batchId:e.batchId,pubkey:e.pubkey,characters:e.characters};return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,metaType:"wallet",metaId:e.address,meta:this.finalMetas(this.contextMetas(t),e),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initTokenCreation({recipientWallet:e,amount:t,meta:s}){this.molecularHash=null;for(const t of["walletAddress","walletPosition","walletPubkey","walletCharacters"])s[t]||(s[t]=e[t.toLowerCase().substr(6)]);return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:t,batchId:e.batchId,metaType:"token",metaId:e.token,meta:this.finalMetas(this.contextMetas(s),this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}createRule({metaType:e,metaId:t,meta:s}){for(let e of["conditions","callback","rule"]){if(void 0===s[e])throw new ce(`Molecule::createRule() - Value for required meta key ${e} in missing!`);for(let t of["[object Object]","[object Array]"])Object.prototype.toString.call(s[e])===t&&(s[e]=JSON.stringify(s[e]))}return this.addAtom(j.create.R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:e,metaId:t,meta:this.finalMetas(s,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initShadowWalletClaim({token:e,wallet:t}){this.molecularHash=null;let s={tokenSlug:e,walletAddress:t.address,walletPosition:t.position,batchId:t.batchId};return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:"wallet",metaId:t.address,meta:this.finalMetas(this.contextMetas(s)),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initIdentifierCreation({type:e,contact:t,code:s}){this.molecularHash=null;const n={code:s,hash:P(t.trim())};return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:"identifier",metaId:e,meta:this.finalMetas(n,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initMeta({meta:e,metaType:t,metaId:s,policy:n}){return this.molecularHash=null,this.atoms.push(j.create.M({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,metaType:t,metaId:s,meta:this.finalMetas(e,this.sourceWallet),index:this.generateIndex()})),this.addPolicyAtom({metaType:t,metaId:s,meta:e,policy:n}),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:a={},batchId:i=null}){return this.molecularHash=null,a.token=e,this.atoms.push(j.create.T({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:t,batchId:i,metaType:s,metaId:n,meta:this.finalMetas(a),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initAuthorization({meta:e}){return this.molecularHash=null,this.atoms.push(j.create.U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,meta:this.finalMetas(e),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}clear(){return this.molecularHash=null,this.bundle=null,this.status=null,this.createdAt=String(+new Date),this.atoms=[],this}sign({anonymous:e=!1,compressed:s=!0}){if(0===this.atoms.length||0!==this.atoms.filter((e=>!(e instanceof j))).length)throw new Y;e||(this.bundle=P(this.secret)),this.molecularHash=j.hashAtoms({atoms:this.atoms});const n=this.atoms[0],a=T(G.generatePrivateKey({secret:this.secret,token:n.token,position:n.position}),128),i=me.normalizedHash(this.molecularHash);let r="";for(const e in a){let s=a[e];for(let n=0,a=8-i[e];n<a;n++)s=t.shake256.create(512).update(s).hex();r+=s}s&&(r=M(r));const l=T(r,Math.ceil(r.length/this.atoms.length));let o=null;for(let e=0,t=l.length;e<t;e++)this.atoms[e].otsFragment=l[e],o=this.atoms[e].position;return o}generateIndex(){return be.generateNextAtomIndex(this.atoms)}static jsonToObject(e){const t=Object.assign(new be({}),JSON.parse(e)),s=Object.keys(new be({}));if(!Array.isArray(t.atoms))throw new Y;for(const e in Object.keys(t.atoms)){t.atoms[e]=j.jsonToObject(JSON.stringify(t.atoms[e]));for(const s of["position","walletAddress","isotope"])if(void 0===t.atoms[e][s]||null===t.atoms[e][s])throw new Y("MolecularStructure::jsonToObject() - Required Atom properties are missing!")}for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t.atoms=j.sortAtoms(t.atoms),t}get cellSlugDelimiter(){return"."}cellSlugBase(){return(this.cellSlug||"").split(this.cellSlugDelimiter)[0]}toJSON(){let e=H(this);for(let t of["remainderWallet","secret","sourceWallet","cellSlugOrigin"])e.hasOwnProperty(t)&&delete e[t];return e}check(e=null){return be.verify({molecule:this,sourceWallet:e})}static verify({molecule:e,sourceWallet:t=null}){return me.molecularHash(e)&&me.ots(e)&&me.index(e)&&me.batchId(e)&&me.continuId(e)&&me.isotopeM(e)&&me.isotopeT(e)&&me.isotopeC(e)&&me.isotopeU(e)&&me.isotopeI(e)&&me.isotopeR(e)&&me.isotopeV(e,t)}}class ke{static __init(e,t){this.arr=[],this.key=null,this.arr=String(t).split("."),this.key=this.arr.shift();const s=Number(this.key);Number.isInteger(s)&&(this.key=s),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!!(Array.isArray(e)||e instanceof Object)&&void 0!==e[this.key]}static has(e,t){return this.__init(e,t),!!this.__next&&(0===this.__nextKey||this.has(e[this.key],this.arr.join(".")))}static get(e,t,s=null){return this.__init(e,t),this.__next?0===this.__nextKey?e[this.key]:this.get(e[this.key],this.arr.join("."),s):s}}const _e=10**18;class fe{static val(e){return Math.abs(e*_e)<1?0:e}static cmp(e,t,s=!1){const n=fe.val(e)*_e,a=fe.val(t)*_e;return Math.abs(n-a)<1?0:n>a?1:-1}static equal(e,t){return 0===fe.cmp(e,t)}}class we{static create(e,t){let s=new we(e);return s.setWallet(t),s}static restore(e,t){let s=new G({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return we.create({token:e.token,expiresAt:e.expiresAt,pubkey:e.pubkey,encrypt:e.encrypt},s)}constructor({token:e,expiresAt:t,encrypt:s,pubkey:n}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=n,this.$__encrypt=s}setWallet(e){this.$__wallet=e}getWallet(){return this.$__wallet}getSnapshot(){return{token:this.$__token,expiresAt:this.$__expiresAt,pubkey:this.$__pubkey,encrypt:this.$__encrypt,wallet:{position:this.$__wallet.position,characters:this.$__wallet.characters}}}getToken(){return this.$__token}getPubkey(){return this.$__pubkey}getExpireInterval(){return 1e3*this.$__expiresAt-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}}class $e extends Z{constructor(e="Code exception",t=null,s=null){super(e,t,s),this.name="CodeException"}}class Ie extends Z{constructor(e="GraphQL did not provide a valid response.",t=null,s=null){super(e,t,s),this.name="InvalidResponseException"}}class Se extends Z{constructor(e="Authorization token missing or invalid.",t=null,s=null){super(e,t,s),this.name="UnauthenticatedException"}}class Ae{constructor({query:e,json:t,dataKey:s=null}){if(this.dataKey=s,this.errorKey="exception",this.$__payload=null,this.$__query=e,this.$__originResponse=t,this.$__response=t,void 0===this.$__response||null===this.$__response)throw new Ie;if(ke.has(this.$__response,this.errorKey)){const e=ke.get(this.$__response,this.errorKey);if(String(e).includes("Unauthenticated"))throw new Se;throw new Ie}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!ke.has(this.response(),this.dataKey))throw new Ie;return ke.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}}class xe{constructor(e){this.client=e,this.$__variables=null,this.$__query=null}response(){return this.$__response}async createResponseRaw(e){return this.createResponse(e)}createResponse(e){return new Ae({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new $e("Query::createQuery() - Node URI was not initialized for this client instance!");if(null===this.$__query)throw new $e("Query::createQuery() - GraphQL subscription was not initialized!");return{query:this.$__query,variables:this.variables()}}async execute({variables:e=null}){this.$__request=this.createQuery({variables:e});let t=await this.client.query(this.$__request);return this.$__response=await this.createResponseRaw(t),this.$__response}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}}class Te extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ContinuId"})}payload(){let e=null;const t=this.data();return t&&(e=new G({secret:null,token:t.tokenSlug}),e.address=t.address,e.position=t.position,e.bundle=t.bundleHash,e.batchId=t.batchId,e.characters=t.characters,e.pubkey=t.pubkey,e.balance=1*t.amount),e}}class ve extends xe{constructor(e){super(e),this.$__query=h.gql`query ($bundle: String!) {
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("js-sha3"),require("big-integer"),require("@stablelib/base64"),require("get-random-values"),require("big-integer/BigInteger"),require("buffer"),require("base-x"),require("tweetnacl"),require("tweetnacl-sealedbox-js"),require("@stablelib/utf8"),require("@apollo/client/core"),require("isomorphic-fetch"),require("@apollo/client/cache"),require("@apollo/client/link/error"),require("laravel-echo"),require("socket.io-client"),require("graphql")):"function"==typeof define&&define.amd?define(["exports","js-sha3","big-integer","@stablelib/base64","get-random-values","big-integer/BigInteger","buffer","base-x","tweetnacl","tweetnacl-sealedbox-js","@stablelib/utf8","@apollo/client/core","isomorphic-fetch","@apollo/client/cache","@apollo/client/link/error","laravel-echo","socket.io-client","graphql"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).KnishIO={},e.jsSha3,e.bigInt,e.base64,e.getRandomValues,e.bigIntB,e.buffer,e.baseX,e.tweetnacl,e.tweetnaclSealedboxJs,e.utf8,e.core,e.fetch,e.cache,e.error,e.Echo,e.io,e.graphql)}(this,(function(e,t,s,n,a,i,r,l,o,u,c,h,d,p,m,y,g,b){"use strict";function k(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var _=k(s),f=k(a),w=k(i),$=k(l),I=k(d),S=k(y),A=k(g);class x{static toHex(e,t){const s=(e,t)=>{const s=t?["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]:["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];return s[Math.floor(e/16)]+s[e%16]},n=Object.assign({grouping:0,rowlength:0,uppercase:!1},t||{});let a="",i=0,r=0;for(let t=0;t<e.length&&(a+=s(e[t],n.uppercase),t!==e.length-1);++t)n.grouping>0&&++i===n.grouping&&(i=0,n.rowlength>0&&++r===n.rowlength?(r=0,a+="\n"):a+=" ");return a}static toUint8Array(e){let t=e.toLowerCase().replace(/\s/g,"");t.length%2==1&&(t=`0${t}`);let s=new Uint8Array(Math.floor(t.length/2)),n=-1;for(let e=0;e<t.length;++e){let a=t[e],i=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"].indexOf(a);if(-1===i)throw Error("unexpected character");-1===n?n=16*i:(s[Math.floor(e/2)]=n+i,n=-1)}return s}}function T(e,t){const s=Math.ceil(e.length/t),n=[];for(let a=0,i=0;a<s;++a,i+=t)n[a]=e.substr(i,t);return n}function v(e=256,t="abcdef0123456789"){let s=new Uint8Array(e);return s=f.default(s),s=s.map((e=>t.charCodeAt(e%t.length))),String.fromCharCode.apply(null,s)}function q(e,t,s,n,a){if(n=n||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~`!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?¿¡",a=a||n,t>n.length||s>a.length)return console.warn("Strings::charsetBaseConvert() - Can't convert",e,"to base",s,"greater than symbol table length. src-table:",n.length,"dest-table:",a.length),!1;let i=_.default(0);for(let s=0;s<e.length;s++)i=i.multiply(t).add(n.indexOf(e.charAt(s)));if(i.lesser(0))return 0;let r=i.mod(s),l=a.charAt(r),o=i.divide(s);for(;!o.equals(0);)r=o.mod(s),o=o.divide(s),l=a.charAt(r)+l;return l}function M(e){return n.encode(x.toUint8Array(e))}function C(e){return x.toHex(n.decode(e),{})}function W(e){return/^[A-F0-9]+$/i.test(e)}function H(e,t){let s,n,a,i=[Array,Date,Number,String,Boolean],r=Object.prototype.toString;for(t=t||[],s=0;s<t.length;s+=2)e===t[s]&&(n=t[s+1]);if(!n&&e&&"object"==typeof e){for(n={},s=0;s<i.length;s++)r.call(e)===r.call(a=new i[s](e))&&(n=s?a:[]);for(s in t.push(e,n),e)t.hasOwnProperty.call(e,s)&&(n[s]=H(e[s],t))}return n||e}function B(...e){return[].concat(...e.map(((t,s)=>{const n=e.slice(0);n.splice(s,1);const a=[...new Set([].concat(...n))];return t.filter((e=>!a.includes(e)))})))}String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}),String.prototype.toCamelCase||(String.prototype.toCamelCase=function(){return this.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g,((e,t)=>t.toUpperCase()))}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,(e=>`_${e.toLowerCase()}`))});class U{constructor({meta:e}){this.meta=e,this.createdAt=+new Date}static normalizeMeta(e){const t=[];for(const s in e)e.hasOwnProperty(s)&&null!==e[s]&&t.push({key:s,value:e[s].toString()});return t}static aggregateMeta(e){let t={};if(Array.isArray(e))for(let s of e)t[s.key]=s.value;else t=e;return t}static policy(e,t){const s={policy:{}};if(t)for(const[e,n]of Object.entries(t||{}))if(null!==n&&["read","write"].includes(e)){s.policy[e]={};for(const[t,a]of Object.entries(n))s.policy[e][t]=a}return s.policy=JSON.stringify(U.__defaultPolicy(s.policy,e)),s}static __defaultPolicy(e,t){const s=H(e),n=Array.from(s).filter((e=>"read"===e.action)),a=Array.from(s).filter((e=>"write"===e.action)),i=Object.keys(t||{});for(const[e,t]of Object.entries({read:n,write:a})){const n=t.map((e=>e.key));s[e]||(s[e]={});for(const t of B(i,n))s[e][t]||(s[e][t]="write"!==e||["characters","pubkey"].includes(t)?["all"]:["self"])}return s}}class j{constructor({position:e=null,walletAddress:t=null,isotope:s=null,token:n=null,value:a=null,batchId:i=null,metaType:r=null,metaId:l=null,meta:o=null,otsFragment:u=null,index:c=null}){this.position=e,this.walletAddress=t,this.isotope=s,this.token=n,this.value=null!==a?String(a):null,this.batchId=i,this.metaType=r,this.metaId=l,this.meta=o?U.normalizeMeta(o):[],this.index=c,this.otsFragment=u,this.createdAt=String(+new Date)}static get create(){return{C({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="C",new j(arguments[0])},I({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="I",new j(arguments[0])},M({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="M",new j(arguments[0])},T({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="T",new j(arguments[0])},U({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="U",new j(arguments[0])},V({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="V",new j(arguments[0])},R({position:e=null,walletAddress:t=null,token:s=null,value:n=null,batchId:a=null,metaType:i=null,metaId:r=null,meta:l=null,otsFragment:o=null,index:u=null}){return arguments[0].isotope="R",new j(arguments[0])}}}static get hashSchema(){return new Map([["position",null],["walletAddress",null],["isotope",null],["token",null],["value",null],["batchId",null],["metaType",null],["metaId",null],["meta",null],["createdAt",null]])}aggregatedMeta(){return U.aggregateMeta(this.meta)}static jsonToObject(e){const t=Object.assign(new j({}),JSON.parse(e)),s=Object.keys(new j({}));for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t}static molecularHashSchema(e){const t=j.hashSchema;for(const s in e)e.hasOwnProperty(s)&&t.has(s)&&t.set(s,e[s]);return t}static hashAtoms({atoms:e,output:s="base17"}){const n=t.shake256.create(256),a=e.length,i=j.sortAtoms(e);for(const e of i){const t=j.molecularHashSchema(e);n.update(String(a));for(const e of t.keys()){const s=t.get(e);if(null!==s||["position","walletAddress"].includes(e))if("meta"!==e)n.update(null===s?"":String(s));else for(const e of s)void 0!==e.value&&null!==e.value&&(n.update(String(e.key)),n.update(String(e.value)))}}switch(s){case"hex":return n.hex();case"array":return n.array();default:return q(n.hex(),16,17,"0123456789abcdef","0123456789abcdefg").padStart(64,"0")}}static sortAtoms(e){const t=[...e];return t.sort(((e,t)=>e.index===t.index?0:e.index<t.index?-1:1)),t}}class O{static encode(e){return n.encode(e)}static decode(e){return r.Buffer.from(n.decode(e))}encode(e){return O.encode(e)}decode(e){return O.decode(e)}}class R{constructor(e={}){this.$options=Object.assign({characters:"GMP"},e),this.$encoder=$.default(this[this.$options.characters]||this.GMP)}encode(e){return this.$encoder.encode(r.Buffer.from(e))}decode(e){return this.$encoder.decode(e)}get GMP(){return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"}get BITCOIN(){return"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}get FLICKR(){return"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}get RIPPLE(){return"rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"}get IPFS(){return"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}}class E{constructor(e={}){this.$options=Object.assign({characters:"BASE64"},e),this.$encoder=new R,["BASE64"].includes(this.$options.characters)?this.$encoder=new O:["BASE2","BASE8","BASE11","BASE36","BASE62","BASE67"].includes(this.$options.characters)?this.$encoder=$.default(this[this.$options.characters]):["BITCOIN","FLICKR","RIPPLE","IPFS"].includes(this.$options.characters)&&(this.$encoder=new R(this.$options))}encode(e){return this.$encoder.encode(r.Buffer.from(e))}decode(e){return this.$encoder.decode(e)}get BASE2(){return"01"}get BASE8(){return"01234567"}get BASE11(){return"0123456789a"}get BASE36(){return"0123456789abcdefghijklmnopqrstuvwxyz"}get BASE62(){return"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}get BASE67(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"}}class K{constructor(e=null){this.base=new E({characters:e||"BASE64"})}encrypt(e,t){return this.encode(u.seal(c.encode(JSON.stringify(e)),this.decode(t)))}decrypt(e,t,s){try{return JSON.parse(c.decode(u.open(this.decode(e),this.decode(s),this.decode(t))))}catch(e){return null}}generatePrivateKey(e){const s=t.shake256.create(8*o.box.secretKeyLength);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}generatePublicKey(e){const t=o.box.keyPair.fromSecretKey(this.decode(e));return this.encode(t.publicKey)}shortHash(e){const s=t.shake256.create(64);return s.update(e),this.base.encode(r.Buffer.from(s.digest()))}decode(e){return this.base.decode(e)}encode(e){return this.base.encode(e)}}function Q(e=null,s=2048){if(console.info(`Crypto::generateSecret() - Computing new secret${e?" from existing seed":""}...`),e){const n=t.shake256.create(2*s);return n.update(e),n.hex()}return v(s)}function P(e){console.info("Crypto::generateBundleHash() - Computing wallet bundle from secret...");const s=t.shake256.create(256);return s.update(e),s.hex()}function N({molecularHash:e=null,index:t=null}){return null!==e&&null!==t?P(String(e)+String(t)):v(64)}function F(e=64){return v(e,"abcdef0123456789")}function V(e,t,s=null){return new K(s).encrypt(e,t)}function D(e,t,s,n=null){return new K(n).decrypt(e,t,s)}function J(e,t=null){return new K(t).generatePrivateKey(e)}function L(e,t=null){return new K(t).generatePublicKey(e)}function z(e,t=null){return new K(t).shortHash(e)}class G{constructor({secret:e=null,token:t="USER",position:s=null,batchId:n=null,characters:a=null}){this.token=t,this.balance=0,this.molecules={},this.key=null,this.address=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.bundle=e?P(e):null,this.batchId=n,this.position=s,this.characters=a||"BASE64",e&&(this.position=this.position||F(),this.prepareKeys(e))}static create({secretOrBundle:e,token:t,batchId:s=null,characters:n=null}){let a=G.isBundleHash(e)?null:e,i=a?P(a):e,r=a?F():null,l=new G({secret:a,token:t,position:r,batchId:s,characters:n});return l.bundle=i,l}static isBundleHash(e){return"string"==typeof e&&(64===e.length&&W(e))}static getTokenUnits(e){let t=[];return e.forEach((e=>{t.push({id:e.shift(),name:e.shift(),metas:e})})),t}hasTokenUnits(){return!!this.tokenUnits&&this.tokenUnits.length>0}tokenUnitsJson(){if(this.hasTokenUnits()){const e=[];return this.tokenUnits.forEach((t=>{e.push([t.id,t.name].concat(t.metas))})),JSON.stringify(e)}return null}splitUnits(e,t,s=null){if(0===e.length)return;let n=[],a=[];this.tokenUnits.forEach((t=>{e.includes(t.id)?n.push(t):a.push(t)})),this.tokenUnits=n,null!==s&&(s.tokenUnits=n),t.tokenUnits=a}isShadow(){return!(void 0!==this.position&&null!==this.position||void 0!==this.address&&null!==this.address)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:N({}))}prepareKeys(e){null===this.key&&null===this.address&&(this.key=G.generatePrivateKey({secret:e,token:this.token,position:this.position}),this.address=G.generatePublicKey(this.key),this.getMyEncPrivateKey(),this.getMyEncPublicKey())}getMyEncPrivateKey(){return null===this.privkey&&null!==this.key&&(this.privkey=J(this.key,this.characters)),this.privkey}getMyEncPublicKey(){const e=this.getMyEncPrivateKey();return!this.pubkey&&e&&(this.pubkey=L(e,this.characters)),this.pubkey}encryptMyMessage(e){const t={};for(let s=1,n=arguments.length;s<n;s++)t[z(arguments[s],this.characters)]=V(e,arguments[s],this.characters);return t}decryptMyMessage(e){const t=this.getMyEncPublicKey();let s=e;return null!==e&&"object"==typeof e&&"[object Object]"===Object.prototype.toString.call(e)&&(s=e[z(t,this.characters)]||""),D(s,this.getMyEncPrivateKey(),t,this.characters)}decryptBinary(e){const t=this.decryptMyMessage(e);return new E({characters:"BASE64"}).decode(t)}encryptBinary(e){const t=Array.from(arguments).slice(1),s=new E({characters:"BASE64"}).encode(e);return this.encryptMyMessage(s,...t)}encryptString({data:e,publicKeys:t}){if(e){const s=this.getMyEncPublicKey();"string"==typeof t&&(t=[t]);const n=this.encryptMyMessage(e,s,...t);return btoa(JSON.stringify(n))}}decryptString({data:e,fallbackValue:t=null}){if(e)try{const s=JSON.parse(atob(e));return this.decryptMyMessage(s)||t}catch(s){return console.error(s),t||e}}static generatePrivateKey({secret:e,token:s,position:n}){const a=w.default(e,16).add(w.default(n,16)),i=t.shake256.create(8192);return i.update(a.toString(16)),s&&i.update(s),t.shake256.create(8192).update(i.hex()).hex()}static generatePublicKey(e){const s=T(e,128),n=t.shake256.create(8192);for(const e in s){let a=s[e];for(let e=1;e<=16;e++)a=t.shake256.create(512).update(a).hex();n.update(a)}return t.shake256.create(256).update(n.hex()).hex()}}class Z extends TypeError{constructor(e=null,t=null,s=null){if(super(e,t,s),null===e)throw new this(`Unknown ${this.constructor.name}`);this.name="BaseException"}toString(){return`${this.name}: ${this.message}.\nStack:\n${this.stack}`}}class X extends Z{constructor(e="There is an atom without an index",t=null,s=null){super(e,t,s),this.name="AtomIndexException"}}class Y extends Z{constructor(e="The molecule does not contain atoms",t=null,s=null){super(e,t,s),this.name="AtomsMissingException"}}class ee extends Z{constructor(e="The molecular hash does not match",t=null,s=null){super(e,t,s),this.name="MolecularHashMismatchException"}}class te extends Z{constructor(e="The molecular hash is missing",t=null,s=null){super(e,t,s),this.name="MolecularHashMissingException"}}class se extends Z{constructor(e="OTS malformed",t=null,s=null){super(e,t,s),this.name="SignatureMalformedException"}}class ne extends Z{constructor(e="One-time signature (OTS) does not match!",t=null,s=null){super(e,t,s),this.name="SignatureMismatchException"}}class ae extends Z{constructor(e="Insufficient balance to make transfer",t=null,s=null){super(e,t,s),this.name="TransferBalanceException"}}class ie extends Z{constructor(e="Token transfer atoms are malformed",t=null,s=null){super(e,t,s),this.name="TransferMalformedException"}}class re extends Z{constructor(e="Token slugs for wallets in transfer do not match!",t=null,s=null){super(e,t,s),this.name="TransferMismatchedException"}}class le extends Z{constructor(e="Invalid remainder provided",t=null,s=null){super(e,t,s),this.name="TransferRemainderException"}}class oe extends Z{constructor(e="Sender and recipient(s) cannot be the same",t=null,s=null){super(e,t,s),this.name="TransferToSelfException"}}class ue extends Z{constructor(e="Token transfer atoms are unbalanced",t=null,s=null){super(e,t,s),this.name="TransferUnbalancedException"}}class ce extends Z{constructor(e="Empty meta data.",t=null,s=null){super(e,t,s),this.name="MetaMissingException"}}class he extends Z{constructor(e="Wrong type of token for this isotope",t=null,s=null){super(e,t,s),this.name="WrongTokenTypeException"}}class de extends Z{constructor(e="Incorrect BatchId",t=null,s=null){super(e,t,s),this.name="BatchIdException"}}class pe extends Z{constructor(e="",t=null,s=null){super(e,t,s),this.name="KnishIOInvalidPolicyException"}}class me{static continuId(e){me.missing(e);if("USER"===e.atoms[0].token&&me.isotopeFilter("I",e.atoms).length<1)throw new Y("Check::continuId() - Molecule is missing required ContinuID Atom!");return!0}static batchId(e){if(e.atoms.length>0){const t=e.atoms[0];if("V"===t.isotope&&null!==t.batchId){const s=me.isotopeFilter("V",e.atoms),n=s[s.length-1];if(t.batchId!==n.batchId)throw new de;for(const e of s)if(null===e.batchId)throw new de}return!0}throw new de}static isotopeI(e){me.missing(e);for(let t of me.isotopeFilter("I",e.atoms)){if("USER"!==t.token)throw new he(`Check::isotopeI() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0===t.index)throw new X(`Check::isotopeI() - Isotope "${t.isotope}" Atoms must have a non-zero index!`)}return!0}static isotopeU(e){me.missing(e);for(let t of me.isotopeFilter("U",e.atoms)){if("AUTH"!==t.token)throw new he(`Check::isotopeU() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeU() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeM(e){me.missing(e);const t=["readPolicy","writePolicy"];for(let s of me.isotopeFilter("M",e.atoms)){if(s.meta.length<1)throw new ce;if("USER"!==s.token)throw new he(`Check::isotopeM() - "${s.token}" is not a valid Token slug for "${s.isotope}" isotope Atoms!`);const e=U.aggregateMeta(s.meta);for(const s of t){let n=e[s];if(n){n=JSON.parse(n);for(const[s,a]of Object.entries(n))if(!t.includes(s)){if(!Object.keys(e).includes(s))throw new pe(`${s} is missing from the meta.`);for(const e of a)if(!G.isBundleHash(e)&&!["all","self"].includes(e))throw new pe(`${e} does not correspond to the format of the policy.`)}}}}return!0}static isotopeC(e){me.missing(e);for(let t of me.isotopeFilter("C",e.atoms)){if("USER"!==t.token)throw new he(`Check::isotopeC() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeC() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeT(e){me.missing(e);for(let t of me.isotopeFilter("T",e.atoms)){const e=t.aggregatedMeta();if("wallet"===String(t.metaType).toLowerCase())for(let t of["position","bundle"])if(!e.hasOwnProperty(t)||!Boolean(e[t]))throw new ce(`Check::isotopeT() - Required meta field "${t}" is missing!`);for(let t of["token"])if(!e.hasOwnProperty(t)||!Boolean(e[t]))throw new ce(`Check::isotopeT() - Required meta field "${t}" is missing!`);if("USER"!==t.token)throw new he(`Check::isotopeT() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);if(0!==t.index)throw new X(`Check::isotopeT() - Isotope "${t.isotope}" Atoms must have an index equal to 0!`)}return!0}static isotopeR(e){me.missing(e);for(let t of me.isotopeFilter("R",e.atoms)){const e=t.aggregatedMeta();if(e.policy){const t=JSON.parse(e.policy);if(!Object.keys(t).every((e=>["read","write"].includes(e))))throw new ce("Check::isotopeR() - Mixing rules with politics!")}if(e.rule){const t=JSON.parse(e.rule);for(let e of["callback","conditions","rule"])if(!t.hasOwnProperty(e))throw new ce(`Check::isotopeR() - Required meta field "${e}" is missing!`);const s=t.conditions;if(Array.isArray(s)&&s.length)for(let e of s){const t=Object.keys(e),s=t.filter((e=>-1!==["key","value","comparison"].indexOf(e))),n=t.filter((e=>-1!==["managedBy"].indexOf(e)));if(s.length<3&&n.length)throw new ce("Check::isotopeR() - Required condition field is missing!")}}}return!0}static isotopeV(e,t=null){me.missing(e);const s=me.isotopeFilter("V",e.atoms);if(0===s.length)return!0;const n=e.atoms[0];if("V"===n.isotope&&2===s.length){const e=s[s.length-1];if(n.token!==e.token)throw new re;if(e.value<0)throw new ie;return!0}let a=0,i=0;for(let t in e.atoms)if(e.atoms.hasOwnProperty(t)){const s=e.atoms[t];if("V"!==s.isotope)continue;if(i=1*s.value,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');if(s.token!==n.token)throw new re;if(t>0){if(i<0)throw new ie;if(s.walletAddress===n.walletAddress)throw new oe}a+=i}if(a!==i)throw new ue;if(t){if(i=1*n.value,Number.isNaN(i))throw new TypeError('Invalid isotope "V" values');const e=1*t.balance+1*i;if(e<0)throw new ae;if(e!==a)throw new le}else if(0!==i)throw new le;return!0}static molecularHash(e){if(me.missing(e),e.molecularHash!==j.hashAtoms({atoms:e.atoms}))throw new ee;return!0}static ots(e){me.missing(e);const s=e.atoms[0].walletAddress,n=me.normalizedHash(e.molecularHash);let a=e.atoms.map((e=>e.otsFragment)).reduce(((e,t)=>e+t));if(2048!==a.length&&(a=C(a),2048!==a.length))throw new se;const i=T(a,128);let r="";for(const e in i){let s=i[e];for(let a=0,i=8+n[e];a<i;a++)s=t.shake256.create(512).update(s).hex();r+=s}const l=t.shake256.create(8192).update(r).hex();if(t.shake256.create(256).update(l).hex()!==s)throw new ne;return!0}static index(e){me.missing(e);for(let t of e.atoms)if(null===t.index)throw new X;return!0}static isotopeFilter(e,t){return(t=t||[]).filter((t=>e===t.isotope))}static normalizedHash(e){return me.normalize(me.enumerate(e))}static enumerate(e){const t={0:-8,1:-7,2:-6,3:-5,4:-4,5:-3,6:-2,7:-1,8:0,9:1,a:2,b:3,c:4,d:5,e:6,f:7,g:8},s=[],n=e.toLowerCase().split("");for(let e=0,a=n.length;e<a;++e){const a=n[e];void 0!==t[a]&&(s[e]=t[a])}return s}static normalize(e){let t=e.reduce(((e,t)=>e+t));const s=t<0;for(;t<0||t>0;)for(const n of Object.keys(e)){if((s?e[n]<8:e[n]>-8)&&(s?(++e[n],++t):(--e[n],--t),0===t))break}return e}static missing(e){if(null===e.molecularHash)throw new te;if(1>e.atoms.length)throw new Y}}class ye extends Z{constructor(e="Insufficient balance for requested transfer",t=null,s=null){super(e,t,s),this.name="BalanceInsufficientException"}}class ge extends Z{constructor(e="Amount cannot be negative!",t=null,s=null){super(e,t,s),this.name="NegativeAmountException"}}class be{constructor({secret:e=null,sourceWallet:t=null,remainderWallet:s=null,cellSlug:n=null}){this.cellSlugOrigin=this.cellSlug=n,this.secret=e,this.sourceWallet=t,this.atoms=[],(s||t)&&(this.remainderWallet=s||G.create({secretOrBundle:e,token:t.token,batchId:t.batchId,characters:t.characters})),this.clear()}static generateNextAtomIndex(e){const t=e.length-1;return t>-1?e[t].index+1:0}continuIdMetaType(){return"walletBundle"}fill(e){for(let t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,this.atoms.push(e),this.atoms=j.sortAtoms(this.atoms),this}finalMetas(e=null,t=null){return e=e||{},(t=t||this.sourceWallet).hasTokenUnits()&&(e.tokenUnits=t.tokenUnitsJson()),e.pubkey=t.pubkey,e.characters=t.characters,e}contextMetas(e=null,t=null){return e=e||{}}replenishTokens({amount:e,token:t,metas:s}){s.action="add";for(let e of["address","position","batchId"])if(void 0===s[e])throw new ce(`Molecule::replenishTokens() - Missing ${e} in meta!`);return this.molecularHash=null,this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,amount:e,batchId:this.sourceWallet.batchId,metaType:"token",metaId:t,meta:this.finalMetas(s),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}addUserRemainderAtom(e){return this.molecularHash=null,this.atoms.push(j.create.I({position:e.position,walletAddress:e.address,token:e.token,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}addPolicyAtom({metaType:e,metaId:t,meta:s={},policy:n={}}){return this.molecularHash=null,this.addAtom(j.create.R({token:"USER",metaType:e,metaId:t,meta:U.policy(this.finalMetas(s),n),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new ge("Molecule::burnToken() - Amount to burn must be positive!");if(this.sourceWallet.balance-e<0)throw new ye;return this.molecularHash=null,this.atoms.push(j.create.V({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:-e,batchId:this.sourceWallet.batchId,meta:this.finalMetas({}),index:this.generateIndex()})),this.atoms.push(j.create.V({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,token:this.sourceWallet.token,value:this.sourceWallet.balance-e,batchId:this.remainderWallet.batchId,metaType:t?"walletBundle":null,metaId:t,meta:this.finalMetas({},this.remainderWallet),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new ye;return this.molecularHash=null,this.atoms.push(j.create.V({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:-t,batchId:this.sourceWallet.batchId,meta:this.finalMetas({}),index:this.generateIndex()})),this.atoms.push(j.create.V({position:e.position,walletAddress:e.address,token:this.sourceWallet.token,value:t,batchId:e.batchId,metaType:"walletBundle",metaId:e.bundle,meta:this.finalMetas({},e),index:this.generateIndex()})),this.atoms.push(j.create.V({position:this.remainderWallet.position,walletAddress:this.remainderWallet.address,token:this.sourceWallet.token,value:this.sourceWallet.balance-t,batchId:this.remainderWallet.batchId,metaType:"walletBundle",metaId:this.sourceWallet.bundle,meta:this.finalMetas({},this.remainderWallet),index:this.generateIndex()})),this.atoms=j.sortAtoms(this.atoms),this}initWalletCreation(e){this.molecularHash=null;const t={address:e.address,token:e.token,bundle:e.bundle,position:e.position,amount:0,batchId:e.batchId,pubkey:e.pubkey,characters:e.characters};return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,metaType:"wallet",metaId:e.address,meta:this.finalMetas(this.contextMetas(t),e),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initTokenCreation({recipientWallet:e,amount:t,meta:s}){this.molecularHash=null;for(const t of["walletAddress","walletPosition","walletPubkey","walletCharacters"])s[t]||(s[t]=e[t.toLowerCase().substr(6)]);return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:t,batchId:e.batchId,metaType:"token",metaId:e.token,meta:this.finalMetas(this.contextMetas(s),this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}createRule({metaType:e,metaId:t,meta:s}){for(let e of["conditions","callback","rule"]){if(void 0===s[e])throw new ce(`Molecule::createRule() - Value for required meta key ${e} in missing!`);for(let t of["[object Object]","[object Array]"])Object.prototype.toString.call(s[e])===t&&(s[e]=JSON.stringify(s[e]))}return this.addAtom(j.create.R({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:e,metaId:t,meta:this.finalMetas(s,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initShadowWalletClaim({token:e,wallet:t}){this.molecularHash=null;let s={tokenSlug:e,walletAddress:t.address,walletPosition:t.position,batchId:t.batchId};return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:"wallet",metaId:t.address,meta:this.finalMetas(this.contextMetas(s)),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initIdentifierCreation({type:e,contact:t,code:s}){this.molecularHash=null;const n={code:s,hash:P(t.trim())};return this.atoms.push(j.create.C({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,metaType:"identifier",metaId:e,meta:this.finalMetas(n,this.sourceWallet),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initMeta({meta:e,metaType:t,metaId:s,policy:n}){return this.molecularHash=null,this.atoms.push(j.create.M({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,metaType:t,metaId:s,meta:this.finalMetas(e,this.sourceWallet),index:this.generateIndex()})),this.addPolicyAtom({metaType:t,metaId:s,meta:e,policy:n}),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initTokenRequest({token:e,amount:t,metaType:s,metaId:n,meta:a={},batchId:i=null}){return this.molecularHash=null,a.token=e,this.atoms.push(j.create.T({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,value:t,batchId:i,metaType:s,metaId:n,meta:this.finalMetas(a),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}initAuthorization({meta:e}){return this.molecularHash=null,this.atoms.push(j.create.U({position:this.sourceWallet.position,walletAddress:this.sourceWallet.address,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,meta:this.finalMetas(e),index:this.generateIndex()})),this.addUserRemainderAtom(this.remainderWallet),this.atoms=j.sortAtoms(this.atoms),this}clear(){return this.molecularHash=null,this.bundle=null,this.status=null,this.createdAt=String(+new Date),this.atoms=[],this}sign({anonymous:e=!1,compressed:s=!0}){if(0===this.atoms.length||0!==this.atoms.filter((e=>!(e instanceof j))).length)throw new Y;e||(this.bundle=P(this.secret)),this.molecularHash=j.hashAtoms({atoms:this.atoms});const n=this.atoms[0],a=T(G.generatePrivateKey({secret:this.secret,token:n.token,position:n.position}),128),i=me.normalizedHash(this.molecularHash);let r="";for(const e in a){let s=a[e];for(let n=0,a=8-i[e];n<a;n++)s=t.shake256.create(512).update(s).hex();r+=s}s&&(r=M(r));const l=T(r,Math.ceil(r.length/this.atoms.length));let o=null;for(let e=0,t=l.length;e<t;e++)this.atoms[e].otsFragment=l[e],o=this.atoms[e].position;return o}generateIndex(){return be.generateNextAtomIndex(this.atoms)}static jsonToObject(e){const t=Object.assign(new be({}),JSON.parse(e)),s=Object.keys(new be({}));if(!Array.isArray(t.atoms))throw new Y;for(const e in Object.keys(t.atoms)){t.atoms[e]=j.jsonToObject(JSON.stringify(t.atoms[e]));for(const s of["position","walletAddress","isotope"])if(void 0===t.atoms[e][s]||null===t.atoms[e][s])throw new Y("MolecularStructure::jsonToObject() - Required Atom properties are missing!")}for(const e in t)t.hasOwnProperty(e)&&!s.includes(e)&&delete t[e];return t.atoms=j.sortAtoms(t.atoms),t}get cellSlugDelimiter(){return"."}cellSlugBase(){return(this.cellSlug||"").split(this.cellSlugDelimiter)[0]}toJSON(){let e=H(this);for(let t of["remainderWallet","secret","sourceWallet","cellSlugOrigin"])e.hasOwnProperty(t)&&delete e[t];return e}check(e=null){return be.verify({molecule:this,sourceWallet:e})}static verify({molecule:e,sourceWallet:t=null}){return me.molecularHash(e)&&me.ots(e)&&me.index(e)&&me.batchId(e)&&me.continuId(e)&&me.isotopeM(e)&&me.isotopeT(e)&&me.isotopeC(e)&&me.isotopeU(e)&&me.isotopeI(e)&&me.isotopeR(e)&&me.isotopeV(e,t)}}class ke{static __init(e,t){this.arr=[],this.key=null,this.arr=String(t).split("."),this.key=this.arr.shift();const s=Number(this.key);Number.isInteger(s)&&(this.key=s),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!!(Array.isArray(e)||e instanceof Object)&&void 0!==e[this.key]}static has(e,t){return this.__init(e,t),!!this.__next&&(0===this.__nextKey||this.has(e[this.key],this.arr.join(".")))}static get(e,t,s=null){return this.__init(e,t),this.__next?0===this.__nextKey?e[this.key]:this.get(e[this.key],this.arr.join("."),s):s}}const _e=10**18;class fe{static val(e){return Math.abs(e*_e)<1?0:e}static cmp(e,t,s=!1){const n=fe.val(e)*_e,a=fe.val(t)*_e;return Math.abs(n-a)<1?0:n>a?1:-1}static equal(e,t){return 0===fe.cmp(e,t)}}class we{static create(e,t){let s=new we(e);return s.setWallet(t),s}static restore(e,t){let s=new G({secret:t,token:"AUTH",position:e.wallet.position,characters:e.wallet.characters});return we.create({token:e.token,expiresAt:e.expiresAt,pubkey:e.pubkey,encrypt:e.encrypt},s)}constructor({token:e,expiresAt:t,encrypt:s,pubkey:n}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=n,this.$__encrypt=s}setWallet(e){this.$__wallet=e}getWallet(){return this.$__wallet}getSnapshot(){return{token:this.$__token,expiresAt:this.$__expiresAt,pubkey:this.$__pubkey,encrypt:this.$__encrypt,wallet:{position:this.$__wallet.position,characters:this.$__wallet.characters}}}getToken(){return this.$__token}getPubkey(){return this.$__pubkey}getExpireInterval(){return 1e3*this.$__expiresAt-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}}class $e extends Z{constructor(e="Code exception",t=null,s=null){super(e,t,s),this.name="CodeException"}}class Ie extends Z{constructor(e="GraphQL did not provide a valid response.",t=null,s=null){super(e,t,s),this.name="InvalidResponseException"}}class Se extends Z{constructor(e="Authorization token missing or invalid.",t=null,s=null){super(e,t,s),this.name="UnauthenticatedException"}}class Ae{constructor({query:e,json:t,dataKey:s=null}){if(this.dataKey=s,this.errorKey="exception",this.$__payload=null,this.$__query=e,this.$__originResponse=t,this.$__response=t,void 0===this.$__response||null===this.$__response)throw new Ie;if(ke.has(this.$__response,this.errorKey)){const e=ke.get(this.$__response,this.errorKey);if(String(e).includes("Unauthenticated"))throw new Se;throw new Ie}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!ke.has(this.response(),this.dataKey))throw new Ie;return ke.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}}class xe{constructor(e){this.client=e,this.$__variables=null,this.$__query=null}response(){return this.$__response}async createResponseRaw(e){return this.createResponse(e)}createResponse(e){return new Ae({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new $e("Query::createQuery() - Node URI was not initialized for this client instance!");if(null===this.$__query)throw new $e("Query::createQuery() - GraphQL subscription was not initialized!");return{query:this.$__query,variables:this.variables()}}async execute({variables:e=null}){this.$__request=this.createQuery({variables:e});let t=await this.client.query(this.$__request);return this.$__response=await this.createResponseRaw(t),this.$__response}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}}class Te extends Ae{constructor({query:e,json:t}){super({query:e,json:t,dataKey:"data.ContinuId"})}payload(){let e=null;const t=this.data();return t&&(e=new G({secret:null,token:t.tokenSlug}),e.address=t.address,e.position=t.position,e.bundle=t.bundleHash,e.batchId=t.batchId,e.characters=t.characters,e.pubkey=t.pubkey,e.balance=1*t.amount),e}}class ve extends xe{constructor(e){super(e),this.$__query=h.gql`query ($bundle: String!) {
|
|
2
2
|
ContinuId(bundle: $bundle) {
|
|
3
3
|
address,
|
|
4
4
|
bundleHash,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wishknish/knishio-client-js",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.41",
|
|
4
4
|
"productName": "Knish.IO Javascript SDK Client",
|
|
5
5
|
"description": "JavaScript implementation of the Knish.IO SDK to consume Knish.IO GraphQL APIs.",
|
|
6
6
|
"license": "GPL-3.0-or-later",
|
package/src/Meta.js
CHANGED
|
@@ -119,35 +119,23 @@ export default class Meta {
|
|
|
119
119
|
*/
|
|
120
120
|
static policy ( meta, policy ) {
|
|
121
121
|
const metas = {
|
|
122
|
-
|
|
123
|
-
rule: meta[ 'rule' ] || [],
|
|
124
|
-
callback: meta[ 'callback' ] || {}
|
|
122
|
+
policy: {}
|
|
125
123
|
};
|
|
126
124
|
|
|
127
125
|
if ( policy ) {
|
|
128
126
|
for ( const [ policyKey, value ] of Object.entries( policy || {} ) ) {
|
|
129
127
|
|
|
130
128
|
if ( value !== null && [ 'read', 'write' ].includes( policyKey ) ) {
|
|
131
|
-
metas[
|
|
129
|
+
metas.policy[ policyKey ] = {};
|
|
132
130
|
|
|
133
131
|
for ( const [ key, content ] of Object.entries( value ) ) {
|
|
134
|
-
metas[
|
|
132
|
+
metas.policy[ policyKey ][ key ] = content;
|
|
135
133
|
}
|
|
136
134
|
}
|
|
137
135
|
}
|
|
138
136
|
}
|
|
139
137
|
|
|
140
|
-
metas
|
|
141
|
-
|
|
142
|
-
for ( const policyKey of [ 'conditions', 'rule', 'callback' ] ) {
|
|
143
|
-
metas[ policyKey ] = Array.isArray( metas[ policyKey ] ) ||
|
|
144
|
-
Object.prototype.toString.call( metas[ policyKey ] ) === '[object Object]' ?
|
|
145
|
-
JSON.stringify( metas[ policyKey ] ) : metas[ policyKey ];
|
|
146
|
-
|
|
147
|
-
if ( policyKey === 'conditions' && Object.prototype.toString.call( metas[ policyKey ] ) === '[object String]' ) {
|
|
148
|
-
metas[ policyKey ] = JSON.stringify( metas[ policyKey ] );
|
|
149
|
-
}
|
|
150
|
-
}
|
|
138
|
+
metas.policy = JSON.stringify( Meta.__defaultPolicy( metas.policy, meta ) );
|
|
151
139
|
|
|
152
140
|
return metas;
|
|
153
141
|
}
|
package/src/libraries/check.js
CHANGED
|
@@ -243,35 +243,35 @@ export default class CheckMolecule {
|
|
|
243
243
|
|
|
244
244
|
for ( let atom of CheckMolecule.isotopeFilter( 'R', molecule.atoms ) ) {
|
|
245
245
|
const metas = atom.aggregatedMeta();
|
|
246
|
-
for ( let key of [ 'callback', 'conditions', 'rule' ] ) {
|
|
247
246
|
|
|
248
|
-
|
|
249
|
-
|
|
247
|
+
if ( metas.policy ) {
|
|
248
|
+
const policy = JSON.parse( metas.policy );
|
|
249
|
+
|
|
250
|
+
if ( !Object.keys( policy ).every( i => [ 'read', 'write' ].includes( i ) ) ) {
|
|
251
|
+
throw new MetaMissingException( 'Check::isotopeR() - Mixing rules with politics!' );
|
|
250
252
|
}
|
|
251
253
|
}
|
|
252
254
|
|
|
253
|
-
|
|
254
|
-
const
|
|
255
|
-
callback = JSON.parse( metas[ 'callback' ] );
|
|
256
|
-
} catch ( err ) {
|
|
257
|
-
throw new MetaMissingException( 'Check::isotopeR() - Condition is formatted incorrectly!' );
|
|
258
|
-
}
|
|
255
|
+
if ( metas.rule ) {
|
|
256
|
+
const rule = JSON.parse( metas.rule );
|
|
259
257
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
258
|
+
for ( let key of [ 'callback', 'conditions', 'rule' ] ) {
|
|
259
|
+
if ( !rule.hasOwnProperty( key ) ) {
|
|
260
|
+
throw new MetaMissingException( `Check::isotopeR() - Required meta field "${ key }" is missing!` );
|
|
261
|
+
}
|
|
262
|
+
}
|
|
265
263
|
|
|
266
|
-
|
|
264
|
+
const conditions = rule[ 'conditions' ];
|
|
267
265
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
266
|
+
if ( Array.isArray( conditions ) && conditions.length ) {
|
|
267
|
+
for ( let condition of conditions ) {
|
|
268
|
+
const keys = Object.keys( condition ),
|
|
269
|
+
property = keys.filter( n => [ 'key', 'value', 'comparison' ].indexOf( n ) !== -1 ),
|
|
270
|
+
property2 = keys.filter( n => [ 'managedBy' ].indexOf( n ) !== -1 );
|
|
272
271
|
|
|
273
|
-
|
|
274
|
-
|
|
272
|
+
if ( property.length < 3 && property2.length ) {
|
|
273
|
+
throw new MetaMissingException( 'Check::isotopeR() - Required condition field is missing!' );
|
|
274
|
+
}
|
|
275
275
|
}
|
|
276
276
|
}
|
|
277
277
|
}
|