@wishknish/knishio-client-js 0.5.0 → 0.5.2

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.
@@ -450,4 +450,4 @@
450
450
  total
451
451
  }
452
452
  }
453
- }`}createResponse(e){return new Ht({query:this,json:e})}static createVariables({metaType:e=null,metaId:t=null,key:s=null,value:n=null,keys:a=null,values:i=null,atomValues:r=null,latest:l=null,latestMetas:o=!0,filter:u=null,queryArgs:c=null,countBy:h=null}){const d={};return r&&(d.atomValues=r),a&&(d.keys=a),i&&(d.values=i),e&&(d.metaTypes="string"==typeof e?[e]:e),t&&(d.metaIds="string"==typeof t?[t]:t),h&&(d.countBy=h),u&&(d.filter=u),s&&n&&(d.filter=d.filter||[],d.filter.push({key:s,value:n,comparison:"="})),l&&(d.latest=!!l,d.latest=!!o),c&&(void 0!==c.limit&&0!==c.limit||(c.limit="*"),d.queryArgs=c),d}}class Rt extends Qe{}class Et extends Ne{fillMolecule({metaType:e,metaId:t,rule:s,policy:n}){this.$__molecule.createRule({metaType:e,metaId:t,rule:s,policy:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Rt({query:this,json:e})}}class Kt extends Ne{fillMolecule({amount:e,tradeRates:t}){this.$__molecule.initDepositBuffer({amount:e,tradeRates:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}class Qt extends Ne{fillMolecule({recipients:e,signingWallet:t}){this.$__molecule.initWithdrawBuffer({recipients:e,signingWallet:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}class Pt{constructor({uri:e,cellSlug:t=null,client:s=null,socket:n=null,serverSdkVersion:a=3,logging:i=!1}){this.initialize({uri:e,cellSlug:t,socket:n,client:s,serverSdkVersion:a,logging:i})}initialize({uri:e,cellSlug:t=null,socket:s=null,client:n=null,serverSdkVersion:a=3,logging:i=!1}){this.$__logging=i,this.$__uris="object"==typeof e?e:[e],this.$__authTokenObjects={},this.$__authInProcess=!1,t&&this.setCellSlug(t);for(let e in this.$__uris){let t=this.$__uris[e];this.$__authTokenObjects[t]=null}this.$__logging&&console.info(`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${a}...`),this.reset(),this.$__client=n||new bt({socket:{socketUri:null,appKey:"knishio",...s||{}},serverUri:this.getRandomUri()}),this.$__serverSdkVersion=a}getRandomUri(){let e=Math.floor(Math.random()*this.$__uris.length);return this.$__uris[e]}switchEncryption(e){return this.$__encrypt!==e&&(this.$__logging&&console.info(`KnishIOClient::switchEncryption() - Forcing encryption ${e?"on":"off"} to match node...`),this.$__encrypt=e,this.$__client.setEncryption(e),!0)}deinitialize(){this.$__logging&&console.info("KnishIOClient::deinitialize() - Clearing the Knish.IO client session..."),this.reset()}subscribe(){if(!this.client().getSocketUri())throw new pe("KnishIOClient::subscribe() - Socket client not initialized!");return this.client()}getServerSdkVersion(){return this.$__serverSdkVersion}reset(){this.$__secret="",this.$__bundle="",this.remainderWallet=null}cellSlug(){return this.$__cellSlug||null}setCellSlug(e){this.$__cellSlug=e}uri(){return this.$__client.getUri()}client(){if(!this.$__authInProcess){let e=this.getRandomUri();this.$__client.setUri(e);let t=this.$__authTokenObjects[e];t?this.$__client.setAuthData(t.getAuthData()):this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt}).then((()=>{}))}return this.$__client}hasSecret(){return!!this.$__secret}setSecret(e){this.$__secret=e,this.$__bundle=K(e)}getSecret(){if(!this.hasSecret())throw new Ae("KnishIOClient::getSecret() - Unable to find a stored secret! Have you set a secret?");return this.$__secret}hasBundle(){return!!this.$__bundle}getBundle(){if(!this.hasBundle())throw new Ae("KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?");return this.$__bundle}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=D.generateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new D({secret:this.getSecret()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,sourceWallet:t=null,remainderWallet:s=null}){return this.$__logging&&console.info("KnishIOClient::createMolecule() - Creating a new molecule..."),e=e||this.getSecret(),!t&&this.lastMoleculeQuery&&"USER"===this.getRemainderWallet().token&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(t=this.getRemainderWallet()),null===t&&(t=await this.getSourceWallet()),this.remainderWallet=s||D.create({secretOrBundle:e,token:"USER",batchId:t.batchId,characters:t.characters}),new we({secret:e,sourceWallet:t,remainderWallet:this.getRemainderWallet(),cellSlug:this.cellSlug()})}createQuery(e){return new e(this.client())}createSubscribe(e){return new e(this.subscribe())}async createMoleculeMutation({mutationClass:e,molecule:t=null}){this.$__logging&&console.info(`KnishIOClient::createMoleculeQuery() - Creating a new ${e.name} query...`);let s=t||await this.createMolecule({});const n=new e(this.client(),s);if(!(n instanceof Ne))throw new pe(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=n,n}async executeQuery(e,t=null){return this.$__authToken&&this.$__authToken.isExpired()&&(console.info("KnishIOClient::executeQuery() - Access token is expired. Getting new one..."),await this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt})),e.execute({variables:t})}async queryBalance({token:e,bundle:t=null,type:s="regular"}){const n=this.createQuery(He);return this.executeQuery(n,{bundleHash:t||this.getBundle(),token:e,type:s})}async querySourceWallet({token:e,amount:t,type:s="regular"}){let n=(await this.queryBalance({token:e,type:s})).payload();if(null===n||Se.cmp(n.balance,t)<0)throw new se;if(!n.position||!n.address)throw new se("Source wallet can not be a shadow wallet.");return n}async subscribeCreateMolecule({bundle:e,closure:t}){const s=this.createSubscribe(ft);return await s.execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:s}){if(!t)throw new pe(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(wt).execute({variables:{bundle:e||this.getBundle(),token:t},closure:s})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe($t).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:s}){return this.createSubscribe(St).execute({variables:{metaType:e,metaId:t},closure:s})}unsubscribe(e){this.subscribe().unsubscribe(e)}unsubscribeAll(){this.subscribe().unsubscribeAll()}queryMeta({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:a=null,latestMetas:i=null,fields:r=null,filter:l=null,queryArgs:o=null,count:u=null,countBy:c=null,throughAtom:h=!1,values:d=null,keys:p=null,atomValues:m=null}){let y,g;return this.$__logging&&console.info(`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`),h?(y=this.createQuery(jt),g=jt.createVariables({metaType:e,metaId:t,key:s,value:n,latest:a,latestMetas:i,filter:l,queryArgs:o,countBy:c,values:d,keys:p,atomValues:m})):(y=this.createQuery(Re),g=Re.createVariables({metaType:e,metaId:t,key:s,value:n,latest:a,latestMetas:i,filter:l,queryArgs:o,count:u,countBy:c})),this.executeQuery(y,g).then((e=>e.payload()))}queryMetaInstance({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:a=null,filter:i=null,fields:r=null}){this.$__logging&&console.info(`KnishIOClient::queryMetaInstance() - Querying metaType: ${e}, metaId: ${t}...`);const l=this.createQuery(Re),o={metaType:e,metaIds:[t],keys:[s],values:[n],latest:a,filter:i};return this.executeQuery(l,o).then((e=>e.data()))}async queryBatch({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Ee);return await this.executeQuery(t,{batchId:e})}async queryBatchHistory({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Ke);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:k,metaTypes:b,metaType:_,metaIds:f,metaId:w,indexes:$,index:S,filter:I,latest:T,queryArgs:A={limit:15,offset:1}}){this.$__logging&&console.info("KnishIOClient::queryAtom() - Querying atom instances");const x=this.createQuery(Mt);return await this.executeQuery(x,Mt.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:k,metaTypes:b,metaType:_,metaIds:f,metaId:w,indexes:$,index:S,filter:I,latest:T,queryArgs:A}))}async createWallet({token:e}){const t=new D({secret:this.getSecret(),token:e}),s=await this.createMoleculeMutation({mutationClass:it});return s.fillMolecule(t),await this.executeQuery(s)}async queryActiveSession({bundleHash:e,metaType:t,metaId:s}){const n=this.createQuery(xt);return await this.executeQuery(n,{bundleHash:e,metaType:t,metaId:s})}async queryUserActivity({bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,countBy:o,interval:u}){const c=this.createQuery(qt);return await this.executeQuery(c,{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,countBy:o,interval:u})}async activeSession({bundle:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,json:o={}}){const u=this.createQuery(Tt);return await this.executeQuery(u,{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,json:JSON.stringify(o)})}async createToken({token:e,amount:t=null,meta:s=null,batchId:n=null,units:a=[]}){if("stackable"===ke.get(s||{},"fungibility")&&(n||(n=Q({})),s.batchId=n,a.length>0)){if(ke.get(s||{},"decimals")>0)throw new ut;if(t>0)throw new ct;t=a.length,s.splittable=1,s.tokenUnits=JSON.stringify(a)}const i=new D({secret:this.getSecret(),token:e,batchId:n}),r=await this.createMoleculeMutation({mutationClass:De});return r.fillMolecule({recipientWallet:i,amount:t,meta:s||{}}),await this.executeQuery(r)}async createRule({metaType:e,metaId:t,rule:s,policy:n={}}){const a=await this.createMoleculeMutation({mutationClass:Et,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})});return a.fillMolecule({metaType:e,metaId:t,rule:s,policy:n}),await this.executeQuery(a)}async createMeta({metaType:e,metaId:t,meta:s=null,policy:n={}}){const a=await this.createMoleculeMutation({mutationClass:nt,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})}),i=s||{};return a.fillMolecule({metaType:e,metaId:t,meta:i,policy:n}),await this.executeQuery(a)}async createIdentifier({type:e,contact:t,code:s}){const n=await this.createMoleculeMutation({mutationClass:Ye});return n.fillMolecule({type:e,contact:t,code:s}),await this.executeQuery(n)}async createPolicy({metaType:e,metaId:t,policy:s={}}){let n=await this.createMolecule({});n.addPolicyAtom({metaType:e,metaId:t,meta:{},policy:s}),n.addContinuIdAtom(),n.sign({}),n.check();const a=await this.createMoleculeMutation({mutationClass:Ne,molecule:n});return await this.executeQuery(a)}async queryPolicy({metaType:e,metaId:t}){const s=this.createQuery(Ot);return await this.executeQuery(s,{metaType:e,metaId:t})}queryWallets({bundle:e=null,token:t=null,unspent:s=!0}){this.$__logging&&console.info(`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:""}...`);const n=this.createQuery(Ue);return this.executeQuery(n,{bundleHash:e||this.getBundle(),token:t,unspent:s}).then((e=>e.payload()))}queryShadowWallets({token:e="KNISH",bundle:t=null}){t=t||this.getBundle(),this.$__logging&&console.info(`KnishIOClient::queryShadowWallets() - Querying ${e} shadow wallets for ${t}...`);const s=this.createQuery(Ue);return this.executeQuery(s,{bundleHash:t,token:e}).then((e=>e.payload()))}queryBundle({bundle:e=null,key:t=null,value:s=null,latest:n=!0,fields:a=null,raw:i=!1}){this.$__logging&&console.info(`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:""}...`);const r=this.createQuery(Be),l=Be.createVariables({bundleHash:e||this.getBundle(),key:t,value:s,latest:n});return this.executeQuery(r,l).then((e=>i?e:e.payload()))}async queryContinuId({bundle:e}){const t=this.createQuery(Ce);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:s=null,units:n=[],meta:a=null,batchId:i=null}){let r,l;a=a||{};const o=this.createQuery(Ct),u=await this.executeQuery(o,{slug:e}),c="stackable"===ke.get(u.data(),"0.fungibility");if(!c&&null!==i)throw new ce("Expected Batch ID = null for non-stackable tokens.");if(c&&null===i&&(i=Q({})),n.length>0){if(s>0)throw new ct;s=n.length,a.tokenUnits=JSON.stringify(n)}t?("[object String]"===Object.prototype.toString.call(t)&&(D.isBundleHash(t)?(r="walletBundle",l=t):t=D.create({secretOrBundle:t,token:e})),t instanceof D&&(r="wallet",a.position=t.position,a.bundle=t.bundle,l=t.address)):(r="walletBundle",l=this.getBundle());const h=await this.createMoleculeMutation({mutationClass:ze});return h.fillMolecule({token:e,amount:s,metaType:r,metaId:l,meta:a,batchId:i}),await this.executeQuery(h)}async claimShadowWallet({token:e,batchId:t=null,molecule:s=null}){const n=await this.createMoleculeMutation({mutationClass:tt,molecule:s});return n.fillMolecule({token:e,batchId:t}),await this.executeQuery(n)}async claimShadowWallets({token:e}){const t=await this.queryShadowWallets({token:e});if(!t||!Array.isArray(t))throw new ot;t.forEach((e=>{if(!e.isShadow())throw new ot}));let s=[];for(const n of t)s.push(await this.claimShadowWallet({token:e,batchId:n.batchId}));return s}async transferToken({bundleHash:e,token:t,amount:s=null,units:n=[],batchId:a=null,sourceWallet:i=null}){if(n.length>0){if(s>0)throw new ct;s=n.length}if(null===i&&(i=await this.querySourceWallet({token:t,amount:s})),null===i||Se.cmp(i.balance,s)<0)throw new se;let r=D.create({secretOrBundle:e,token:t});null!==a?r.batchId=a:r.initBatchId({sourceWallet:i}),this.remainderWallet=D.create({secretOrBundle:this.getSecret(),token:t,characters:i.characters}),this.remainderWallet.initBatchId({sourceWallet:i,isRemainder:!0}),i.splitUnits(n,this.remainderWallet,r);const l=await this.createMolecule({sourceWallet:i,remainderWallet:this.remainderWallet}),o=await this.createMoleculeMutation({mutationClass:Ge,molecule:l});return o.fillMolecule({recipientWallet:r,amount:s}),await this.executeQuery(o)}async depositBufferToken({tokenSlug:e,amount:t,tradeRates:s,sourceWallet:n=null}){null===n&&(n=await this.querySourceWallet({token:e,amount:t})),this.remainderWallet=D.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters}),this.remainderWallet.initBatchId({sourceWallet:n,isRemainder:!0});const a=await this.createMolecule({sourceWallet:n,remainderWallet:this.remainderWallet}),i=await this.createMoleculeMutation({mutationClass:Kt,molecule:a});return i.fillMolecule({amount:t,tradeRates:s}),await this.executeQuery(i)}async withdrawBufferToken({tokenSlug:e,amount:t,sourceWallet:s=null,signingWallet:n=null}){null===s&&(s=await this.querySourceWallet({token:e,amount:t,type:"buffer"})),this.remainderWallet=s;const a=await this.createMolecule({sourceWallet:s,remainderWallet:this.remainderWallet}),i=await this.createMoleculeMutation({mutationClass:Qt,molecule:a});let r={};return r[this.getBundle()]=t,i.fillMolecule({recipients:r,signingWallet:n}),await this.executeQuery(i)}async burnTokens({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){null===n&&(n=await this.querySourceWallet({token:e,amount:t}));let a=D.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});if(a.initBatchId({sourceWallet:n,isRemainder:!0}),s.length>0){if(t>0)throw new ct;t=s.length,n.splitUnits(s,a)}let i=await this.createMolecule({sourceWallet:n,remainderWallet:a});i.burnToken({amount:t}),i.sign({}),i.check();const r=await this.createMoleculeMutation({mutationClass:Ne,molecule:i});return this.executeQuery(r)}async replenishToken({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){if(null===n&&(n=(await this.queryBalance({token:e})).payload()),!n)throw new se("Source wallet is missing or invalid.");let a=D.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});a.initBatchId({sourceWallet:n,isRemainder:!0});let i=await this.createMolecule({sourceWallet:n,remainderWallet:a});i.replenishToken({amount:t,units:s}),i.sign({}),i.check();const r=await this.createMoleculeMutation({mutationClass:Ne,molecule:i});return this.executeQuery(r)}async fuseToken({bundleHash:e,tokenSlug:t,newTokenUnit:s,fusedTokenUnitIds:n,sourceWallet:a=null}){if(null===a&&(a=(await this.queryBalance({token:t})).payload()),null===a)throw new se("Source wallet is missing or invalid.");if(!a.tokenUnits||!a.tokenUnits.length)throw new se("Source wallet does not have token units.");if(!n.length)throw new se("Fused token unit list is empty.");let i=[];a.tokenUnits.forEach((e=>{i.push(e.id)})),n.forEach((e=>{if(!i.includes(e))throw new se(`Fused token unit ID = ${e} does not found in the source wallet.`)}));let r=D.create({secretOrBundle:e,token:t});r.initBatchId({sourceWallet:a});let l=D.create({secretOrBundle:this.getSecret(),token:t,batchId:a.batchId,characters:a.characters});l.initBatchId({sourceWallet:a,isRemainder:!0}),a.splitUnits(n,l),s.metas.fusedTokenUnits=a.getTokenUnitsData(),r.tokenUnits=[s];let o=await this.createMolecule({sourceWallet:a,remainderWallet:l});o.fuseToken(a.tokenUnits,r),o.sign({}),o.check();const u=await this.createMoleculeMutation({mutationClass:Ne,molecule:o});return this.executeQuery(u)}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);const s=new D({secret:E(),token:"AUTH"}),n=await this.createQuery(lt),a={cellSlug:e,pubkey:s.pubkey,encrypt:t},i=await n.execute(a);if(!i.success())throw new Wt(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);{const e=Ie.create(i.payload(),s);this.setAuthToken(e)}return i}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const s=new D({secret:e,token:"AUTH"}),n=await this.createMolecule({secret:e,sourceWallet:s}),a=await this.createMoleculeMutation({mutationClass:Ve,molecule:n});a.fillMolecule({meta:{encrypt:t?"true":"false"}});const i=await a.execute({});if(!i.success())throw new Wt(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);{const e=Ie.create(i.payload(),s);this.setAuthToken(e)}return i}async requestAuthToken({secret:e=null,seed:t=null,cellSlug:s=null,encrypt:n=!1}){if(this.$__serverSdkVersion<3)return this.$__logging&&console.warn("KnishIOClient::authorize() - Server SDK version does not require an authorization..."),null;let a;return null===e&&t&&(e=E(t)),this.$__authInProcess=!0,a=e?await this.requestProfileAuthToken({secret:e,encrypt:n}):await this.requestGuestAuthToken({cellSlug:s,encrypt:n}),this.$__logging&&console.info(`KnishIOClient::authorize() - Successfully retrieved auth token ${this.$__authToken.getToken()}...`),this.switchEncryption(n),this.$__authInProcess=!1,a}setAuthToken(e){e?(this.$__authTokenObjects[this.uri()]=e,this.client().setAuthData(e.getAuthData()),this.$__authToken=e):this.$__logging&&console.info("KnishIOClient::setAuthToken() - authToken object is empty.")}getAuthToken(){return this.$__authToken}}class Nt{static async run(e){for(let t in e){let s=new Nt(e[t]);await s.testAll()}}constructor(e,t=!1){this.encrypt=t,this.secrets=[E(),E()],this.tokenSlugs=["TESTTOKEN","UTENVSTACKABLE","UTSTACKUNIT","UTENVSTACKUNIT","UTSTACKUNITZONES","UTSLUG0","UTSLUG1"],this.graphqlUrl=e,console.log(`---------- GraphQL URI: ${this.graphqlUrl}`),this.clients={},this.tokenUnits=[["unit_id_1","unit_name_1"],["unit_id_2","unit_name_2"],["unit_id_3","unit_name_3"],["unit_id_4","unit_name_4"],["unit_id_5","unit_name_5"],["unit_id_6","unit_name_6"],["unit_id_7","unit_name_7"],["unit_id_8","unit_name_8"],["unit_id_9","unit_name_9"],["unit_id_10","unit_name_10"],["unit_id_11","unit_name_11"]],this.replenishTokenUnits=[["unit_id_12","unit_id_12"],["unit_id_13","unit_id_13"],["unit_id_14","unit_id_14"],["unit_id_15","unit_id_15"]];let s=(e,t=0)=>{let s=[];return e.forEach(((e,n)=>{let a=Array.from(e);a.push({fragmentZone:t+n}),s.push(a)})),s};this.tokenUnitsFZ=s(this.tokenUnits),this.replenishTokenUnitsFZ=s(Array.from(this.replenishTokenUnits),this.tokenUnits.length),this.fragmentZones=this.tokenUnitsFZ.length+this.replenishTokenUnitsFZ.length,this.fusedTokenUnitIds=[],this.tokenUnitsFZ.slice(0,5).forEach((e=>{this.fusedTokenUnitIds.push(e[0])}))}async testAll(){console.info(`Executing test for: ${this.graphqlUrl}...`),await this.client(this.secrets[0]),await this.client(this.secrets[1]),await this.testCreateToken(),await this.testFuseToken(),await this.testCreateWallet(),await this.testCreateMeta(),await this.testCreateIdentifier(),await this.testRequestTokens(),await this.testTransferToken(),await this.testBurnToken(),await this.testReplenishToken(),await this.testClaimShadowWallet(),await this.testWalletBufferTransactions(),await this.testQueryMeta(),await this.testQueryWallets(),await this.testQueryShadowWallets(),await this.testQueryBundle(),await this.testQueryBalance()}async testTokenExpiration(){const e=await this.client(this.secrets[0]),t=t=>{setTimeout((e=>{console.warn(`setTimeout ${t}`),e.queryMeta({metaType:"metaType",metaId:"metaId"})}),t,e,t)};t(3e3),t(3e4),t(61e3),t(64e3)}async testCreateToken(){let e={},t=await this.client(this.secrets[0]);e[0]=await t.createToken({token:this.tokenSlugs[0],amount:1e3,meta:{name:this.tokenSlugs[0],fungibility:"stackable",supply:"replenishable",decimals:0,icon:"icon"},batchId:"batch_0"}),this.checkResponse(e[0],"testCreateToken.0");let s=await this.client(process.env.SECRET_TOKEN_KNISH);e[1]=await s.createToken({token:this.tokenSlugs[1],amount:1e3,meta:{name:this.tokenSlugs[1],fungibility:"stackable",supply:"limited",decimals:0,icon:"icon"},batchId:"server_batch_0"}),this.checkResponse(e[1],"testCreateToken.1"),e[2]=await t.createToken({token:this.tokenSlugs[2],units:this.tokenUnits,meta:{name:this.tokenSlugs[2],supply:"replenishable",fungibility:"stackable"},batchId:"unit_batch_0"}),this.checkResponse(e[2],"testCreateToken.2"),e[3]=await s.createToken({token:this.tokenSlugs[3],units:this.tokenUnits,meta:{name:this.tokenSlugs[3],supply:"limited",fungibility:"stackable"},batchId:"server_unit_batch_0"}),this.checkResponse(e[3],"testCreateToken.3"),e[4]=await t.createToken({token:this.tokenSlugs[4],units:this.tokenUnitsFZ,meta:{name:this.tokenSlugs[4],supply:"replenishable",fungibility:"stackable",fragmentZones:this.fragmentZones},batchId:"unit_fz_batch_0"}),this.checkResponse(e[4],"testCreateToken.4"),t=await this.client(this.secrets[0]);for(const s of[this.tokenSlugs[5],this.tokenSlugs[6]])e[0]=await t.createToken({token:s,amount:1e3,meta:{name:s,fungibility:"fungible",supply:"limited",decimals:0,icon:"icon"}}),this.checkResponse(e[0],`testCreateToken.${s}`)}async testCreateWallet(){let e=await this.client(this.secrets[0]),t=await e.createWallet({token:this.tokenSlugs[1]});this.checkResponse(t,"testCreateWallet")}async testCreateMeta(){let e=await this.client(this.secrets[0]),t=await e.createMeta({metaType:"metaType",metaId:"metaId",meta:{key1:"value1",key2:"value2"}});this.checkResponse(t,"testCreateMeta")}async testCreateIdentifier(){let e=await this.client(this.secrets[0]),t=await e.createIdentifier({type:"email",contact:"test@test.com",code:"1234"});console.log(" ############### testCreateIdentifier ###############"),"Outdated code"!==t.reason()&&console.error("Error with response."),this.debug(t)}async testRequestTokens(){let e=await this.client(this.secrets[0]),t=await e.requestTokens({token:this.tokenSlugs[1],amount:10,to:this.secrets[0],batchId:"batch_5"});this.checkResponse(t,"testRequestTokens.1"),t=await e.requestTokens({token:this.tokenSlugs[3],units:["unit_id_10","unit_id_11"],to:this.secrets[0],batchId:"batch_6"}),this.checkResponse(t,"testRequestTokens.2")}async testTransferToken(){let e,t=K(this.secrets[1]),s=await this.client(this.secrets[0]);e=await s.transferToken({bundleHash:t,token:this.tokenSlugs[0],amount:10,batchId:"batch_1"}),this.checkResponse(e,"testTransferToken"),e=await s.transferToken({bundleHash:t,token:this.tokenSlugs[2],units:["unit_id_1","unit_id_2"],batchId:"batch_2"}),this.checkResponse(e,"testTransferUnitToken")}async testBurnToken(){let e,t=await this.client(this.secrets[0]);e=await t.burnTokens({token:this.tokenSlugs[0],amount:10}),this.checkResponse(e,"testBurnToken"),e=await t.burnTokens({token:this.tokenSlugs[2],units:["unit_id_3","unit_id_4"]}),this.checkResponse(e,"testBurnUnitToken")}async testReplenishToken(){let e,t=await this.client(this.secrets[0]);e=await t.replenishToken({token:this.tokenSlugs[0],amount:25}),this.checkResponse(e,"testReplenishToken"),e=await t.replenishToken({token:this.tokenSlugs[2],amount:0,units:this.replenishTokenUnits}),this.checkResponse(e,"testReplenishUnitToken")}async testFuseToken(){let e=this.tokenSlugs[4],t=E(),s=await this.client(t),n=new V("fusedTokenUnitId"),a=await this.client(this.secrets[0]),i=await a.fuseToken({bundleHash:s.getBundle(),tokenSlug:e,newTokenUnit:n,fusedTokenUnitIds:this.fusedTokenUnitIds});this.checkResponse(i,"testFuseToken");let r=(await s.queryBalance({token:e})).payload(),l=(await a.queryBalance({token:e})).payload();console.assert(r.tokenUnits.length,1),console.assert(r.tokenUnits[0].id,"fusedTokenUnitId");let o=r.tokenUnits[0].getFusedTokenUnits();console.assert(o.length,this.fusedTokenUnitIds.length);let u=[];o.forEach((e=>{u.push(e[0])})),console.assert(l.tokenUnits.length,6);let c=[];l.tokenUnits.forEach((e=>{c.push(e.id)})),console.assert(c,["unit_id_6","unit_id_7","unit_id_8","unit_id_9","unit_id_10","unit_id_11"])}async testClaimShadowWallet(){let e=await this.client(this.secrets[1]),t=await e.queryBalance({token:this.tokenSlugs[0]}),s=await e.claimShadowWallet({token:this.tokenSlugs[0],batchId:t.payload().batchId});this.checkResponse(s,"testClaimShadowWallet")}async testWalletBufferTransactions(){let e=await this.client(this.secrets[0]),t={};t[this.tokenSlugs[1]]=2,t[this.tokenSlugs[3]]=1;let s=await e.depositBufferToken({tokenSlug:this.tokenSlugs[5],amount:200,tradeRates:t});this.checkResponse(s,"testWalletBufferTransactions: depositBufferToken"),await e.withdrawBufferToken({tokenSlug:this.tokenSlugs[5],amount:100}),this.checkResponse(s,"testWalletBufferTransactions: withdrawBufferToken")}async testQueryMeta(){let e=await this.client(this.secrets[0]),t=await e.queryMeta({metaType:"metaType",metaId:"metaId"});this.checkResponse(t,"testQueryMeta")}async testQueryWallets(){let e=await this.client(this.secrets[0]),t=await e.queryWallets({});this.checkResponse(t,"testQueryWallets")}async testQueryShadowWallets(){let e=await this.client(this.secrets[1]),t=await e.queryShadowWallets({token:this.tokenSlugs[0]});this.checkResponse(t,"testQueryShadowWallets")}async testQueryBundle(){let e=await this.client(this.secrets[0]),t=await e.queryBundle({});this.checkResponse(t,"testQueryBundle")}async testQueryContinuId(){let e=K(this.secrets[0]),t=await this.client(this.secrets[0]),s=await t.queryContinuId({bundle:e});this.checkResponse(s,"testQueryContinuId")}async testQueryBalance(){let e=await this.client(this.secrets[0]),t=await e.queryBalance({token:this.tokenSlugs[0]});this.checkResponse(t,"testQueryBalance")}async client(e,t="unit_test"){return this.clients[e]||(this.clients[e]=new Pt({uri:this.graphqlUrl,logging:!0}),await this.clients[e].requestAuthToken({secret:e,encrypt:this.encrypt,cellSlug:t}),this.clients[e].getAuthToken()||console.log("Error with authorize - get an empty response.")),this.clients[e]}checkResponse(e,t){console.log(` ############### ${t} ###############`),console.log(e),e instanceof Qe?(e.success()||this.debug(e),console.assert(e.success(),e)):this.debug(e)}debug(e){e.data&&ke.get(e.data()||{},"reason")?console.log(e.data().reason):console.log(e)}}e.Atom=R,e.KnishIOClient=Pt,e.Meta=B,e.Molecule=we,e.Test=Nt,e.Wallet=D,e.base64ToHex=C,e.bufferToHexString=function(e){return T.toHex(e,{})},e.charsetBaseConvert=v,e.chunkSubstr=A,e.generateBundleHash=K,e.generateSecret=E,e.hexStringToBuffer=function(e){return T.toUint8Array(e)},e.hexToBase64=q,e.isHex=W,e.randomString=x,Object.defineProperty(e,"__esModule",{value:!0})}));
453
+ }`}createResponse(e){return new Ht({query:this,json:e})}static createVariables({metaType:e=null,metaId:t=null,key:s=null,value:n=null,keys:a=null,values:i=null,atomValues:r=null,latest:l=null,latestMetas:o=!0,filter:u=null,queryArgs:c=null,countBy:h=null}){const d={};return r&&(d.atomValues=r),a&&(d.keys=a),i&&(d.values=i),e&&(d.metaTypes="string"==typeof e?[e]:e),t&&(d.metaIds="string"==typeof t?[t]:t),h&&(d.countBy=h),u&&(d.filter=u),s&&n&&(d.filter=d.filter||[],d.filter.push({key:s,value:n,comparison:"="})),l&&(d.latest=!!l,d.latest=!!o),c&&(void 0!==c.limit&&0!==c.limit||(c.limit="*"),d.queryArgs=c),d}}class Rt extends Qe{}class Et extends Ne{fillMolecule({metaType:e,metaId:t,rule:s,policy:n}){this.$__molecule.createRule({metaType:e,metaId:t,rule:s,policy:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Rt({query:this,json:e})}}class Kt extends Ne{fillMolecule({amount:e,tradeRates:t}){this.$__molecule.initDepositBuffer({amount:e,tradeRates:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}class Qt extends Ne{fillMolecule({recipients:e,signingWallet:t}){this.$__molecule.initWithdrawBuffer({recipients:e,signingWallet:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}}class Pt{constructor({uri:e,cellSlug:t=null,client:s=null,socket:n=null,serverSdkVersion:a=3,logging:i=!1}){this.initialize({uri:e,cellSlug:t,socket:n,client:s,serverSdkVersion:a,logging:i})}initialize({uri:e,cellSlug:t=null,socket:s=null,client:n=null,serverSdkVersion:a=3,logging:i=!1}){this.$__logging=i,this.$__uris="object"==typeof e?e:[e],this.$__authTokenObjects={},this.$__authInProcess=!1,t&&this.setCellSlug(t);for(let e in this.$__uris){let t=this.$__uris[e];this.$__authTokenObjects[t]=null}this.$__logging&&console.info(`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${a}...`),this.reset(),this.$__client=n||new bt({socket:{socketUri:null,appKey:"knishio",...s||{}},serverUri:this.getRandomUri()}),this.$__serverSdkVersion=a}getRandomUri(){let e=Math.floor(Math.random()*this.$__uris.length);return this.$__uris[e]}switchEncryption(e){return this.$__encrypt!==e&&(this.$__logging&&console.info(`KnishIOClient::switchEncryption() - Forcing encryption ${e?"on":"off"} to match node...`),this.$__encrypt=e,this.$__client.setEncryption(e),!0)}deinitialize(){this.$__logging&&console.info("KnishIOClient::deinitialize() - Clearing the Knish.IO client session..."),this.reset()}subscribe(){if(!this.client().getSocketUri())throw new pe("KnishIOClient::subscribe() - Socket client not initialized!");return this.client()}getServerSdkVersion(){return this.$__serverSdkVersion}reset(){this.$__secret="",this.$__bundle="",this.remainderWallet=null}cellSlug(){return this.$__cellSlug||null}setCellSlug(e){this.$__cellSlug=e}uri(){return this.$__client.getUri()}client(){if(!this.$__authInProcess){let e=this.getRandomUri();this.$__client.setUri(e);let t=this.$__authTokenObjects[e];t?this.$__client.setAuthData(t.getAuthData()):this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt}).then((()=>{}))}return this.$__client}hasSecret(){return!!this.$__secret}setSecret(e){this.$__secret=e,this.$__bundle=K(e)}getSecret(){if(!this.hasSecret())throw new Ae("KnishIOClient::getSecret() - Unable to find a stored secret! Have you set a secret?");return this.$__secret}hasBundle(){return!!this.$__bundle}getBundle(){if(!this.hasBundle())throw new Ae("KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?");return this.$__bundle}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=D.generateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new D({secret:this.getSecret()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,sourceWallet:t=null,remainderWallet:s=null}){return this.$__logging&&console.info("KnishIOClient::createMolecule() - Creating a new molecule..."),e=e||this.getSecret(),!t&&this.lastMoleculeQuery&&"USER"===this.getRemainderWallet().token&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(t=this.getRemainderWallet()),null===t&&(t=await this.getSourceWallet()),this.remainderWallet=s||D.create({secretOrBundle:e,token:"USER",batchId:t.batchId,characters:t.characters}),new we({secret:e,sourceWallet:t,remainderWallet:this.getRemainderWallet(),cellSlug:this.cellSlug()})}createQuery(e){return new e(this.client())}createSubscribe(e){return new e(this.subscribe())}async createMoleculeMutation({mutationClass:e,molecule:t=null}){this.$__logging&&console.info(`KnishIOClient::createMoleculeQuery() - Creating a new ${e.name} query...`);let s=t||await this.createMolecule({});const n=new e(this.client(),s);if(!(n instanceof Ne))throw new pe(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=n,n}async executeQuery(e,t=null){return this.$__authToken&&this.$__authToken.isExpired()&&(console.info("KnishIOClient::executeQuery() - Access token is expired. Getting new one..."),await this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt})),e.execute({variables:t})}async queryBalance({token:e,bundle:t=null,type:s="regular"}){const n=this.createQuery(He);return this.executeQuery(n,{bundleHash:t||this.getBundle(),token:e,type:s})}async querySourceWallet({token:e,amount:t,type:s="regular"}){let n=(await this.queryBalance({token:e,type:s})).payload();if(null===n||Se.cmp(n.balance,t)<0)throw new se;if(!n.position||!n.address)throw new se("Source wallet can not be a shadow wallet.");return n}async subscribeCreateMolecule({bundle:e,closure:t}){const s=this.createSubscribe(ft);return await s.execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:s}){if(!t)throw new pe(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(wt).execute({variables:{bundle:e||this.getBundle(),token:t},closure:s})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe($t).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:s}){return this.createSubscribe(St).execute({variables:{metaType:e,metaId:t},closure:s})}unsubscribe(e){this.subscribe().unsubscribe(e)}unsubscribeAll(){this.subscribe().unsubscribeAll()}queryMeta({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:a=null,latestMetas:i=null,fields:r=null,filter:l=null,queryArgs:o=null,count:u=null,countBy:c=null,throughAtom:h=!1,values:d=null,keys:p=null,atomValues:m=null}){let y,g;return this.$__logging&&console.info(`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`),h?(y=this.createQuery(jt),g=jt.createVariables({metaType:e,metaId:t,key:s,value:n,latest:a,latestMetas:i,filter:l,queryArgs:o,countBy:c,values:d,keys:p,atomValues:m})):(y=this.createQuery(Re),g=Re.createVariables({metaType:e,metaId:t,key:s,value:n,latest:a,latestMetas:i,filter:l,queryArgs:o,count:u,countBy:c})),this.executeQuery(y,g).then((e=>e.payload()))}queryMetaInstance({metaType:e,metaId:t=null,key:s=null,value:n=null,latest:a=null,filter:i=null,fields:r=null}){this.$__logging&&console.info(`KnishIOClient::queryMetaInstance() - Querying metaType: ${e}, metaId: ${t}...`);const l=this.createQuery(Re),o={metaType:e,metaIds:[t],keys:[s],values:[n],latest:a,filter:i};return this.executeQuery(l,o).then((e=>e.data()))}async queryBatch({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Ee);return await this.executeQuery(t,{batchId:e})}async queryBatchHistory({batchId:e}){this.$__logging&&console.info(`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);const t=this.createQuery(Ke);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:k,metaTypes:b,metaType:_,metaIds:f,metaId:w,indexes:$,index:S,filter:I,latest:T,queryArgs:A={limit:15,offset:1}}){this.$__logging&&console.info("KnishIOClient::queryAtom() - Querying atom instances");const x=this.createQuery(Mt);return await this.executeQuery(x,Mt.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:s,bundleHash:n,positions:a,position:i,walletAddresses:r,walletAddress:l,isotopes:o,isotope:u,tokenSlugs:c,tokenSlug:h,cellSlugs:d,cellSlug:p,batchIds:m,batchId:y,values:g,value:k,metaTypes:b,metaType:_,metaIds:f,metaId:w,indexes:$,index:S,filter:I,latest:T,queryArgs:A}))}async createWallet({token:e}){const t=new D({secret:this.getSecret(),token:e}),s=await this.createMoleculeMutation({mutationClass:it});return s.fillMolecule(t),await this.executeQuery(s)}async queryActiveSession({bundleHash:e,metaType:t,metaId:s}){const n=this.createQuery(xt);return await this.executeQuery(n,{bundleHash:e,metaType:t,metaId:s})}async queryUserActivity({bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,countBy:o,interval:u}){const c=this.createQuery(qt);return await this.executeQuery(c,{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,countBy:o,interval:u})}async activeSession({bundle:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,json:o={}}){const u=this.createQuery(Tt);return await this.executeQuery(u,{bundleHash:e,metaType:t,metaId:s,ipAddress:n,browser:a,osCpu:i,resolution:r,timeZone:l,json:JSON.stringify(o)})}async createToken({token:e,amount:t=null,meta:s=null,batchId:n=null,units:a=[]}){const i=ke.get(s||{},"fungibility");if("stackable"===i&&(s.batchId=n||Q({})),["nonfungible","stackable"].includes(i)&&a.length>0){if(ke.get(s||{},"decimals")>0)throw new ut;if(t>0)throw new ct;t=a.length,s.splittable=1,s.decimals=0,s.tokenUnits=JSON.stringify(a)}const r=new D({secret:this.getSecret(),token:e,batchId:n}),l=await this.createMoleculeMutation({mutationClass:De});return l.fillMolecule({recipientWallet:r,amount:t,meta:s||{}}),await this.executeQuery(l)}async createRule({metaType:e,metaId:t,rule:s,policy:n={}}){const a=await this.createMoleculeMutation({mutationClass:Et,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})});return a.fillMolecule({metaType:e,metaId:t,rule:s,policy:n}),await this.executeQuery(a)}async createMeta({metaType:e,metaId:t,meta:s=null,policy:n={}}){const a=await this.createMoleculeMutation({mutationClass:nt,molecule:await this.createMolecule({secret:this.getSecret(),sourceWallet:await this.getSourceWallet()})}),i=s||{};return a.fillMolecule({metaType:e,metaId:t,meta:i,policy:n}),await this.executeQuery(a)}async createIdentifier({type:e,contact:t,code:s}){const n=await this.createMoleculeMutation({mutationClass:Ye});return n.fillMolecule({type:e,contact:t,code:s}),await this.executeQuery(n)}async createPolicy({metaType:e,metaId:t,policy:s={}}){let n=await this.createMolecule({});n.addPolicyAtom({metaType:e,metaId:t,meta:{},policy:s}),n.addContinuIdAtom(),n.sign({}),n.check();const a=await this.createMoleculeMutation({mutationClass:Ne,molecule:n});return await this.executeQuery(a)}async queryPolicy({metaType:e,metaId:t}){const s=this.createQuery(Ot);return await this.executeQuery(s,{metaType:e,metaId:t})}queryWallets({bundle:e=null,token:t=null,unspent:s=!0}){this.$__logging&&console.info(`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:""}...`);const n=this.createQuery(Ue);return this.executeQuery(n,{bundleHash:e||this.getBundle(),token:t,unspent:s}).then((e=>e.payload()))}queryShadowWallets({token:e="KNISH",bundle:t=null}){t=t||this.getBundle(),this.$__logging&&console.info(`KnishIOClient::queryShadowWallets() - Querying ${e} shadow wallets for ${t}...`);const s=this.createQuery(Ue);return this.executeQuery(s,{bundleHash:t,token:e}).then((e=>e.payload()))}queryBundle({bundle:e=null,key:t=null,value:s=null,latest:n=!0,fields:a=null,raw:i=!1}){this.$__logging&&console.info(`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:""}...`);const r=this.createQuery(Be),l=Be.createVariables({bundleHash:e||this.getBundle(),key:t,value:s,latest:n});return this.executeQuery(r,l).then((e=>i?e:e.payload()))}async queryContinuId({bundle:e}){const t=this.createQuery(Ce);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:s=null,units:n=[],meta:a=null,batchId:i=null}){let r,l;a=a||{};const o=this.createQuery(Ct),u=await this.executeQuery(o,{slug:e}),c="stackable"===ke.get(u.data(),"0.fungibility");if(!c&&null!==i)throw new ce("Expected Batch ID = null for non-stackable tokens.");if(c&&null===i&&(i=Q({})),n.length>0){if(s>0)throw new ct;s=n.length,a.tokenUnits=JSON.stringify(n)}t?("[object String]"===Object.prototype.toString.call(t)&&(D.isBundleHash(t)?(r="walletBundle",l=t):t=D.create({secretOrBundle:t,token:e})),t instanceof D&&(r="wallet",a.position=t.position,a.bundle=t.bundle,l=t.address)):(r="walletBundle",l=this.getBundle());const h=await this.createMoleculeMutation({mutationClass:ze});return h.fillMolecule({token:e,amount:s,metaType:r,metaId:l,meta:a,batchId:i}),await this.executeQuery(h)}async claimShadowWallet({token:e,batchId:t=null,molecule:s=null}){const n=await this.createMoleculeMutation({mutationClass:tt,molecule:s});return n.fillMolecule({token:e,batchId:t}),await this.executeQuery(n)}async claimShadowWallets({token:e}){const t=await this.queryShadowWallets({token:e});if(!t||!Array.isArray(t))throw new ot;t.forEach((e=>{if(!e.isShadow())throw new ot}));let s=[];for(const n of t)s.push(await this.claimShadowWallet({token:e,batchId:n.batchId}));return s}async transferToken({bundleHash:e,token:t,amount:s=null,units:n=[],batchId:a=null,sourceWallet:i=null}){if(n.length>0){if(s>0)throw new ct;s=n.length}if(null===i&&(i=await this.querySourceWallet({token:t,amount:s})),null===i||Se.cmp(i.balance,s)<0)throw new se;let r=D.create({secretOrBundle:e,token:t});null!==a?r.batchId=a:r.initBatchId({sourceWallet:i}),this.remainderWallet=D.create({secretOrBundle:this.getSecret(),token:t,characters:i.characters}),this.remainderWallet.initBatchId({sourceWallet:i,isRemainder:!0}),i.splitUnits(n,this.remainderWallet,r);const l=await this.createMolecule({sourceWallet:i,remainderWallet:this.remainderWallet}),o=await this.createMoleculeMutation({mutationClass:Ge,molecule:l});return o.fillMolecule({recipientWallet:r,amount:s}),await this.executeQuery(o)}async depositBufferToken({tokenSlug:e,amount:t,tradeRates:s,sourceWallet:n=null}){null===n&&(n=await this.querySourceWallet({token:e,amount:t})),this.remainderWallet=D.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters}),this.remainderWallet.initBatchId({sourceWallet:n,isRemainder:!0});const a=await this.createMolecule({sourceWallet:n,remainderWallet:this.remainderWallet}),i=await this.createMoleculeMutation({mutationClass:Kt,molecule:a});return i.fillMolecule({amount:t,tradeRates:s}),await this.executeQuery(i)}async withdrawBufferToken({tokenSlug:e,amount:t,sourceWallet:s=null,signingWallet:n=null}){null===s&&(s=await this.querySourceWallet({token:e,amount:t,type:"buffer"})),this.remainderWallet=s;const a=await this.createMolecule({sourceWallet:s,remainderWallet:this.remainderWallet}),i=await this.createMoleculeMutation({mutationClass:Qt,molecule:a});let r={};return r[this.getBundle()]=t,i.fillMolecule({recipients:r,signingWallet:n}),await this.executeQuery(i)}async burnTokens({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){null===n&&(n=await this.querySourceWallet({token:e,amount:t}));let a=D.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});if(a.initBatchId({sourceWallet:n,isRemainder:!0}),s.length>0){if(t>0)throw new ct;t=s.length,n.splitUnits(s,a)}let i=await this.createMolecule({sourceWallet:n,remainderWallet:a});i.burnToken({amount:t}),i.sign({}),i.check();const r=await this.createMoleculeMutation({mutationClass:Ne,molecule:i});return this.executeQuery(r)}async replenishToken({token:e,amount:t=null,units:s=[],sourceWallet:n=null}){if(null===n&&(n=(await this.queryBalance({token:e})).payload()),!n)throw new se("Source wallet is missing or invalid.");let a=D.create({secretOrBundle:this.getSecret(),token:e,characters:n.characters});a.initBatchId({sourceWallet:n,isRemainder:!0});let i=await this.createMolecule({sourceWallet:n,remainderWallet:a});i.replenishToken({amount:t,units:s}),i.sign({}),i.check();const r=await this.createMoleculeMutation({mutationClass:Ne,molecule:i});return this.executeQuery(r)}async fuseToken({bundleHash:e,tokenSlug:t,newTokenUnit:s,fusedTokenUnitIds:n,sourceWallet:a=null}){if(null===a&&(a=(await this.queryBalance({token:t})).payload()),null===a)throw new se("Source wallet is missing or invalid.");if(!a.tokenUnits||!a.tokenUnits.length)throw new se("Source wallet does not have token units.");if(!n.length)throw new se("Fused token unit list is empty.");let i=[];a.tokenUnits.forEach((e=>{i.push(e.id)})),n.forEach((e=>{if(!i.includes(e))throw new se(`Fused token unit ID = ${e} does not found in the source wallet.`)}));let r=D.create({secretOrBundle:e,token:t});r.initBatchId({sourceWallet:a});let l=D.create({secretOrBundle:this.getSecret(),token:t,batchId:a.batchId,characters:a.characters});l.initBatchId({sourceWallet:a,isRemainder:!0}),a.splitUnits(n,l),s.metas.fusedTokenUnits=a.getTokenUnitsData(),r.tokenUnits=[s];let o=await this.createMolecule({sourceWallet:a,remainderWallet:l});o.fuseToken(a.tokenUnits,r),o.sign({}),o.check();const u=await this.createMoleculeMutation({mutationClass:Ne,molecule:o});return this.executeQuery(u)}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);const s=new D({secret:E(),token:"AUTH"}),n=await this.createQuery(lt),a={cellSlug:e,pubkey:s.pubkey,encrypt:t},i=await n.execute(a);if(!i.success())throw new Wt(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);{const e=Ie.create(i.payload(),s);this.setAuthToken(e)}return i}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);const s=new D({secret:e,token:"AUTH"}),n=await this.createMolecule({secret:e,sourceWallet:s}),a=await this.createMoleculeMutation({mutationClass:Ve,molecule:n});a.fillMolecule({meta:{encrypt:t?"true":"false"}});const i=await a.execute({});if(!i.success())throw new Wt(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${i.reason()}`);{const e=Ie.create(i.payload(),s);this.setAuthToken(e)}return i}async requestAuthToken({secret:e=null,seed:t=null,cellSlug:s=null,encrypt:n=!1}){if(this.$__serverSdkVersion<3)return this.$__logging&&console.warn("KnishIOClient::authorize() - Server SDK version does not require an authorization..."),null;let a;return null===e&&t&&(e=E(t)),this.$__authInProcess=!0,a=e?await this.requestProfileAuthToken({secret:e,encrypt:n}):await this.requestGuestAuthToken({cellSlug:s,encrypt:n}),this.$__logging&&console.info(`KnishIOClient::authorize() - Successfully retrieved auth token ${this.$__authToken.getToken()}...`),this.switchEncryption(n),this.$__authInProcess=!1,a}setAuthToken(e){e?(this.$__authTokenObjects[this.uri()]=e,this.client().setAuthData(e.getAuthData()),this.$__authToken=e):this.$__logging&&console.info("KnishIOClient::setAuthToken() - authToken object is empty.")}getAuthToken(){return this.$__authToken}}class Nt{static async run(e){for(let t in e){let s=new Nt(e[t]);await s.testAll()}}constructor(e,t=!1){this.encrypt=t,this.secrets=[E(),E()],this.tokenSlugs=["TESTTOKEN","UTENVSTACKABLE","UTSTACKUNIT","UTENVSTACKUNIT","UTSTACKUNITZONES","UTSLUG0","UTSLUG1"],this.graphqlUrl=e,console.log(`---------- GraphQL URI: ${this.graphqlUrl}`),this.clients={},this.tokenUnits=[["unit_id_1","unit_name_1"],["unit_id_2","unit_name_2"],["unit_id_3","unit_name_3"],["unit_id_4","unit_name_4"],["unit_id_5","unit_name_5"],["unit_id_6","unit_name_6"],["unit_id_7","unit_name_7"],["unit_id_8","unit_name_8"],["unit_id_9","unit_name_9"],["unit_id_10","unit_name_10"],["unit_id_11","unit_name_11"]],this.replenishTokenUnits=[["unit_id_12","unit_id_12"],["unit_id_13","unit_id_13"],["unit_id_14","unit_id_14"],["unit_id_15","unit_id_15"]];let s=(e,t=0)=>{let s=[];return e.forEach(((e,n)=>{let a=Array.from(e);a.push({fragmentZone:t+n}),s.push(a)})),s};this.tokenUnitsFZ=s(this.tokenUnits),this.replenishTokenUnitsFZ=s(Array.from(this.replenishTokenUnits),this.tokenUnits.length),this.fragmentZones=this.tokenUnitsFZ.length+this.replenishTokenUnitsFZ.length,this.fusedTokenUnitIds=[],this.tokenUnitsFZ.slice(0,5).forEach((e=>{this.fusedTokenUnitIds.push(e[0])}))}async testAll(){console.info(`Executing test for: ${this.graphqlUrl}...`),await this.client(this.secrets[0]),await this.client(this.secrets[1]),await this.testCreateToken(),await this.testFuseToken(),await this.testCreateWallet(),await this.testCreateMeta(),await this.testCreateIdentifier(),await this.testRequestTokens(),await this.testTransferToken(),await this.testBurnToken(),await this.testReplenishToken(),await this.testClaimShadowWallet(),await this.testWalletBufferTransactions(),await this.testQueryMeta(),await this.testQueryWallets(),await this.testQueryShadowWallets(),await this.testQueryBundle(),await this.testQueryBalance()}async testTokenExpiration(){const e=await this.client(this.secrets[0]),t=t=>{setTimeout((e=>{console.warn(`setTimeout ${t}`),e.queryMeta({metaType:"metaType",metaId:"metaId"})}),t,e,t)};t(3e3),t(3e4),t(61e3),t(64e3)}async testCreateToken(){let e={},t=await this.client(this.secrets[0]);e[0]=await t.createToken({token:this.tokenSlugs[0],amount:1e3,meta:{name:this.tokenSlugs[0],fungibility:"stackable",supply:"replenishable",decimals:0,icon:"icon"},batchId:"batch_0"}),this.checkResponse(e[0],"testCreateToken.0");let s=await this.client(process.env.SECRET_TOKEN_KNISH);e[1]=await s.createToken({token:this.tokenSlugs[1],amount:1e3,meta:{name:this.tokenSlugs[1],fungibility:"stackable",supply:"limited",decimals:0,icon:"icon"},batchId:"server_batch_0"}),this.checkResponse(e[1],"testCreateToken.1"),e[2]=await t.createToken({token:this.tokenSlugs[2],units:this.tokenUnits,meta:{name:this.tokenSlugs[2],supply:"replenishable",fungibility:"stackable"},batchId:"unit_batch_0"}),this.checkResponse(e[2],"testCreateToken.2"),e[3]=await s.createToken({token:this.tokenSlugs[3],units:this.tokenUnits,meta:{name:this.tokenSlugs[3],supply:"limited",fungibility:"stackable"},batchId:"server_unit_batch_0"}),this.checkResponse(e[3],"testCreateToken.3"),e[4]=await t.createToken({token:this.tokenSlugs[4],units:this.tokenUnitsFZ,meta:{name:this.tokenSlugs[4],supply:"replenishable",fungibility:"stackable",fragmentZones:this.fragmentZones},batchId:"unit_fz_batch_0"}),this.checkResponse(e[4],"testCreateToken.4"),t=await this.client(this.secrets[0]);for(const s of[this.tokenSlugs[5],this.tokenSlugs[6]])e[0]=await t.createToken({token:s,amount:1e3,meta:{name:s,fungibility:"fungible",supply:"limited",decimals:0,icon:"icon"}}),this.checkResponse(e[0],`testCreateToken.${s}`)}async testCreateWallet(){let e=await this.client(this.secrets[0]),t=await e.createWallet({token:this.tokenSlugs[1]});this.checkResponse(t,"testCreateWallet")}async testCreateMeta(){let e=await this.client(this.secrets[0]),t=await e.createMeta({metaType:"metaType",metaId:"metaId",meta:{key1:"value1",key2:"value2"}});this.checkResponse(t,"testCreateMeta")}async testCreateIdentifier(){let e=await this.client(this.secrets[0]),t=await e.createIdentifier({type:"email",contact:"test@test.com",code:"1234"});console.log(" ############### testCreateIdentifier ###############"),"Outdated code"!==t.reason()&&console.error("Error with response."),this.debug(t)}async testRequestTokens(){let e=await this.client(this.secrets[0]),t=await e.requestTokens({token:this.tokenSlugs[1],amount:10,to:this.secrets[0],batchId:"batch_5"});this.checkResponse(t,"testRequestTokens.1"),t=await e.requestTokens({token:this.tokenSlugs[3],units:["unit_id_10","unit_id_11"],to:this.secrets[0],batchId:"batch_6"}),this.checkResponse(t,"testRequestTokens.2")}async testTransferToken(){let e,t=K(this.secrets[1]),s=await this.client(this.secrets[0]);e=await s.transferToken({bundleHash:t,token:this.tokenSlugs[0],amount:10,batchId:"batch_1"}),this.checkResponse(e,"testTransferToken"),e=await s.transferToken({bundleHash:t,token:this.tokenSlugs[2],units:["unit_id_1","unit_id_2"],batchId:"batch_2"}),this.checkResponse(e,"testTransferUnitToken")}async testBurnToken(){let e,t=await this.client(this.secrets[0]);e=await t.burnTokens({token:this.tokenSlugs[0],amount:10}),this.checkResponse(e,"testBurnToken"),e=await t.burnTokens({token:this.tokenSlugs[2],units:["unit_id_3","unit_id_4"]}),this.checkResponse(e,"testBurnUnitToken")}async testReplenishToken(){let e,t=await this.client(this.secrets[0]);e=await t.replenishToken({token:this.tokenSlugs[0],amount:25}),this.checkResponse(e,"testReplenishToken"),e=await t.replenishToken({token:this.tokenSlugs[2],amount:0,units:this.replenishTokenUnits}),this.checkResponse(e,"testReplenishUnitToken")}async testFuseToken(){let e=this.tokenSlugs[4],t=E(),s=await this.client(t),n=new V("fusedTokenUnitId"),a=await this.client(this.secrets[0]),i=await a.fuseToken({bundleHash:s.getBundle(),tokenSlug:e,newTokenUnit:n,fusedTokenUnitIds:this.fusedTokenUnitIds});this.checkResponse(i,"testFuseToken");let r=(await s.queryBalance({token:e})).payload(),l=(await a.queryBalance({token:e})).payload();console.assert(r.tokenUnits.length,1),console.assert(r.tokenUnits[0].id,"fusedTokenUnitId");let o=r.tokenUnits[0].getFusedTokenUnits();console.assert(o.length,this.fusedTokenUnitIds.length);let u=[];o.forEach((e=>{u.push(e[0])})),console.assert(l.tokenUnits.length,6);let c=[];l.tokenUnits.forEach((e=>{c.push(e.id)})),console.assert(c,["unit_id_6","unit_id_7","unit_id_8","unit_id_9","unit_id_10","unit_id_11"])}async testClaimShadowWallet(){let e=await this.client(this.secrets[1]),t=await e.queryBalance({token:this.tokenSlugs[0]}),s=await e.claimShadowWallet({token:this.tokenSlugs[0],batchId:t.payload().batchId});this.checkResponse(s,"testClaimShadowWallet")}async testWalletBufferTransactions(){let e=await this.client(this.secrets[0]),t={};t[this.tokenSlugs[1]]=2,t[this.tokenSlugs[3]]=1;let s=await e.depositBufferToken({tokenSlug:this.tokenSlugs[5],amount:200,tradeRates:t});this.checkResponse(s,"testWalletBufferTransactions: depositBufferToken"),await e.withdrawBufferToken({tokenSlug:this.tokenSlugs[5],amount:100}),this.checkResponse(s,"testWalletBufferTransactions: withdrawBufferToken")}async testQueryMeta(){let e=await this.client(this.secrets[0]),t=await e.queryMeta({metaType:"metaType",metaId:"metaId"});this.checkResponse(t,"testQueryMeta")}async testQueryWallets(){let e=await this.client(this.secrets[0]),t=await e.queryWallets({});this.checkResponse(t,"testQueryWallets")}async testQueryShadowWallets(){let e=await this.client(this.secrets[1]),t=await e.queryShadowWallets({token:this.tokenSlugs[0]});this.checkResponse(t,"testQueryShadowWallets")}async testQueryBundle(){let e=await this.client(this.secrets[0]),t=await e.queryBundle({});this.checkResponse(t,"testQueryBundle")}async testQueryContinuId(){let e=K(this.secrets[0]),t=await this.client(this.secrets[0]),s=await t.queryContinuId({bundle:e});this.checkResponse(s,"testQueryContinuId")}async testQueryBalance(){let e=await this.client(this.secrets[0]),t=await e.queryBalance({token:this.tokenSlugs[0]});this.checkResponse(t,"testQueryBalance")}async client(e,t="unit_test"){return this.clients[e]||(this.clients[e]=new Pt({uri:this.graphqlUrl,logging:!0}),await this.clients[e].requestAuthToken({secret:e,encrypt:this.encrypt,cellSlug:t}),this.clients[e].getAuthToken()||console.log("Error with authorize - get an empty response.")),this.clients[e]}checkResponse(e,t){console.log(` ############### ${t} ###############`),console.log(e),e instanceof Qe?(e.success()||this.debug(e),console.assert(e.success(),e)):this.debug(e)}debug(e){e.data&&ke.get(e.data()||{},"reason")?console.log(e.data().reason):console.log(e)}}e.Atom=R,e.KnishIOClient=Pt,e.Meta=B,e.Molecule=we,e.Test=Nt,e.Wallet=D,e.base64ToHex=C,e.bufferToHexString=function(e){return T.toHex(e,{})},e.charsetBaseConvert=v,e.chunkSubstr=A,e.generateBundleHash=K,e.generateSecret=E,e.hexStringToBuffer=function(e){return T.toUint8Array(e)},e.hexToBase64=q,e.isHex=W,e.randomString=x,Object.defineProperty(e,"__esModule",{value:!0})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wishknish/knishio-client-js",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
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",
@@ -1124,33 +1124,32 @@ export default class KnishIOClient {
1124
1124
  units = []
1125
1125
  } ) {
1126
1126
 
1127
- // Stackable tokens need a new batch for every transfer
1128
- if ( Dot.get( meta || {}, 'fungibility' ) === 'stackable' ) {
1127
+ // What is the fungibility mode for this token?
1128
+ const fungibility = Dot.get( meta || {}, 'fungibility' );
1129
1129
 
1130
- // No batch ID specified? Create a random one
1131
- if ( !batchId ) {
1132
- batchId = generateBatchId( {} );
1133
- }
1134
- meta.batchId = batchId;
1135
-
1136
- // Adding unit IDs to the token
1137
- if ( units.length > 0 ) {
1130
+ // For stackable token - create a batch ID
1131
+ if ( fungibility === 'stackable' ) {
1132
+ meta.batchId = batchId || generateBatchId( {} );
1133
+ }
1138
1134
 
1139
- // Stackable tokens with Unit IDs must not use decimals
1140
- if ( Dot.get( meta || {}, 'decimals' ) > 0 ) {
1141
- throw new StackableUnitDecimalsException();
1142
- }
1135
+ // Special logic for token unit initialization (nonfungible || stackable)
1136
+ if ( [ 'nonfungible', 'stackable' ].includes( fungibility ) && units.length > 0 ) {
1143
1137
 
1144
- // Can't create stackable units AND provide amount
1145
- if ( amount > 0 ) {
1146
- throw new StackableUnitAmountException();
1147
- }
1138
+ // Stackable tokens with Unit IDs must not use decimals
1139
+ if ( Dot.get( meta || {}, 'decimals' ) > 0 ) {
1140
+ throw new StackableUnitDecimalsException();
1141
+ }
1148
1142
 
1149
- // Calculating amount based on Unit IDs
1150
- amount = units.length;
1151
- meta.splittable = 1;
1152
- meta.tokenUnits = JSON.stringify( units );
1143
+ // Can't create stackable units AND provide amount
1144
+ if ( amount > 0 ) {
1145
+ throw new StackableUnitAmountException();
1153
1146
  }
1147
+
1148
+ // Calculating amount based on Unit IDs
1149
+ amount = units.length;
1150
+ meta.splittable = 1;
1151
+ meta.decimals = 0;
1152
+ meta.tokenUnits = JSON.stringify( units );
1154
1153
  }
1155
1154
 
1156
1155
  // Creating the wallet that will receive the new tokens
@@ -0,0 +1,340 @@
1
+ /*
2
+ (
3
+ (/(
4
+ (//(
5
+ (///(
6
+ (/////(
7
+ (//////( )
8
+ (////////( (/)
9
+ (////////( (///)
10
+ (//////////( (////)
11
+ (//////////( (//////)
12
+ (////////////( (///////)
13
+ (/////////////( (/////////)
14
+ (//////////////( (///////////)
15
+ (///////////////( (/////////////)
16
+ (////////////////( (//////////////)
17
+ ((((((((((((((((((( (((((((((((((((
18
+ ((((((((((((((((((( ((((((((((((((
19
+ ((((((((((((((((((( ((((((((((((((
20
+ (((((((((((((((((((( (((((((((((((
21
+ (((((((((((((((((((( ((((((((((((
22
+ ((((((((((((((((((( ((((((((((((
23
+ ((((((((((((((((((( ((((((((((
24
+ ((((((((((((((((((/ (((((((((
25
+ (((((((((((((((((( ((((((((
26
+ ((((((((((((((((( (((((((
27
+ (((((((((((((((((( (((((
28
+ ################# ##
29
+ ################ #
30
+ ################# ##
31
+ %################ ###
32
+ ###############( ####
33
+ ############### ####
34
+ ############### ######
35
+ %#############( (#######
36
+ %############# #########
37
+ ############( ##########
38
+ ########### #############
39
+ ######### ##############
40
+ %######
41
+
42
+ Powered by Knish.IO: Connecting a Decentralized World
43
+
44
+ Please visit https://github.com/WishKnish/KnishIO-Client-JS for information.
45
+
46
+ License: https://github.com/WishKnish/KnishIO-Client-JS/blob/master/LICENSE
47
+ */
48
+ import KnishIOClient from '../KnishIOClient';
49
+ import Dot from '../libraries/Dot';
50
+ import {
51
+ generateBundleHash,
52
+ generateSecret
53
+ } from '../libraries/crypto';
54
+ import ResponseMolecule from '../response/ResponseProposeMolecule';
55
+ import TokenUnit from '../TokenUnit';
56
+
57
+ /*
58
+
59
+ import Test from '@wishknish/knishio-client-js/src/test/Test';
60
+ import { KNISHIO_SETTINGS, } from 'src/libraries/constants/knishio';
61
+
62
+ // Run all test
63
+ await TestTokenUnit.run( KNISHIO_SETTINGS.serverUriConfig );
64
+
65
+ */
66
+
67
+ export default class TestTokenUnit {
68
+
69
+ /**
70
+ * Run all
71
+ */
72
+ static async run ( uris ) {
73
+ for ( let uriIndex in uris ) {
74
+ let test = new TestTokenUnit( uris[ uriIndex ] );
75
+ await test.testAll();
76
+ }
77
+ }
78
+
79
+ /**
80
+ *
81
+ * @param graphqlUrl
82
+ * @param encrypt
83
+ */
84
+ constructor ( graphqlUrl, encrypt = false ) {
85
+ this.encrypt = encrypt;
86
+ this.secrets = [ generateSecret(), generateSecret() ];
87
+ this.tokenSlugs = [ 'UTNFUNGUNIT' ];
88
+ this.graphqlUrl = graphqlUrl;
89
+ console.log( `---------- GraphQL URI: ${ this.graphqlUrl }` );
90
+
91
+ this.clients = {};
92
+ this.tokenUnits = [
93
+ [ 'unit_id_1', 'unit_name_1', {url: "test1.com"} ],
94
+ [ 'unit_id_2', 'unit_name_2', {url: "test2.com"} ],
95
+ [ 'unit_id_3', 'unit_name_3', {url: "test3.com"} ],
96
+ [ 'unit_id_4', 'unit_name_4', {url: "test4.com"} ],
97
+ [ 'unit_id_5', 'unit_name_5', {url: "test5.com"} ],
98
+ [ 'unit_id_6', 'unit_name_6', {url: "test6.com"} ],
99
+ ];
100
+ }
101
+
102
+
103
+ /**
104
+ * Test all KnishIOClient functions
105
+ */
106
+ async testAll () {
107
+ console.info( `Executing test for: ${ this.graphqlUrl }...` );
108
+
109
+ await this.client( this.secrets[ 0 ] );
110
+ await this.client( this.secrets[ 1 ] );
111
+
112
+ await this.testCreateToken();
113
+ await this.queryWalletsOutput();
114
+
115
+ await this.testTransferToken1();
116
+ await this.queryWalletsOutput();
117
+
118
+ await this.testTransferToken2();
119
+ await this.queryWalletsOutput();
120
+
121
+ await this.testClaimShadowWallet();
122
+ await this.queryWalletsOutput();
123
+
124
+ await this.testTransferTokenBack1();
125
+ await this.queryWalletsOutput();
126
+
127
+ await this.testTransferTokenBack2();
128
+ await this.queryWalletsOutput();
129
+ }
130
+
131
+ /**
132
+ * @throws \Exception
133
+ */
134
+ async testCreateToken () {
135
+
136
+ let responses = {};
137
+
138
+ // Regular stackable token
139
+ let client = await this.client( this.secrets[ 0 ] );
140
+
141
+ // --------- UNITABLE TOKENS ----------
142
+
143
+ // Create stackable unit token
144
+ responses[ 0 ] = await client.createToken( {
145
+ token: this.tokenSlugs[ 0 ],
146
+ units: this.tokenUnits,
147
+ meta: {
148
+ name: this.tokenSlugs[ 0 ],
149
+ supply: 'replenishable',
150
+ fungibility: 'nonfungible'
151
+ }
152
+ } );
153
+ this.checkResponse( responses[ 0 ], 'testCreateToken.0' );
154
+ }
155
+
156
+
157
+ /**
158
+ *
159
+ * @return {Promise<void>}
160
+ */
161
+ async testTransferToken1 () {
162
+
163
+ let bundleHash = generateBundleHash( this.secrets[ 1 ] );
164
+
165
+ let client = await this.client( this.secrets[ 0 ] );
166
+ let response = await client.transferToken( {
167
+ bundleHash,
168
+ token: this.tokenSlugs[ 0 ],
169
+ units: [ 'unit_id_1', 'unit_id_2' ],
170
+ } );
171
+ this.checkResponse( response, 'testTransferUnitToken.1' );
172
+ }
173
+
174
+ /**
175
+ *
176
+ * @return {Promise<void>}
177
+ */
178
+ async testTransferToken2 () {
179
+
180
+ let bundleHash = generateBundleHash( this.secrets[ 1 ] );
181
+
182
+ let client = await this.client( this.secrets[ 0 ] );
183
+ let response = await client.transferToken( {
184
+ bundleHash,
185
+ token: this.tokenSlugs[ 0 ],
186
+ units: [ 'unit_id_3', 'unit_id_4' ],
187
+ } );
188
+ this.checkResponse( response, 'testTransferUnitToken.2' );
189
+ }
190
+
191
+ /**
192
+ *
193
+ */
194
+ async testClaimShadowWallet () {
195
+ let client = await this.client( this.secrets[ 1 ] );
196
+
197
+ let response = await client.claimShadowWallet( {
198
+ token: this.tokenSlugs[ 0 ]
199
+ } );
200
+ this.checkResponse( response, 'testClaimShadowWallet' );
201
+ }
202
+
203
+
204
+ /**
205
+ *
206
+ * @return {Promise<void>}
207
+ */
208
+ async testTransferTokenBack1 () {
209
+
210
+ let bundleHash = generateBundleHash( this.secrets[ 0 ] );
211
+
212
+ let client = await this.client( this.secrets[ 1 ] );
213
+ let response = await client.transferToken( {
214
+ bundleHash,
215
+ token: this.tokenSlugs[ 0 ],
216
+ units: [ 'unit_id_1', ],
217
+ } );
218
+ this.checkResponse( response, 'testTransferBackToken.1' );
219
+ }
220
+
221
+ /**
222
+ *
223
+ * @return {Promise<void>}
224
+ */
225
+ async testTransferTokenBack2 () {
226
+
227
+ let bundleHash = generateBundleHash( this.secrets[ 0 ] );
228
+
229
+ let client = await this.client( this.secrets[ 1 ] );
230
+ let response = await client.transferToken( {
231
+ bundleHash,
232
+ token: this.tokenSlugs[ 0 ],
233
+ units: [ 'unit_id_3' ],
234
+ } );
235
+ this.checkResponse( response, 'testTransferBackToken.2' );
236
+ }
237
+
238
+
239
+ /**
240
+ *
241
+ */
242
+ async queryWalletsOutput() {
243
+ await this.queryWallet( this.secrets[ 0 ], 'Token creation wallet' );
244
+ await this.queryWallet( this.secrets[ 1 ], 'Recipient wallet' );
245
+ }
246
+
247
+
248
+ /**
249
+ *
250
+ */
251
+ async queryWallet ( secret, title ) {
252
+ let client = await this.client( secret );
253
+ let response = await client.queryWallets( {
254
+ token: this.tokenSlugs[ 0 ]
255
+ } );
256
+
257
+ let outputData = 'Wallet not found.';
258
+ if ( response[ 0 ] ) {
259
+ outputData = response[ 0 ].tokenUnits;
260
+ }
261
+ console.warn( `--- Query wallet: ${ title }: `, outputData );
262
+ }
263
+
264
+
265
+ /**
266
+ * Get a client for each secret
267
+ *
268
+ * @param secret
269
+ * @param cellSlug
270
+ * @returns {Promise<*>}
271
+ */
272
+ async client ( secret, cellSlug = 'unit_test' ) {
273
+
274
+ // Create new client
275
+ if ( !this.clients[ secret ] ) {
276
+
277
+ // Create a client
278
+ this.clients[ secret ] = new KnishIOClient( {
279
+ uri: this.graphqlUrl,
280
+ logging: true
281
+ } );
282
+
283
+ // Auth the client
284
+ await this.clients[ secret ]
285
+ .requestAuthToken( {
286
+ secret,
287
+ encrypt: this.encrypt,
288
+ cellSlug
289
+ } );
290
+ if ( !this.clients[ secret ].getAuthToken() ) {
291
+ console.log( 'Error with authorize - get an empty response.' );
292
+ }
293
+ }
294
+
295
+ // Return the client by secret
296
+ return this.clients[ secret ];
297
+ }
298
+
299
+
300
+ /**
301
+ * Check a response
302
+ * @param response
303
+ * @param key
304
+ */
305
+ checkResponse ( response, key ) {
306
+
307
+ console.log( ` ############### ${ key } ###############` );
308
+ console.log( response );
309
+
310
+ // Check molecule response
311
+ if ( response instanceof ResponseMolecule ) {
312
+ if ( !response.success() ) {
313
+ this.debug( response );
314
+ }
315
+ console.assert( response.success(), response );
316
+ }
317
+
318
+ // Default response
319
+ else {
320
+ this.debug( response );
321
+ }
322
+ }
323
+
324
+
325
+ /**
326
+ * Debug output
327
+ * @param response
328
+ */
329
+ debug ( response ) {
330
+
331
+ // Reason data on the top of the output
332
+ if ( response.data && Dot.get( response.data() || {}, 'reason' ) ) {
333
+ console.log( response.data().reason );
334
+ } else {
335
+ console.log( response );
336
+ }
337
+
338
+ }
339
+
340
+ }