@decaf-ts/for-fabric 0.0.4 → 0.0.6
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/for-fabric.cjs +1 -1
- package/dist/for-fabric.cjs.map +1 -1
- package/dist/for-fabric.js +1 -1
- package/dist/for-fabric.js.map +1 -1
- package/lib/client/FabricClientAdapter.cjs +1 -2
- package/lib/client/FabricClientAdapter.d.ts +3 -2
- package/lib/client/FabricClientAdapter.js.map +1 -1
- package/lib/client/FabricClientDispatch.cjs +4 -1
- package/lib/client/FabricClientDispatch.js.map +1 -1
- package/lib/client/erc20/{erc20ClientRepository.cjs → FabricERC20ClientRepository.cjs} +1 -1
- package/lib/client/erc20/FabricERC20ClientRepository.js.map +1 -0
- package/lib/client/erc20/index.cjs +18 -0
- package/lib/client/erc20/index.d.ts +1 -0
- package/lib/client/erc20/index.js.map +1 -0
- package/lib/client/fabric-fs.d.ts +1 -1
- package/lib/client/index.cjs +3 -1
- package/lib/client/index.d.ts +3 -1
- package/lib/client/index.js.map +1 -1
- package/lib/client/services/{enrollementService.cjs → FabricEnrollmentService.cjs} +1 -1
- package/lib/client/services/FabricEnrollmentService.js.map +1 -0
- package/lib/client/services/index.cjs +2 -1
- package/lib/client/services/index.d.ts +2 -1
- package/lib/client/services/index.js.map +1 -1
- package/lib/contracts/ContractAdapter.cjs +0 -2
- package/lib/contracts/ContractAdapter.js.map +1 -1
- package/lib/contracts/ContractPrivateDataAdapter.cjs +9 -0
- package/lib/contracts/ContractPrivateDataAdapter.d.ts +2 -0
- package/lib/contracts/ContractPrivateDataAdapter.js.map +1 -1
- package/lib/esm/client/FabricClientAdapter.d.ts +3 -2
- package/lib/esm/client/FabricClientAdapter.js +2 -3
- package/lib/esm/client/FabricClientAdapter.js.map +1 -1
- package/lib/esm/client/FabricClientDispatch.js +5 -2
- package/lib/esm/client/FabricClientDispatch.js.map +1 -1
- package/lib/esm/client/erc20/{erc20ClientRepository.js → FabricERC20ClientRepository.js} +1 -1
- package/lib/esm/client/erc20/FabricERC20ClientRepository.js.map +1 -0
- package/lib/esm/client/erc20/index.d.ts +1 -0
- package/lib/esm/client/erc20/index.js +2 -0
- package/lib/esm/client/erc20/index.js.map +1 -0
- package/lib/esm/client/fabric-fs.d.ts +1 -1
- package/lib/esm/client/index.d.ts +3 -1
- package/lib/esm/client/index.js +3 -1
- package/lib/esm/client/index.js.map +1 -1
- package/lib/esm/client/services/{enrollementService.js → FabricEnrollmentService.js} +1 -1
- package/lib/esm/client/services/FabricEnrollmentService.js.map +1 -0
- package/lib/esm/client/services/index.d.ts +2 -1
- package/lib/esm/client/services/index.js +2 -1
- package/lib/esm/client/services/index.js.map +1 -1
- package/lib/esm/contracts/ContractAdapter.js +0 -2
- package/lib/esm/contracts/ContractAdapter.js.map +1 -1
- package/lib/esm/contracts/ContractPrivateDataAdapter.d.ts +2 -0
- package/lib/esm/contracts/ContractPrivateDataAdapter.js +9 -0
- package/lib/esm/contracts/ContractPrivateDataAdapter.js.map +1 -1
- package/lib/esm/shared/crypto.js +2 -3
- package/lib/esm/shared/crypto.js.map +1 -1
- package/lib/esm/shared/decorators.js.map +1 -1
- package/lib/esm/shared/erc20/erc20-constants.d.ts +1 -1
- package/lib/esm/shared/erc20/erc20-constants.js +1 -1
- package/lib/esm/shared/erc20/erc20-constants.js.map +1 -1
- package/lib/esm/shared/events.d.ts +1 -1
- package/lib/esm/shared/events.js +1 -1
- package/lib/esm/shared/events.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/shared/crypto.cjs +2 -3
- package/lib/shared/crypto.js.map +1 -1
- package/lib/shared/decorators.js.map +1 -1
- package/lib/shared/erc20/erc20-constants.cjs +1 -1
- package/lib/shared/erc20/erc20-constants.d.ts +1 -1
- package/lib/shared/erc20/erc20-constants.js.map +1 -1
- package/lib/shared/events.cjs +1 -1
- package/lib/shared/events.d.ts +1 -1
- package/lib/shared/events.js.map +1 -1
- package/lib/version.cjs +1 -1
- package/lib/version.d.ts +1 -1
- package/package.json +1 -17
- package/lib/client/erc20/erc20ClientRepository.js.map +0 -1
- package/lib/client/services/enrollementService.js.map +0 -1
- package/lib/esm/client/erc20/erc20ClientRepository.js.map +0 -1
- package/lib/esm/client/services/enrollementService.js.map +0 -1
- /package/lib/client/erc20/{erc20ClientRepository.d.ts → FabricERC20ClientRepository.d.ts} +0 -0
- /package/lib/client/services/{enrollementService.d.ts → FabricEnrollmentService.d.ts} +0 -0
- /package/lib/esm/client/erc20/{erc20ClientRepository.d.ts → FabricERC20ClientRepository.d.ts} +0 -0
- /package/lib/esm/client/services/{enrollementService.d.ts → FabricEnrollmentService.d.ts} +0 -0
package/dist/for-fabric.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{normalizeImport as t}from"@decaf-ts/utils";import{Logging as e,isBrowser as r,debug as i,MiniLogger as a,NumericLogLevels as n,LogLevel as s}from"@decaf-ts/logging";import{User as o}from"fabric-common";import{signers as c,connect as l}from"@hyperledger/fabric-gateway";import{InternalError as d,Context as p,OperationKeys as h,SerializationError as u,BulkCrudOperationKeys as g,modelToTransient as f,NotFoundError as y,transient as w,readonly as m,onCreate as b,getAllPropertyDecoratorsRecursive as v,BaseError as A,enforceDBDecorators as S,ValidationError as E,ConflictError as C,findPrimaryKey as O,onCreateUpdate as R,DBKeys as N,onUpdate as T,onDelete as $,afterAny as k}from"@decaf-ts/db-decorators";import{__decorate as I,__metadata as F}from"tslib";import{CouchDBAdapter as P,CouchDBKeys as x,CouchDBStatement as D,CouchDBGroupOperator as z,CouchDBOperator as j}from"@decaf-ts/for-couchdb";import*as B from"@grpc/grpc-js";import{Client as L}from"@grpc/grpc-js";import{JSONSerializer as M,getMetadata as K,ModelKeys as _,Model as J,Decoration as U,propMetadata as H,required as q,model as G,prop as Y,type as V,list as W,stringFormat as Q}from"@decaf-ts/decorator-validation";import{Repository as X,Dispatch as Z,UnsupportedError as tt,Adapter as et,PersistenceKeys as rt,final as it,ObserverHandler as at,AuthorizationError as nt,pk as st,index as ot,table as ct,BaseModel as lt,Sequence as dt,Condition as pt,repositoryFromTypeMetadata as ht,cacheModelForPopulate as ut,Cascade as gt,createOrUpdate as ft,getPopulateKey as yt,OrderDirection as wt,NumericSequence as mt,sequenceNameForModel as bt,oneToManyOnUpdate as vt,column as At,oneToOne as St}from"@decaf-ts/core";import{Property as Et,Object as Ct,Contract as Ot,Transaction as Rt,Context as Nt}from"fabric-contract-api";import{apply as Tt}from"@decaf-ts/reflection";import $t from"fabric-ca-client";import*as kt from"@peculiar/x509";import{Crypto as It}from"@peculiar/webcrypto";import{Metadata as Ft}from"@decaf-ts/decoration";const Pt=e.for("fabric-fs");async function xt(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function Dt(e){return"string"!=typeof e?e:await(async e=>{const{promises:r}=await t(import("fs"));return await r.readFile(e)})(e)}async function zt(t,e,r,i){Pt.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const a=new o(t),n=o.newCryptoSuite();a.setCryptoSuite(n);const s=n.createKeyFromRaw(e);return await a.setEnrollment(s,r,i),a}async function jt(e,r){return{mspId:e,credentials:await xt(r,async e=>{const{promises:r}=await t(import("fs")),i=await Bt(e);return await r.readFile(i)})}}async function Bt(e){const{promises:r}=await t(import("fs")),{join:i}=await t(import("path"));return i(e,(await r.readdir(e))[0])}async function Lt(e){const{promises:r}=await t(import("fs")),{join:i}=await t(import("path")),a=await r.readdir(e);return(await r.readFile(i(e,a[0]))).toString()}async function Mt(e){const r=await xt(e,async e=>{const{promises:r}=await t(import("fs")),i=await Bt(e);return await r.readFile(i)}),i=await Kt(r),a=i[Object.getOwnPropertySymbols(i)[0]];return c.newPrivateKeySigner(a)}async function Kt(e){let i;if(r())i=globalThis.crypto.subtle;else{const e=await t(import("crypto"));i=e.subtle||e.webcrypto.subtle}if(!i)throw Error("Could not load SubtleCrypto module");const a=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),n=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(a,"base64").toString("binary"));try{return await i.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(t){throw new d(t)}}class _t extends X{constructor(t,e){super(t,e)}async createPrefix(t,...e){const r=await p.args(h.CREATE,this.class,e,this.adapter,this._overrides||{});return[t=new this.class(t),...r.args]}async createAllPrefix(t,...e){return[t,...(await p.args(h.CREATE,this.class,e,this.adapter,this._overrides||{})).args]}async readPrefix(t,...e){return[t,...(await p.args(h.READ,this.class,e,this.adapter,this._overrides||{})).args]}async readAllPrefix(t,...e){return[t,...(await p.args(h.READ,this.class,e,this.adapter,this._overrides||{})).args]}async updatePrefix(t,...e){return[t,...(await p.args(h.UPDATE,this.class,e,this.adapter,this._overrides||{})).args]}async updateAllPrefix(t,...e){return[t,...(await p.args(h.UPDATE,this.class,e,this.adapter,this._overrides||{})).args]}async deletePrefix(t,...e){const r=await p.args(h.DELETE,this.class,e,this.adapter,this._overrides||{});return await this.read(t,...r.args),[t,...r.args]}async deleteAllPrefix(t,...e){const r=await p.args(h.DELETE,this.class,e,this.adapter,this._overrides||{});return await this.readAll(t,...r.args),[t,...r.args]}}var Jt,Ut;(t=>{t.PRIVATE="private",t.FABRIC="fabric.",t.OWNEDBY="owned-by"})(Jt||(Jt={})),(t=>{t.X509="X.509"})(Ut||(Ut={}));const Ht="hlf-fabric";class qt extends M{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i;try{i=K(t)}catch(t){i=e}if(!i)throw new u("Could not find metadata for "+t.constructor.name);return r[_.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[_.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return J.build(e,r)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}function Gt(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function Yt(t){const e=t.split("_");return 2>e.length||e.length>3?{event:t,table:void 0,owner:void 0}:{table:e[0],event:e[1],owner:e[2]}}class Vt extends Z{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof Wt))throw new tt("Only FabricClientAdapter can be observed by dispatch");this.adapter=t,this.models=et.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))}async updateObservers(t,e,r){if(this.adapter)try{await this.adapter.refresh(t,e,r.id?r.id:void 0,r)}catch(t){throw new d("Failed to refresh dispatch: "+t)}else this.log.verbose(`No adapter observed for dispatch; skipping observer update for ${t}:${e}`)}async handleEvents(){if(!this.listeningStack)throw new d('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new d("No adapter found. should be impossible");const t=this.log.for(this.handleEvents);t.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const e of this.listeningStack){const{table:r,event:i,owner:a}=Yt(e.eventName);if(a&&a!==this.adapter.config?.mspId)continue;const n=this.parsePayload(e.payload);try{await this.updateObservers(r||this.models[0].name,i,n)}catch(e){t.error(`Failed update observables for table ${r} event ${i} id: ${n.id}: ${e}`)}}}catch(e){t.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${e}`),await this.close()}}async initialize(){if(!this.adapter)throw new d("No adapter or config observed for dispatch");const t=(await Wt.getGateway(this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new d("No adapter observed for dispatch");this.listeningStack=await t.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents()}}class Wt extends P{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new qt}static{this.log=e.for(Wt)}get log(){return Wt.log}constructor(t,e){super(t,Ht,e),this.serializer=Wt.serializer}decode(t){return Wt.decoder.decode(t)}repository(){return _t}async createAll(t,e,r,i){const a=this.log.for(this.createAll);if(e.length!==r.length)throw new d(`Ids and models must have the same length: ${e.length} != ${r.length}`);a.info(`adding ${e.length} entries to ${t} table`),a.verbose("pks: "+e);const n=await this.submitTransaction(g.CREATE_ALL,[e,r.map(e=>this.serializer.serialize(e,t))],i);try{return JSON.parse(this.decode(n)).map(t=>JSON.parse(t))}catch(t){throw new u(t)}}async readAll(t,e){const r=this.log.for(this.readAll);r.info(`reading ${e.length} entries to ${t} table`),r.verbose("pks: "+e);const i=await this.submitTransaction(g.READ_ALL,[e]);try{return JSON.parse(this.decode(i)).map(t=>JSON.parse(t))}catch(t){throw new u(t)}}async updateAll(t,e,r,i){const a=this.log.for(this.updateAll);if(e.length!==r.length)throw new d(`Ids and models must have the same length: ${e.length} != ${r.length}`);a.info(`updating ${e.length} entries to ${t} table`),a.verbose("pks: "+e);const n=await this.submitTransaction(g.UPDATE_ALL,[e,r.map(e=>this.serializer.serialize(e,t))],i);try{return JSON.parse(this.decode(n)).map(t=>JSON.parse(t))}catch(t){throw new u(t)}}async deleteAll(t,e){const r=this.log.for(this.deleteAll);r.info(`deleting ${e.length} entries to ${t} table`),r.verbose("pks: "+e);const i=await this.submitTransaction(g.DELETE_ALL,[e]);try{return JSON.parse(this.decode(i)).map(t=>JSON.parse(t))}catch(t){throw new u(t)}}prepare(t,e){const r=this.log.for(this.prepare),i=f(t);return t[rt.METADATA]&&(r.silly("Passing along persistence metadata for "+t[rt.METADATA]),Object.defineProperty(i.model,rt.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:t[rt.METADATA]})),{record:i.model,id:t[e],transient:i.transient}}revert(t,e,r,i,a){const n=this.log.for(this.revert),s={};s[r]=i;const o="string"==typeof e?J.build(s,e):new e(s);n.silly(`Rebuilding model ${o.constructor.name} id ${i}`);const c=t[rt.METADATA],l=Object.keys(o).reduce((e,r)=>(e[r]=t[r],e),o);return a&&(n.verbose("re-adding transient properties: "+Object.keys(a).join(", ")),Object.entries(a).forEach(([t,e])=>{if(t in l&&void 0!==l[t])throw new d(`Transient property ${t} already exists on model ${o.constructor.name}. should be impossible`);l[t]=e})),c&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${o.constructor.name} id ${i}: ${c}`),Object.defineProperty(l,rt.METADATA,{enumerable:!1,configurable:!1,writable:!1,value:c})),l}index(t){throw Error()}async create(t,e,r,i){const a=this.log.for(this.create);a.verbose(`adding entry to ${t} table`),a.debug("pk: "+e);const n=await this.submitTransaction(h.CREATE,[this.serializer.serialize(r,t)],i);return this.serializer.deserialize(this.decode(n))}async read(t,e){const r=this.log.for(this.read);r.verbose(`reading entry from ${t} table`),r.debug("pk: "+e);const i=await this.evaluateTransaction(h.READ,[e.toString()]);return this.serializer.deserialize(this.decode(i))}async update(t,e,r,i){const a=this.log.for(this.update);a.verbose(`updating entry to ${t} table`),a.debug("pk: "+e);const n=await this.submitTransaction(h.UPDATE,[this.serializer.serialize(r,t)],i);return this.serializer.deserialize(this.decode(n))}async delete(t,e){const r=this.log.for(this.delete);r.verbose(`deleting entry from ${t} table`),r.debug("pk: "+e);const i=await this.submitTransaction(h.DELETE,[t,e]);return this.serializer.deserialize(this.decode(i))}async raw(t,e){const r=this.log.for(this.raw);let i,a,n;r.info("Performing raw query on table"),r.debug("processing raw input for query: "+JSON.stringify(t));try{i=JSON.stringify(t)}catch(t){throw new u("Failed to process raw input for query: "+t)}try{a=await this.evaluateTransaction("query",[i])}catch(t){throw this.parseError(t)}try{n=JSON.parse(this.decode(a))}catch(t){throw new u("Failed to process result: "+t)}if(Array.isArray(n)){if(!n.length)return n;const t=n[0];return J.isModel(t)?n.map(t=>J.build(t)):n}return s=n,J.isModel(s)?J.build(s):s;var s}getClient(){return this._client||(this._client=Wt.getClient(this.config)),this._client}async Gateway(){return Wt.getGateway(this.config,this.client)}async Contract(){return Wt.getContract(await this.Gateway(),this.config)}async transaction(t,e=!0,r,i,a){const n=this.log.for(this.transaction),s=await this.Gateway();try{const s=await this.Contract();n.verbose(`${e?"Submit":"Evaluate"}ting transaction ${this.config.contractName}.${t}`),n.debug("args: "+(r?.map(t=>t.toString()).join("\n")||"none"));const o=e?s.submit:s.evaluate;a=a?.length?a:void 0;const c={arguments:r||[],transientData:i};return await o.call(s,t,c)}catch(t){if(10===t.code)throw Error(""+t.details[0].message);throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),s.close()}}parseError(t,e){return Wt.parseError(t,e)}async submitTransaction(t,e,r,i){return this.transaction(t,!0,e,r,i)}async evaluateTransaction(t,e,r,i){return this.transaction(t,!1,e,r,i)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e){const r=this.log.for(this.getContract),i=this.getNetwork(t,e.channel);let a;try{r.debug(`Retrieving chaincode ${e.chaincodeName} contract ${e.contractName} from network ${e.channel}`),a=i.getContract(e.chaincodeName,e.contractName)}catch(t){throw this.parseError(t)}return a}static getNetwork(t,e){const r=this.log.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+e),i=t.getNetwork(e)}catch(t){throw this.parseError(t)}return i}static async getGateway(t,e){return await this.getConnection(e||await this.getClient(t),t)}static getClient(t){const e=this.log.for(this.getClient);e.debug("generating TLS credentials for msp "+t.mspId);const r=B.credentials.createSsl("string"==typeof t.tlsCert?Buffer.from(t.tlsCert):t.tlsCert);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new L(t.peerEndpoint,r)}static async getConnection(t,e){const r=this.log.for(this.getConnection);r.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const i=await jt(e.mspId,e.certCertOrDirectoryPath);r.debug("Retrieving signer key from "+e.keyCertOrDirectoryPath);const a={client:t,identity:i,signer:await Mt(e.keyCertOrDirectoryPath),evaluateOptions:()=>({deadline:Date.now()+5e3}),endorseOptions:()=>({deadline:Date.now()+15e3}),submitOptions:()=>({deadline:Date.now()+5e3}),commitStatusOptions:()=>({deadline:Date.now()+6e4})};return r.debug("Connecting to "+e.mspId),l(a)}Dispatch(){return new Vt(this.getClient())}static parseError(t,e){return super.parseError(t,e)}}I([i(),F("design:type",Function),F("design:paramtypes",[Object]),F("design:returntype",Promise)],Wt.prototype,"index",null),I([i(),it(),F("design:type",Function),F("design:paramtypes",[String,Object,Object,Object]),F("design:returntype",Promise)],Wt.prototype,"create",null),I([i(),it(),F("design:type",Function),F("design:paramtypes",[String,Object]),F("design:returntype",Promise)],Wt.prototype,"read",null),I([i(),it(),F("design:type",Function),F("design:paramtypes",[String,Object,Object,Object]),F("design:returntype",Promise)],Wt.prototype,"update",null),I([i(),it(),F("design:type",Function),F("design:paramtypes",[String,Object]),F("design:returntype",Promise)],Wt.prototype,"delete",null),I([i(),F("design:type",Function),F("design:paramtypes",[Object,Boolean]),F("design:returntype",Promise)],Wt.prototype,"raw",null),Wt.decoration(),et.setCurrent(Ht);class Qt extends p{constructor(){super()}get stub(){return this.get("stub")}get timestamp(){return this.stub.getDateTimestamp()}get identity(){try{return this.get("clientIdentity")}catch(t){return this.get("identity")}}get logger(){return this.get("logger")}}class Xt extends at{constructor(t=[h.CREATE,h.UPDATE,h.DELETE,g.CREATE_ALL,g.UPDATE_ALL,g.DELETE_ALL]){super(),this.supportedEvents=t}async updateObservers(t,e,r,i,a,n,s){const{stub:o}=a;if(-1!==this.supportedEvents.indexOf(r)){t.debug(`Emitting ${r} event`);const a=Gt(e,r,n);o.setEvent(a,Buffer.from(JSON.stringify({id:i})))}else o.setEvent(r,Buffer.from(JSON.stringify(s)))}}function Zt(){return function(t,e,r){const i=r.value;return r.value=async function(...t){const r=t[0],a=r.clientIdentity.getID(),n=await this.tokenRepository.selectWithContext(void 0,r),s=await n.execute();if(0==s.length)throw new y("No tokens avaialble");if(s.length>1)throw new y("To many token available : "+s.length);if(s[0].owner!=a)throw new nt(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function te(t,e,r,i){const{stub:a}=t,n=(await a.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}function ee(){const t=re(Jt.OWNEDBY);return U.for(t).define({decorator:()=>(t,e)=>Tt(q(),m(),b(te),H(re(Jt.OWNEDBY),e))(t,e),args:[]}).apply()}function re(t){return J.key(Jt.FABRIC+t)}function ie(t){if(!t)throw Error("Collection name is required");const e=re(Jt.PRIVATE);return(r,i)=>{const a=i||void 0,n=Reflect.getMetadata(e,r[_.ANCHOR]||r,a),s=n?.collections||[];H(re(Jt.PRIVATE),{...!i&&{collections:s?[...new Set([...s,t])]:[t]},isPrivate:!i})(i?r.constructor:r[_.ANCHOR]||r),i&&(H(re(Jt.PRIVATE),{collections:s?[...new Set([...s,t])]:[t]})(r,i),w()(r,i))}}const ae=/private\s+data\s+matching\s+public\s+hash\s+version\s+is\s+not\s+available/i;function ne(t){let e=Reflect.getMetadata(re(Jt.PRIVATE),t);return e=e||Reflect.getMetadata(re(Jt.PRIVATE),t.constructor),e}function se(t){const e=ne(t);return!(!e||void 0===e.isPrivate)&&e.isPrivate}function oe(t){if(!(t=>!!ne(t))(t))return{model:t};const e=v(t,void 0,re(Jt.PRIVATE)),r=se(t),i=ne(t);let a={model:t,private:void 0};if(a=r?Object.keys(t).reduce((e,r)=>{const a=i.collections;e.private=e.private||{};for(const i of a)try{e.private[i]=e.private[i]||{},e.private[i][r]=t[r]}catch(t){throw new u(`Failed to serialize private property ${r}: ${t}`)}return e},{model:{}}):Object.entries(e).reduce((e,[r,i])=>{const a=i.find(t=>""===t.key);if(a){const i=a.props.collections;e.private=e.private||{};for(const a of i)try{e.private[a]=e.private[a]||{},e.private[a][r]=t[r]}catch(t){throw new u(`Failed to serialize private property ${r}: ${t}`)}}else e.model=e.model||{},e.model[r]=t[r];return e},{}),a.model=a.model||{},a.model=J.build(a.model,t.constructor.name),a.private){const e=Object.keys(a.private);for(const r of e)a.private[r]=J.build(a.private[r],t.constructor.name)}return a}class ce extends d{constructor(t){super(t,ce.name)}}class le extends d{constructor(t){super(t,le.name)}}class de extends d{constructor(t){super(t,de.name)}}class pe extends nt{constructor(t){super(t,pe.name)}}class he extends d{constructor(t){super(t,he.name,500)}}class ue extends A{constructor(t="private data matching public hash version is not available ..."){super(ue.name,t,403)}}class ge extends A{constructor(t){super(ge.name,t,409)}}let fe=class extends lt{constructor(t){super(t)}};I([st(),F("design:type",String)],fe.prototype,"id",void 0),I([q(),ot(),F("design:type",Object)],fe.prototype,"current",void 0),fe=I([ct(x.SEQUENCE),G(),F("design:paramtypes",[Object])],fe);class ye extends dt{constructor(t,e,r){super(t);for(const t of r||[])ie(t)(fe);this.repo=X.forModel(fe,e.alias)}async current(t){if(!t)throw new he("Context is required");const{name:e,startWith:r}=this.options;try{const r=await this.repo.read(e,t);return this.parse(r.current)}catch(t){if(t instanceof y){if(void 0===r)throw new d("Starting value is not defined for a non existing sequence");try{return this.parse(r)}catch(t){throw new d(`Failed to parse initial value for sequence ${r}: ${t}`)}}throw new d(`Failed to retrieve current value for sequence ${e}: ${t}`)}}parse(t){return dt.parseValue(this.options.type,t)}async increment(t,e,r){if(!r)throw new he("Context is required");const{type:i,incrementBy:a,name:n}=this.options;let s;const o=e||a;if(o%a!==0)throw new d("Value to increment does not consider the incrementBy setting: "+a);switch(i){case"Number":s=this.parse(t)+o;break;case"BigInt":s=this.parse(t)+BigInt(o);break;default:throw new d("Should never happen")}let c;try{c=await this.repo.update(new fe({id:n,current:s}),r)}catch(t){if(!(t instanceof y))throw t;c=await this.repo.create(new fe({id:n,current:s}),r)}return c.current}async next(t){if(!t)throw new he("Context is required");const e=await this.current(t);return this.increment(e,void 0,t)}async range(t,e){if(!e)throw new he("Context is required");const r=await this.current(e),i=this.parse(this.options.incrementBy),a=await this.increment(r,this.parse(t)*i,e),n=[];for(let e=1;t>=e;e++)n.push(r+i*this.parse(e));if(n[n.length-1]!==a)throw new d("Miscalculation of range");return n}}class we extends X{constructor(t,e,r){super(t,e),this.trackedEvents=r}logFor(t){return e.for(we,{},t)}async create(t,...e){const r=e[e.length-1],i=this.logFor(r).for(this.create);i.info("Preparing model: "+JSON.stringify(t));let a,{record:n,id:s,transient:o}=this.adapter.prepare(t,this.pk,this.tableName,...e);return i.info("Creating model: "+JSON.stringify(t)),n=await this.adapter.create(this.tableName,s,n,...e),e.length&&(a=e[e.length-1]),i.info("Reverting model: "+JSON.stringify(t)),this.adapter.revert(n,this.class,this.pk,s,a&&a.get("rebuildWithTransient")?o:void 0)}async read(t,...e){const r=await this.adapter.read(this.tableName,t,new this.class,...e);return this.adapter.revert(r,this.class,this.pk,t)}async delete(t,...e){const r=await this.adapter.delete(this.tableName,t,new this.class,...e);return this.adapter.revert(r,this.class,this.pk,t)}async update(t,...e){const r=e[e.length-1],i=this.logFor(r).for(this.update);i.info("Preparing model: "+JSON.stringify(t));let a,{record:n,id:s,transient:o}=this.adapter.prepare(t,this.pk,this.tableName,...e);return i.info("Updating model: "+JSON.stringify(t)),n=await this.adapter.update(this.tableName,s,n,...e),e.length&&(a=e[e.length-1]),i.info("Reverting model: "+JSON.stringify(t)),this.adapter.revert(n,this.class,this.pk,s,a&&a.get("rebuildWithTransient")?o:void 0)}ObserverHandler(){return new Xt}async createAll(t,...e){if(!t.length)return t;const r=t.map(t=>this.adapter.prepare(t,this.pk,this.tableName,...e)),i=r.map(t=>t.id);let a=r.map(t=>t.record);const n=r.map(t=>t.transient).filter(t=>!!t);let s;return e.length&&(s=e[e.length-1]),a=await this.adapter.createAll(this.tableName,i,a,...e),a.map((t,e)=>this.adapter.revert(t,this.class,this.pk,i[e],s&&s.get("rebuildWithTransient")?n:void 0))}async updateAll(t,...e){if(!t.length)return t;const r=t.map(t=>this.adapter.prepare(t,this.pk,this.tableName,...e)),i=r.map(t=>t.transient).filter(t=>!!t);let a;return e.length&&(a=e[e.length-1]),(await this.adapter.updateAll(this.tableName,r.map(t=>t.id),r.map(t=>t.record),...e)).map((t,e)=>this.adapter.revert(t,this.class,this.pk,r[e].id,a&&a.get("rebuildWithTransient")?i:void 0))}async raw(t,e,...r){const i=r.pop(),a=await p.args("QUERY",this.class,[i],this.adapter,{});return this.adapter.raw(t,e,new this.class,...a.args)}async updateObservers(t,e,r,i,...a){if(!this.trackedEvents||-1!==this.trackedEvents.indexOf(e))return await super.updateObservers(t,e,r,i,...a)}async selectWithContext(t,e){let r;return e instanceof Qt?r.context=e:r=await p.args(h.CREATE,this.class,[e],this.adapter,this._overrides||{}),t?this.adapter.Statement(r.context).select(t).from(this.class):this.adapter.Statement(r.context).select().from(this.class)}async createAllPrefix(t,...e){const r=e[e.length-1],i=await p.args(h.CREATE,this.class,e,this.adapter,this._overrides||{});if(!t.length)return[t,...i.args];const a=X.getSequenceOptions(t[0]);let n=[];a.type?(a.name||(a.name=ye.pk(t[0])),n=await(await this.adapter.Sequence(a)).range(t.length,r)):n=t.map((t,e)=>{if(void 0===t[this.pk])throw new d("Primary key is not defined for model in position "+e);return t[this.pk]}),t=await Promise.all(t.map(async(t,e)=>(t=new this.class(t),a.type&&(t[this.pk]=n[e]),await S(this,i.context,t,h.CREATE,h.ON),t)));const s=i.context.get("ignoredValidationProperties")||[],o=(await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...s))))).reduce((t,e,r)=>(e&&(t="string"==typeof t?t+`\n - ${r}: ${e.toString()}`:` - ${r}: ${e.toString()}`),t),void 0);if(o)throw new E(o);return[t,...i.args]}async createPrefix(t,...e){const r=await super.createPrefix(t,...e),i=r[0][this.pk];try{if(await this.read(i+"",...e))throw new C(`Conflict detected while creating model with id: ${i} already exists`)}catch(t){if(404!==t.code)throw t;this.logFor(e[e.length-1]).info(`Record entry with pk ${i} does not exist, creating it now...`)}return r}}class me extends D{constructor(t,e){super(t),this.ctx=e}async raw(t){const e=await this.adapter.raw(t,!0,this.ctx),r=O(new this.fromSelector),i=r.id,a=r.props.type;return this.selectSelector?e:e.map(t=>this.processRecord(t,i,a))}build(){const t={};t[x.TABLE]={},t[x.TABLE]=X.table(this.fromSelector);const e={selector:t};if(this.selectSelector&&(e.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(pt.and(this.whereCondition,pt.attribute(x.TABLE).eq(e.selector[x.TABLE]))).selector,r=Object.keys(t);if(1===r.length&&-1!==Object.values(z).indexOf(r[0]))switch(r[0]){case z.AND:t[z.AND]=[...Object.values(t[z.AND]).reduce((t,e)=>{const r=Object.keys(e);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const i=r[0];return i===z.AND?t.push(...e[i]):t.push(e),t},[])],e.selector=t;break;case z.OR:{const r={};r[z.AND]=[t,...Object.entries(e.selector).map(([t,e])=>{const r={};return r[t]=e,r})],e.selector=r;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,r])=>{e.selector[t],e.selector[t]=r})}if(this.orderBySelector){e.sort=e.sort||[],e.selector=e.selector||{};const[t,r]=this.orderBySelector,i={};i[t]=r,e.sort.push(i),e.selector[t]||(e.selector[t]={},e.selector[t][j.BIGGER]=null)}return this.limitSelector&&(e.limit=this.limitSelector),this.offsetSelector&&(e.skip=this.offsetSelector),e}}class be extends M{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}preSerialize(t){return Object.assign({},t)}}async function ve(t,e,r,i){const a=i[r];if(!a)return;if("object"!=typeof a){const e=ht(i,r,this.adapter.alias),n=await e.read(a,t);return await ut(t,i,r,a,n),void(i[r]=a)}e.class="string"==typeof e.class?e.class:e.class().name;const n=J.get(e.class);if(!n)throw new d("Could not find model "+e.class);const s=X.forModel(n,this.adapter.alias),o=await s.create(a,t),c=O(o).id;await ut(t,i,r,o[c],o),i[r]=o[c]}async function Ae(t,e,r,i){const a=i[r];if(!a)return;if(e.cascade.update!==gt.CASCADE)return;if("object"!=typeof a){const e=ht(i,r,this.adapter.alias),n=await e.read(a,t);return await ut(t,i,r,a,n),void(i[r]=a)}const n=await ft(i[r],t,this.adapter.alias),s=O(n).id;await ut(t,i,r,n[s],n),i[r]=n[s]}async function Se(t,e,r,i){const a=i[r];if(!a)return;if(e.cascade.update!==gt.CASCADE)return;const n=ht(i,r,this.adapter.alias);let s;s=a instanceof J?await n.delete(i[r][n.pk],t):await n.delete(i[r],t),await ut(t,i,r,s[n.pk],s)}async function Ee(t,e,r,i){const a=i[r];if(!a||!a.length)return;const n=typeof a[0];if(!a.every(t=>typeof t===n))throw new d(`Invalid operation. All elements of property ${r} must match the same type.`);const s=new Set([...a]);if("object"!==n){const e=ht(i,r,this.adapter.alias);for(const a of s){const n=await e.read(a,t);await ut(t,i,r,a,n)}return void(i[r]=[...s])}const o=O(a[0]).id,c=new Set;for(const e of a){const a=await ft(e,t,this.adapter.alias);await ut(t,i,r,a[o],a),c.add(a[o])}i[r]=[...c]}async function Ce(t,e,r,i){if(e.cascade.delete!==gt.CASCADE)return;const a=i[r];if(!a||!a.length)return;const n=typeof a[0];if(!a.every(t=>typeof t===n))throw new d(`Invalid operation. All elements of property ${r} must match the same type.`);const s="object"===n,o=s?X.forModel(a[0],this.adapter.alias):ht(i,r,this.adapter.alias),c=new Set([...s?a.map(t=>t[o.pk]):a]);for(const e of c.values()){const a=await o.delete(e,t);await ut(t,i,r,e,a)}i[r]=[...c]}async function Oe(t,e,r,i){if(!e.populate)return;const a=i[r],n=Array.isArray(a);if(void 0===a||n&&0===a.length)return;const s=await(async(e,r,i,a,n)=>{let s,o;const c=[];for(const l of a){s=yt(r.constructor.name,i,l);try{o=await e.get(s)}catch(e){const a=ht(r,i,n);if(!a)throw new d("Could not find repo");o=await a.read(l,t)}c.push(o)}return c})(t,i,r,n?a:[a],this.adapter.alias);i[r]=n?s:s[0]}async function Re(t,e,r,i){try{const e=t.get("clientIdentity");i[r]=e.getID()}catch(t){throw new tt("No User found in context. Please provide a user in the context")}}async function Ne(t,e,r,i){if(!e.type||i[r])return;let a;e.name||(e.name=bt(i,"pk"));try{a=await this.adapter.Sequence(e)}catch(t){throw new d(`Failed to instantiate Sequence ${e.name}: ${t}`)}const n=await a.next(t);Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}class Te extends P{getClient(){throw new tt("Client is not supported in Fabric contracts")}static{this.textDecoder=new TextDecoder("utf8")}static{this.serializer=new be}logFor(t){return e.for(Te,{},t)}repository(){return we}constructor(t,e){super(t,Ht,e),this.Context=Qt}for(t,...e){return super.for(t,...e)}async create(t,e,r,...i){const{stub:a,logger:n}=i.pop(),s=n.for(this.create);try{s.info(`adding entry to ${t} table with pk ${e}`),r=await this.putState(a,e.toString(),r)}catch(t){throw this.parseError(t)}return r}async read(t,e,...r){const{stub:i,logger:a}=r.pop(),n=a.for(this.read);let s;try{const r=await this.readState(i,t,e.toString());if(1>r.length)throw n.debug(`No record found for id ${e} in ${t} table`),new y(`No record found for id ${e} in ${t} table`);2>r.length?(n.debug(`No record found for id ${e} in ${t} table`),s=r.pop()):s=this.mergeModels(r)}catch(t){throw this.parseError(t)}return s}async update(t,e,r,...i){const{stub:a,logger:n}=i.pop(),s=n.for(this.update);try{s.info(`updating entry to ${t} table with pk ${e}`),r=await this.putState(a,e.toString(),r)}catch(t){throw this.parseError(t)}return r}async delete(t,e,...r){const i=r.pop(),{stub:a,logger:n}=i,s=n.for(this.delete);let o;r.push(i);try{o=await this.read(t,e,...r),s.verbose(`deleting entry with pk ${e} from ${t} table`),this.deleteState(a,t,e.toString())}catch(t){throw this.parseError(t)}return o}async deleteState(t,e,r,...i){const a=t.createCompositeKey(e,[r+""]);await t.deleteState(a)}async putState(t,e,r,...i){let a;try{a=Buffer.from(Te.serializer.serialize(r))}catch(t){throw new u(`Failed to serialize record with id ${e}: ${t}`)}return await t.putState(e.toString(),a),r}async readState(t,e,r,...i){const a=t.createCompositeKey(e,[r+""]),n=[];let s=await t.getState(a);if(""===s.toString())throw new y(`Record with id ${r} not found`);try{s=Te.serializer.deserialize(s.toString())}catch(t){throw new u("Failed to parse record: "+t)}return n.push(s),n}async queryResult(t,e,...r){return await t.getQueryResult(JSON.stringify(e))}async queryResultPaginated(t,e,r=250,i,...a){return await t.getQueryResultWithPagination(JSON.stringify(e),r,i?.toString())}mergeModels(t){const e=t=>Object.entries(t).reduce((t,[e,r])=>(void 0!==r&&(t[e]=r),t),{});let r=t.pop();for(const i of t)r=Object.assign({},e(r),e(i));return r}decode(t){return Te.textDecoder.decode(t)}async flags(t,e,r,i,...a){return Object.assign(await super.flags(t,e,r,...a),{stub:i.stub,identity:i.clientIdentity,logger:this.logFor(i)})}index(t){return Promise.resolve(void 0)}async resultIterator(t,e,r=!1){const i=[];let a=await e.next();for(;!a.done;){if(a.value&&a.value.value.toString()){let e={};if(t.debug(a.value.value.toString("utf8")),r){e.TxId=a.value.txId,e.Timestamp=a.value.timestamp;try{e.Value=JSON.parse(a.value.value.toString("utf8"))}catch(r){t.error(r),e.Value=a.value.value.toString("utf8")}}else try{e=JSON.parse(a.value.value.toString("utf8"))}catch(r){t.error(r),e=a.value.value.toString("utf8")}i.push(e)}a=await e.next()}return t.debug(`Closing iterator after ${i.length} results`),e.close(),i}async raw(t,e,...r){const{stub:i,logger:a}=r.pop(),n=a.for(this.raw),{skip:s,limit:o}=t;let c;o||s?(delete t.limit,delete t.skip,n.debug(`Retrieving paginated iterator: limit: ${o}/ skip: ${s}`),c=(await this.queryResultPaginated(i,t,o||250,s?.toString())).iterator):(n.debug("Retrieving iterator"),c=await this.queryResult(i,t)),n.debug("Iterator acquired");const l=await this.resultIterator(n,c);return n.debug("returning {0} results",""+(Array.isArray(l)?l.length:1)),l}Statement(t){if(!t)throw new he("Context is required");return new me(this,t)}async Sequence(t){return new ye(t,this)}async createAll(t,e,r,...i){if(e.length!==r.length)throw new d("Ids and models must have the same length");const{logger:a}=i[i.length-1],n=a.for(this.createAll);return n.info(`Creating ${e.length} entries ${t} table`),n.debug("pks: "+e),Promise.all(e.map(async(e,a)=>this.create(t,e,r[a],...i)))}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new d("Ids and models must have the same length");const{logger:a}=i[i.length-1],n=a.for(this.createAll);return n.info(`Updating ${e.length} entries ${t} table`),n.debug("pks: "+e),Promise.all(e.map(async(e,a)=>this.update(t,e,r[a],...i)))}prepare(t,e,...r){const{stub:i,logger:a}=r.pop(),n=r.shift(),s=a.for(this.prepare),o=f(t),c=Object.entries(o.model).reduce((e,[r,i])=>{if(void 0===i)return e;const a=X.column(t,r);if(this.isReserved(a))throw new d(`Property name ${a} is reserved`);return e[a]=i,e},{});return t[rt.METADATA]&&(s.silly("Passing along persistence metadata for "+t[rt.METADATA]),Object.defineProperty(c,rt.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:t[rt.METADATA]})),s.info(`Preparing record for ${n} table with pk ${t[e]}`),{record:c,id:i.createCompositeKey(n,[t[e]+""]),transient:o.transient}}revert(t,e,r,i,a){const n=this.log.for(this.revert),s={};s[r]=i;const o="string"==typeof e?J.build(s,e):new e(s);n.silly(`Rebuilding model ${o.constructor.name} id ${i}`);const c=t[rt.METADATA],l=Object.keys(o).reduce((e,r)=>(e[r]=t[X.column(e,r)],e),o);return a&&(n.verbose("re-adding transient properties: "+Object.keys(a).join(", ")),Object.entries(a).forEach(([t,e])=>{if(t in l&&void 0!==l[t])throw new d(`Transient property ${t} already exists on model ${o.constructor.name}. should be impossible`);l[t]=e})),c&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${o.constructor.name} id ${i}: ${c}`),Object.defineProperty(l,rt.METADATA,{enumerable:!1,configurable:!1,writable:!1,value:c})),l}createPrefix(t,e,r,...i){const a=i.pop(),n={};return n[x.TABLE]=t,Object.assign(n,r),[t,e,n,a]}updatePrefix(t,e,r,...i){const a=i.pop(),n={};return n[x.TABLE]=t,Object.assign(n,r),[t,e,n,a]}createAllPrefix(t,e,r,...i){if(e.length!==r.length)throw new d("Ids and models must have the same length");const a=i.pop(),n=e.map((e,i)=>{const a={};return a[x.TABLE]=t,Object.assign(a,r[i]),a});return[t,e,n,a]}updateAllPrefix(t,e,r,...i){if(e.length!==r.length)throw new d("Ids and models must have the same length");const a=i.pop(),n=e.map((e,i)=>{const a={};return a[x.TABLE]=t,Object.assign(a,r[i]),a});return[t,e,n,a]}static decoration(){super.decoration();const t=X.key(rt.CREATED_BY),e=X.key(rt.UPDATED_BY);U.flavouredAs(Ht).for(t).define(b(Re),H(t,{})).apply(),U.flavouredAs(Ht).for(e).define(R(Re),H(e,{})).apply();const r=X.key(N.ID);U.flavouredAs(Ht).for(r).define(ot([wt.ASC,wt.DSC]),q(),m(),H(r,mt),b(Ne,mt)).apply();const i=et.key(rt.COLUMN);U.flavouredAs(Ht).for(i).extend(Et()).apply();const a=et.key(rt.TABLE);U.flavouredAs(Ht).for(a).extend(t=>Ct()(t)).apply();const n=X.key(rt.ONE_TO_ONE);U.flavouredAs(Ht).for(n).define({decorator:(t,e,r,i,a)=>{const s={class:t.name?t.name:t,cascade:e,populate:r};return i&&(s.joinTable=i),a&&(s.name=a),Tt(Y(rt.RELATIONS),V([t.name?t.name:t,String.name,Number.name,BigInt.name]),b(ve,s),T(Ae,s),$(Se,s),k(Oe,s),H(n,s))}}).apply();const s=X.key(rt.ONE_TO_MANY);U.for(s).define({decorator:(t,e,r,i,a)=>{const n={class:t.name?t.name:t,cascade:e,populate:r};return i&&(n.joinTable=i),a&&(n.name=a),Tt(Y(rt.RELATIONS),W([t,String,Number]),b(Ee,n),T(vt,n),$(Ce,n),k(Oe,n),H(s,n))}}).apply()}}Te.decoration(),et.setCurrent(Ht);class $e extends M{constructor(){super()}deserialize(t){return super.deserialize(t)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}class ke extends Te{constructor(t,e,r){super(t,e),this.collections=r,this.collections=r||[]}async Sequence(t){return new ye(t,this,this.collections)}async read(t,e,r,...i){const{stub:a,logger:n}=i.pop(),s=n.for(this.read);let o;try{const i=await this.readState(a,t,e.toString(),r);if(1>i.length)throw s.debug(`No record found for id ${e} in ${t} table`),new y(`No record found for id ${e} in ${t} table`);2>i.length?(s.debug(`No record found for id ${e} in ${t} table`),o=i.pop()):o=this.mergeModels(i)}catch(t){throw this.parseError(t)}return o}async delete(t,e,r,...i){const a=i.pop(),{stub:n,logger:s}=a,o=s.for(this.delete);let c;i.push(a);try{c=await this.read(t,e,r,...i),o.verbose(`deleting entry with pk ${e} from ${t} table`),this.deleteState(n,t,e.toString(),r)}catch(t){throw this.parseError(t)}return c}prepare(t,e,...r){const{stub:i,logger:a}=r.pop(),n=r.shift(),s=a.for(this.prepare),o=((t,e)=>{const r=f(e),i=oe(e),a=e=>Object.entries(e).reduce((r,[i,a])=>{if(void 0===a)return r;const n=X.column(e,i);if(t.isReserved(n))throw new d(`Property name ${n} is reserved`);return r[n]=a,r},{});if(i.private){const t=Object.keys(i.private);for(const e of t)i.private[e]=a(i.private[e])}return{model:r.model,transient:r.transient,privateData:i.private,result:a(r.model)}})(this,t);return s.info(`Preparing record for ${n} table with pk ${t[e]}`),{record:o.privateData,id:i.createCompositeKey(n,[t[e]+""]),transient:o.transient}}updatePrefix(t,e,r,...i){const a=i.pop(),n=Object.keys(r);for(const e of n)r[e][x.TABLE]=t;return[t,e,r,a]}async putState(t,e,r,...i){const a=Object.keys(r);let n,s={};for(const i of a){s=r[i];try{n=Buffer.from(Te.serializer.serialize(r[i]))}catch(t){throw new u(`Failed to serialize record with id ${e}: ${t}`)}await t.putPrivateData(i,e.toString(),n)}return s}async readState(t,e,r,i,...a){const n=t.createCompositeKey(e,[r+""]),s=oe(i),o=Object.keys(s.private),c=[];for(const e of o)try{let i=await t.getPrivateData(e,n);if(""===i.toString())throw new y(`Entry with id ${r} doesn't exist...`);try{i=Te.serializer.deserialize(i.toString())}catch(t){throw new u("Failed to parse private data: "+t)}c.push(i)}catch(t){if(ae.test(t.message))throw new ue(t);throw t}return c}async deleteState(t,e,r,i,...a){const n=t.createCompositeKey(e,[r+""]),s=oe(i),o=Object.keys(s.private);for(const e of o)await t.deletePrivateData(e,n)}async queryResult(t,e,r){const i=oe(r).private,a=Object.keys(i)[0]||"";return(await t.getPrivateDataQueryResult(a,JSON.stringify(e))).iterator}async queryResultPaginated(t,e,r=250,i=void 0,a){const n=oe(a).private,s=Object.keys(n)[0]||"",o=await t.getPrivateDataQueryResult(s,JSON.stringify(e)),c=[];let l=0,d=!i,p=null;for(;;){const t=await o.next();if(t.value&&t.value.value.toString()){const e=t.value.key,a=t.value.value.toString("utf8");if(!d){e===i?.toString()&&(d=!0);continue}if(c.push({Key:e,Record:JSON.parse(a)}),p=e,l++,l>=r)return await o.close(),{iterator:c,metadata:{fetchedRecordsCount:c.length,bookmark:p}}}if(t.done)return await o.close(),{iterator:c,metadata:{fetchedRecordsCount:c.length,bookmark:""}}}}async raw(t,e,...r){const{stub:i,logger:a}=r.pop(),n=a.for(this.raw),{skip:s,limit:o}=t,c=r.shift();let l;o||s?(delete t.limit,delete t.skip,n.debug(`Retrieving paginated iterator: limit: ${o}/ skip: ${s}`),l=(await this.queryResultPaginated(i,t,o||250,s?.toString(),c)).iterator):(n.debug("Retrieving iterator"),l=await this.queryResult(i,t,c)),n.debug("Iterator acquired");const d=await this.resultIterator(n,l);return n.debug("returning {0} results",""+(Array.isArray(d)?d.length:1)),d}}class Ie extends Ot{static{this.serializer=new $e}constructor(t,e){super(t),this.clazz=e,this.initialized=!1,Ie.adapter=this.getAdapter(e),this.repo=X.forModel(e,Ie.adapter.alias)}getAdapter(t){const e=new t;if(se(e)){const t=oe(e),r=Object.keys(t.private);return new ke(void 0,"fabric-private-data-adapter",r)}return new Te(void 0,"fabric-public-data-adapter")}logFor(t){return e.for(Ie.name,{},t)}async create(t,e,...r){const i=this.logFor(t).for(this.create);"string"==typeof e&&(e=this.deserialize(e)),i.info("Creating model: "+JSON.stringify(e));const a=this.getTransientData(t);return i.info("Merging transient data..."),e=this.repo.merge(e,a),this.repo.create(e,t,...r)}async read(t,e,...r){return this.logFor(t).for(this.read).info(`reading entry with pk ${e} `),this.repo.read(e,t,...r)}getTransientData(t){const e=t.stub.getTransient();let r={};return e.has(this.repo.tableName)&&(r=JSON.parse(e.get(this.repo.tableName)?.toString("utf8"))),r}async update(t,e,...r){const i=this.logFor(t).for(this.update);"string"==typeof e&&(e=this.deserialize(e)),i.info("Updating model: "+JSON.stringify(e));const a=this.getTransientData(t);return i.info("Merging transient data..."),e=this.repo.merge(e,a),this.repo.update(e,t,...r)}async delete(t,e,...r){return this.logFor(t).for(this.delete).info(`deleting entry with pk ${e} `),this.repo.delete(e+"",t,...r)}async deleteAll(t,e,...r){return"string"==typeof e&&(e=JSON.parse(e)),this.repo.deleteAll(e,t,...r)}async readAll(t,e,...r){return"string"==typeof e&&(e=JSON.parse(e)),this.repo.readAll(e,t,...r)}async updateAll(t,e,...r){const i=this.logFor(t).for(this.updateAll);return"string"==typeof e&&(e=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t))),i.info(`updating ${e.length} entries to the table`),this.repo.updateAll(e,t,...r)}async raw(t,e,r,...i){return"string"==typeof e&&(e=JSON.parse(e)),this.repo.raw(e,r,t,...i)}serialize(t){return Ie.serializer.serialize(t)}deserialize(t){return Ie.serializer.deserialize(t)}async init(t){const e=this.logFor(t).for(this.init);e.info("Running contract initialization..."),this.initialized=!0,e.info("Contract initialization completed.")}async healthcheck(t){return this.logFor(t).for(this.healthcheck).info(`Running Healthcheck: ${this.initialized}...`),{healthcheck:this.initialized}}async createAll(t,e,...r){const i=this.logFor(t).for(this.createAll);return"string"==typeof e&&(e=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t))),i.info(`adding ${e.length} entries to the table`),this.repo.createAll(e,t,...r)}}class Fe extends Ie{constructor(t,e){super(t,e)}logFor(t){return e.for(Fe,{},t)}async create(t,e){const r=this.logFor(t).for(this.create);r.info("Creating model: "+e);const i=this.deserialize(e);return r.info("Model deserialized: "+JSON.stringify(i)),this.serialize(await super.create(t,i))}async read(t,e){return this.logFor(t).for(this.read).info("Reading id: "+e),this.serialize(await super.read(t,e))}async update(t,e){return this.logFor(t).for(this.update).info("Updating model: "+e),this.serialize(await super.update(t,e))}async delete(t,e){return this.logFor(t).for(this.delete).info("Deleting id: "+e),this.serialize(await super.delete(t,e))}async deleteAll(t,e){const r=JSON.parse(e);return this.logFor(t).for(this.deleteAll).info(`deleting ${r.length} entries from the table`),JSON.stringify((await super.deleteAll(t,r)).map(t=>this.serialize(t)))}async readAll(t,e){const r=JSON.parse(e);return this.logFor(t).for(this.readAll).info(`reading ${r.length} entries from the table`),JSON.stringify((await super.readAll(t,r)).map(t=>this.serialize(t)))}async updateAll(t,e){const r=this.logFor(t).for(this.updateAll),i=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t));return r.info(`Updating ${i.length} entries to the table`),JSON.stringify((await super.updateAll(t,i)).map(t=>this.serialize(t)))}async raw(t,e,r){const i=JSON.parse(e);return super.raw(t,i,r)}async init(t){await super.init(t)}async healthcheck(t){return JSON.stringify(await super.healthcheck(t))}async createAll(t,e){const r=this.logFor(t).for(this.createAll),i=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t));return r.info(`Adding ${i.length} entries to the table`),JSON.stringify((await super.createAll(t,i)).map(t=>this.serialize(t)))}}function Pe(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new ce(`Addition overflow: ${t} + ${e}`);return r}function xe(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new ce(`Subtraction overflow: ${t} - ${e}`);return r}I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String]),F("design:returntype",Promise)],Fe.prototype,"create",null),I([Rt(!1),F("design:type",Function),F("design:paramtypes",[Nt,String]),F("design:returntype",Promise)],Fe.prototype,"read",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String]),F("design:returntype",Promise)],Fe.prototype,"update",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String]),F("design:returntype",Promise)],Fe.prototype,"delete",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String]),F("design:returntype",Promise)],Fe.prototype,"deleteAll",null),I([Rt(!1),F("design:type",Function),F("design:paramtypes",[Nt,String]),F("design:returntype",Promise)],Fe.prototype,"readAll",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String]),F("design:returntype",Promise)],Fe.prototype,"updateAll",null),I([Rt(!1),F("design:type",Function),F("design:paramtypes",[Nt,String,Boolean]),F("design:returntype",Promise)],Fe.prototype,"raw",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt]),F("design:returntype",Promise)],Fe.prototype,"init",null),I([Rt(!1),F("design:type",Function),F("design:paramtypes",[Nt]),F("design:returntype",Promise)],Fe.prototype,"healthcheck",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String]),F("design:returntype",Promise)],Fe.prototype,"createAll",null);let De=class extends lt{constructor(t){super(t)}};I([st({type:"String"}),F("design:type",String)],De.prototype,"name",void 0),I([At(),q(),F("design:type",String)],De.prototype,"owner",void 0),I([At(),q(),F("design:type",String)],De.prototype,"symbol",void 0),I([At(),q(),F("design:type",Number)],De.prototype,"decimals",void 0),De=I([ct("erc20_tokens"),G(),F("design:paramtypes",[Object])],De);let ze=class extends lt{constructor(t){super(t)}};I([st({type:"String"}),F("design:type",String)],ze.prototype,"id",void 0),I([At(),q(),F("design:type",String)],ze.prototype,"token",void 0),I([At(),q(),F("design:type",Number)],ze.prototype,"balance",void 0),I([At(),F("design:type",String)],ze.prototype,"captive",void 0),ze=I([ct("erc20_wallets"),G(),F("design:paramtypes",[Object])],ze);let je=class extends lt{constructor(t){super(t)}};var Be;I([st({type:"String"}),At(),q(),F("design:type",String)],je.prototype,"owner",void 0),I([At(),q(),F("design:type",String)],je.prototype,"spender",void 0),I([At(),q(),F("design:type",Number)],je.prototype,"value",void 0),je=I([ct("erc20_allowances"),G(),F("design:paramtypes",[Object])],je),(t=>{t.TRANSFER=" Transfer",t.APPROVAL="Approval"})(Be||(Be={}));class Le extends Ie{constructor(t){super(t,ze),Le.adapter=Le.adapter||new Te,this.walletRepository=we.forModel(ze,Le.adapter.alias),this.tokenRepository=we.forModel(De,Le.adapter.alias),this.allowanceRepository=we.forModel(je,Le.adapter.alias)}async TokenName(t){await this.CheckInitialized(t);const e=await this.tokenRepository.selectWithContext(void 0,t);return(await e.execute())[0].name}async Symbol(t){await this.CheckInitialized(t);const e=await this.tokenRepository.selectWithContext(void 0,t);return(await e.execute())[0].symbol}async Decimals(t){await this.CheckInitialized(t);const e=await this.tokenRepository.selectWithContext(void 0,t);return(await e.execute())[0].decimals}async TotalSupply(t){await this.CheckInitialized(t);const e=await this.walletRepository.selectWithContext(void 0,t),r=await e.execute();if(0==r.length)throw new y(`The token ${this.getName()} does not exist`);let i=0;return r.forEach(t=>{i+=t.balance}),i}async BalanceOf(t,e){return await this.CheckInitialized(t),(await this.walletRepository.read(e,t)).balance}async Transfer(t,e,r){await this.CheckInitialized(t);const i=t.clientIdentity.getID();if(!await this._transfer(t,i,e,r))throw new d("Failed to transfer");return!0}async TransferFrom(t,e,r,i){await this.CheckInitialized(t);const a=t.clientIdentity.getID(),n=await this._getAllowance(t,e,a);if(!n||0>n.value)throw new de(`spender ${a} has no allowance from ${e}`);const s=n.value;if(i>s)throw new le("The spender does not have enough allowance to spend.");const o=xe(s,i),c=Object.assign({},n,{value:o});if(await this.allowanceRepository.update(c,t),!await this._transfer(t,e,r,i))throw new d("Failed to transfer");return!0}async _transfer(t,e,r,i){const a=this.logFor(t).for(this._transfer);if(e===r)throw new nt("cannot transfer to and from same client account");if(0>i)throw new le("transfer amount cannot be negative");const n=await this.walletRepository.read(e,t),s=n.balance;if(i>s)throw new le(`client account ${e} has insufficient funds.`);let o,c=!1;try{o=await this.walletRepository.read(r,t)}catch(e){if(!(e instanceof A))throw new d(e);if(404!==e.code)throw new d(e.message);o=new ze({id:r,balance:0,token:await this.TokenName(t)}),c=!0}const l=o.balance,p=xe(s,i),h=Pe(l,i),u=Object.assign({},n,{balance:p});await this.walletRepository.update(u,t);const g=Object.assign({},o,{balance:h});c?await this.walletRepository.create(g,t):await this.walletRepository.update(g,t);const f={from:e,to:r,value:i};return this.repo.ObserverHandler().updateObservers(a,"",Be.TRANSFER,"",t,"",f),!0}async Approve(t,e,r){await this.CheckInitialized(t);const i=this.logFor(t).for(this.Approve),a=t.clientIdentity.getID();let n=await this._getAllowance(t,a,e);if((await this.walletRepository.read(a,t)).balance<r)throw new le(`client account ${a} has insufficient funds.`);n?(n.value=r,await this.allowanceRepository.update(n,t)):(n=new je({owner:a,spender:e,value:r}),await this.allowanceRepository.create(n,t));const s={owner:a,spender:e,value:r};return this.repo.ObserverHandler().updateObservers(i,"",Be.APPROVAL,"",t,"",s),!0}async Allowance(t,e,r){await this.CheckInitialized(t);const i=await this._getAllowance(t,e,r);if(!i)throw new de(`spender ${r} has no allowance from ${e}`);return i.value}async _getAllowance(t,e,r){const i=pt.and(pt.attribute("owner").eq(e),pt.attribute("spender").eq(r)),a=await this.allowanceRepository.selectWithContext(void 0,t),n=await a.where(i).execute();return n?.[0]}async Initialize(t,e){const r=await this.tokenRepository.selectWithContext(void 0,t);if((await r.execute()).length>0)throw new nt("contract options are already set, client is not authorized to change them");return e.owner=t.clientIdentity.getID(),await this.tokenRepository.create(e,t),!0}async CheckInitialized(t){const e=await this.tokenRepository.selectWithContext(void 0,t);if(0==(await e.execute()).length)throw new ge("contract options need to be set before calling any function, call Initialize() to initialize contract")}async Mint(t,e){await this.CheckInitialized(t);const r=this.logFor(t).for(this.Mint),i=t.clientIdentity.getID();if(0>=e)throw new E("mint amount must be a positive integer");let a;try{a=await this.walletRepository.read(i,t);const r=Pe(a.balance,e),n=Object.assign({},a,{balance:r});await this.walletRepository.update(n,t)}catch(r){if(!(r instanceof A))throw new d(r);if(404!==r.code)throw new d(r.message);{const r=new ze({id:i,balance:e,token:await this.TokenName(t)});await this.walletRepository.create(r,t)}}const n={from:"0x0",to:i,value:e};this.repo.ObserverHandler().updateObservers(r,"",Be.TRANSFER,"",t,"",n)}async Burn(t,e){await this.CheckInitialized(t);const r=this.logFor(t).for(this.Burn),i=t.clientIdentity.getID(),a=await this.walletRepository.read(i,t),n=a.balance;if(e>n)throw new le("Minter has insufficient funds.");const s=xe(n,e),o=Object.assign({},a,{balance:s});await this.walletRepository.update(o,t),r.info(e+" tokens were burned");const c={from:i,to:"0x0",value:e};this.repo.ObserverHandler().updateObservers(r,"",Be.TRANSFER,"",t,"",c)}async BurnFrom(t,e,r){await this.CheckInitialized(t);const i=this.logFor(t).for(this.BurnFrom),a=await this.walletRepository.read(e,t),n=a.balance;if(r>n)throw new le(e+" has insufficient funds.");const s=xe(n,r),o=Object.assign({},a,{balance:s});await this.walletRepository.update(o,t),i.info(`${r} tokens were berned from ${e}`);const c={from:e,to:"0x0",value:r};this.repo.ObserverHandler().updateObservers(i,"",Be.TRANSFER,"",t,"",c)}async ClientAccountBalance(t){await this.CheckInitialized(t);const e=t.clientIdentity.getID(),r=await this.walletRepository.read(e,t);if(!r)throw new le(`The account ${e} does not exist`);return r.balance}async ClientAccountID(t){return await this.CheckInitialized(t),t.clientIdentity.getID()}}I([Rt(!1),F("design:type",Function),F("design:paramtypes",[Nt]),F("design:returntype",Promise)],Le.prototype,"TokenName",null),I([Rt(!1),F("design:type",Function),F("design:paramtypes",[Nt]),F("design:returntype",Promise)],Le.prototype,"Symbol",null),I([Rt(!1),F("design:type",Function),F("design:paramtypes",[Nt]),F("design:returntype",Promise)],Le.prototype,"Decimals",null),I([Rt(!1),F("design:type",Function),F("design:paramtypes",[Nt]),F("design:returntype",Promise)],Le.prototype,"TotalSupply",null),I([Rt(!1),F("design:type",Function),F("design:paramtypes",[Nt,String]),F("design:returntype",Promise)],Le.prototype,"BalanceOf",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String,Number]),F("design:returntype",Promise)],Le.prototype,"Transfer",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String,String,Number]),F("design:returntype",Promise)],Le.prototype,"TransferFrom",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String,Number]),F("design:returntype",Promise)],Le.prototype,"Approve",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String,String]),F("design:returntype",Promise)],Le.prototype,"Allowance",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt,De]),F("design:returntype",Promise)],Le.prototype,"Initialize",null),I([Rt(!1),F("design:type",Function),F("design:paramtypes",[Nt]),F("design:returntype",Promise)],Le.prototype,"CheckInitialized",null),I([Zt(),Rt(),F("design:type",Function),F("design:paramtypes",[Nt,Number]),F("design:returntype",Promise)],Le.prototype,"Mint",null),I([Zt(),Rt(),F("design:type",Function),F("design:paramtypes",[Nt,Number]),F("design:returntype",Promise)],Le.prototype,"Burn",null),I([Zt(),Rt(),F("design:type",Function),F("design:paramtypes",[Nt,String,Number]),F("design:returntype",Promise)],Le.prototype,"BurnFrom",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt]),F("design:returntype",Promise)],Le.prototype,"ClientAccountBalance",null),I([Rt(),F("design:type",Function),F("design:paramtypes",[Nt]),F("design:returntype",Promise)],Le.prototype,"ClientAccountID",null);const Me=[Le];class Ke extends a{constructor(t,e,r){super(t,e),this.logger=r?r.logger:new a(t,e)}log(t,e,r){if(n[this.config("level")]<n[t])return;let i;switch(t){case s.info:i=this.logger.info;break;case s.verbose:i=this.logger.verbose;break;case s.debug:i=this.logger.debug;break;case s.error:i=this.logger.error;break;case s.silly:i=this.logger.silly;break;default:throw Error("Invalid log level")}i.call(this.logger,this.createLog(t,e,r))}}e.setFactory((t,e,r)=>new Ke(t,e||{},r));class _e{static{this.logger=e.for(_e.name)}constructor(){}static async contentOfLoadFile(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}static async readFile(e){return"string"!=typeof e?e:await(async e=>{const{promises:r}=await t(import("fs"));return await r.readFile(e)})(e)}static async getCAUser(t,e,r,i){this.logger.debug(Q("Creating CA {0} user {1} with certificate {2}",i,t,r));const a=new o(t),n=o.newCryptoSuite();a.setCryptoSuite(n);const s=n.createKeyFromRaw(e);return await a.setEnrollment(s,r,i),a}static async getIdentity(e,r){return{mspId:e,credentials:await this.contentOfLoadFile(r,async e=>{const{promises:r}=await t(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)})}}static async getFirstDirFileName(e){const{promises:r}=await t(import("fs")),{join:i}=await t(import("path"));return i(e,(await r.readdir(e))[0])}static async getFirstDirFileNameContent(e){const{promises:r}=await t(import("fs")),{join:i}=await t(import("path")),a=await r.readdir(e);return(await r.readFile(i(e,a[0]))).toString()}static async getFileContent(e){const{promises:r}=await t(import("fs"));return(await r.readFile(e)).toString()}static async getSigner(e){const r=await this.contentOfLoadFile(e,async e=>{const{promises:r}=await t(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)}),i=await this.extractPrivateKey(r),a=i[Object.getOwnPropertySymbols(i)[0]];return c.newPrivateKeySigner(a)}static async extractPrivateKey(e){let r;if(globalThis.window&&globalThis.window.Crypto)r=globalThis.Crypto.subtle;else{const e=await t(import("crypto"));r=e.subtle||e.webcrypto.subtle}if(!r)throw Error("Could not load SubtleCrypto module");const i=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),a=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(i,"base64").toString("binary"));return await r.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}let Je=class extends lt{constructor(t){super(t),this.id=void 0,this.certificate=void 0,this.rootCertificate=void 0,this.privateKey=void 0}};I([st(),F("design:type",String)],Je.prototype,"id",void 0),I([q(),F("design:type",String)],Je.prototype,"certificate",void 0),I([q(),F("design:type",String)],Je.prototype,"rootCertificate",void 0),I([q(),F("design:type",String)],Je.prototype,"privateKey",void 0),Je=I([G(),F("design:paramtypes",[Object])],Je);let Ue=class extends lt{constructor(t){super(t),this.id=void 0,this.credentials=void 0,this.mspId=void 0,this.type=Ut.X509}};I([st(),F("design:type",String)],Ue.prototype,"id",void 0),I([St(Je,{update:gt.CASCADE,delete:gt.CASCADE}),F("design:type",Je)],Ue.prototype,"credentials",void 0),I([q(),F("design:type",String)],Ue.prototype,"mspId",void 0),I([q(),F("design:type",String)],Ue.prototype,"type",void 0),Ue=I([G(),F("design:paramtypes",[Object])],Ue);const He=new It;var qe,Ge,Ye,Ve;kt.cryptoProvider.set(He),(t=>{t.BASE2="01",t.BASE8="01234567",t.BASE11="0123456789a",t.BASE16="0123456789abcdef",t.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",t.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",t.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",t.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})(qe||(qe={})),(t=>{t.HASH="SHA-256",t[t.ITERATIONS=1e3]="ITERATIONS",t[t.KEYLENGTH=48]="KEYLENGTH",t[t.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",t[t.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",t.ALGORYTHM="AES-GCM",t.KEY_ALGORYTHM="PBKDF2"})(Ge||(Ge={}));class We{constructor(t){if(this.alphabet=t,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let t=0;t<this.baseMap.length;t++)this.baseMap[t]=255;for(let e=0;e<t.length;e++){const r=t.charAt(e),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=e}this.base=this.alphabet.length,this.leader=this.alphabet.charAt(0),this.factor=Math.log(this.base)/Math.log(256),this.iFactor=Math.log(256)/Math.log(this.base)}encode(t){if("string"==typeof t?t=Buffer.from(t):ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t)),0===t.length)return"";let e=0,r=0,i=0;const a=t.length;for(;i!==a&&0===t[i];)i++,e++;const n=(a-i)*this.iFactor+1>>>0,s=new Uint8Array(n);for(;i!==a;){let e=t[i],a=0;for(let t=n-1;(0!==e||r>a)&&-1!==t;t--,a++)e+=256*s[t]>>>0,s[t]=e%this.base>>>0,e=e/this.base>>>0;if(0!==e)throw Error("Non-zero carry");r=a,i++}let o=n-r;for(;o!==n&&0===s[o];)o++;let c=this.leader.repeat(e);for(;n>o;++o)c+=this.alphabet.charAt(s[o]);return c}decodeUnsafe(t){if(0===t.length)return new Uint8Array(0);let e=0,r=0,i=0;for(;t[e]===this.leader;)r++,e++;const a=(t.length-e)*this.factor+1>>>0,n=new Uint8Array(a);for(;t[e];){let r=this.baseMap[t.charCodeAt(e)];if(255===r)return;let s=0;for(let t=a-1;(0!==r||i>s)&&-1!==t;t--,s++)r+=this.base*n[t]>>>0,n[t]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=s,e++}let s=a-i;for(;s!==a&&0===n[s];)s++;const o=new Uint8Array(r+(a-s));let c=r;for(;s!==a;)o[c++]=n[s++];return o}decode(t){const e=this.decodeUnsafe(t);if(e)return e;throw Error("Non-base"+this.base+" character")}}class Qe{static{this.b58encoder=new We(qe.BASE58)}static{this.logger=e.for(Qe.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(Q("Parsing certificate: {0}",t));const e=new kt.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(Q("Certificate parsed with subject {0} and issuer {1}",r,i)),`x509::/${r.replaceAll(", ","/")}::/${i.replaceAll(", ","/")}`}static encode(t){return this.b58encoder.encode(t)}static decode(t){const e=this.b58encoder.decode(t);return(new TextDecoder).decode(e)}static stringToArrayBuffer(t){const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e}static async extractKey(t,e,r){const i=He.subtle,a=e.toString("utf8").replace(RegExp(`-----BEGIN (${t.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${t.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(a,"base64").toString("binary"),s=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(t,e){return this.extractKey("private",t,e)}static async extractPublicKey(t,e){return this.extractKey("public",t,e)}static async sign(t,e){const r=await this.extractPrivateKey(t),i=await He.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,e);return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}static async verify(t,e,r){const i=new kt.X509Certificate(t),a=await i.publicKey.export();return e="string"==typeof e?Buffer.from(e,"hex"):e,r="string"==typeof r?Buffer.from(r):r,He.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,e,r)}static async encrypt(t,e){const r=new kt.X509Certificate(t),i=await r.publicKey.export();e="string"==typeof e?Buffer.from(e):e;const a=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,e);return Array.from(new Uint8Array(a)).map(t=>t.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return r()?globalThis.window.crypto.subtle:He.subtle}static async decrypt(t,e){const r=await this.extractPrivateKey(t);return e="string"==typeof e?Buffer.from(e,"hex"):e,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,e)}static async getMaster(t){const e=new TextEncoder;if(void 0===t){const r=He.randomUUID();t=e.encode(r)}return{key:await this.getSubtleCrypto().importKey("raw",t,Ge.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,e){const r=(new TextEncoder).encode(t),i=await this.getSubtleCrypto().digest("SHA-256",r),a={name:Ge.KEY_ALGORYTHM,hash:Ge.HASH,salt:i,iterations:Ge.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(a,e,8*Ge.KEYLENGTH);return this.getKey(n)}static async getKey(t){const e=t.slice(0,32),r=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",e,{name:Ge.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:Ge.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:Ge.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class Xe{constructor(){}get log(){return this._log||(this._log=e.for(this.constructor.name)),this._log}static get log(){return Xe._log||(Xe._log=e.get()),Xe._log}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(Ye||(Ye={})),(t=>{t.HFREGISTRARROLES="hf.Registrar.Roles",t.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",t.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",t.HFINTERMEDIATECA="hf.IntermediateCA",t.HFREVOKER="hf.Revoker",t.HFAFFILIATIONMGR="hf.AffiliationMgr",t.HFGENCRL="hf.GenCRL"})(Ve||(Ve={}));class Ze extends Xe{constructor(t){super(),this.caConfig=t}async User(){if(this.user)return this.user;const{caName:t,caCert:e,caKey:r,url:i}=this.caConfig,a=this.log.for(this.User);a.debug(`Creating CA user for ${t} at ${i}`),a.debug("Retrieving CA certificate from "+e);const n=await _e.getFirstDirFileNameContent(e);a.debug("Retrieving CA key from "+r);const s=await _e.getFirstDirFileNameContent(r);return a.debug("Loading Admin user for ca "+t),this.user=await _e.getCAUser("admin",s,n,t),this.user}async CA(){if(this.ca)return this.ca;const t=this.log.for(this.CA),{url:e,tls:r,caName:i}=this.caConfig;let{trustedRoots:a,verify:n}=r;n=!1;const s=a[0];t.debug(`Retrieving CA certificate from ${s}. cwd: ${process.cwd()}`);const o=await _e.getFileContent(s);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new $t(e,{trustedRoots:Buffer.from(o),verify:n},i),this.ca}async Client(){if(this.client)return this.client;const t=await this.CA();return this.client=t._FabricCAServices,this.client}async Certificate(){return this.certificateService||(this.certificateService=(await this.Client()).newCertificateService()),this.certificateService}async Affiliations(){return this.affiliationService||(this.affiliationService=(await this.CA()).newAffiliationService()),this.affiliationService}async Identities(){return this.identityService||(this.identityService=(await this.CA()).newIdentityService()),this.identityService}async getCertificates(t,e=!0){const r=await this.Certificate(),i=await this.User(),a=this.log.for(this.getCertificates);a.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(t||{},i)).result;return a.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),e?n.certs.map(t=>t.PEM):n}async getIdentities(){const t=await this.Identities(),e=this.log.for(this.getIdentities);e.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new pe(t);const[,r,i]=e;switch(r){case"74":case"71":return new C(i);case"20":return new nt(i);default:return new pe(i)}}async getAffiliations(){const t=await this.Affiliations(),e=this.log.for(this.getAffiliations);e.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(t){const e=await this.CA(),r=await this.User();let i;try{i=await e.newIdentityService().getOne(t,r)}catch(e){throw new y(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new y(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,a,n){let s;const o=this.log.for(this.register);try{const{userName:c,password:l}=t,d=await this.CA(),p=await this.User(),h={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:n};s=await d.register(h,p),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return s}static identityFromEnrollment(t,e){const{certificate:r,key:i,rootCertificate:a}=t,n=this.log.for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const s=Qe.fabricIdFromCertificate(r),o=Qe.encode(s);n.debug(`Identity ${s} and encodedId ${o}`);const c=new Date;return new Ue({id:o,credentials:{id:o,certificate:r,privateKey:i.toBytes(),rootCertificate:a,createdOn:c,updatedOn:c},mspId:e,createdOn:c,updatedOn:c})}async enroll(t,e){let r;const i=this.log.for(this.enroll);try{const a=await this.CA();i.debug("Enrolling "+t);const n=await a.enroll({enrollmentID:t,enrollmentSecret:e});r=Ze.identityFromEnrollment(n,this.caConfig.caName),i.info(`Successfully enrolled ${t} under ${this.caConfig.caName} as ${r.id}`)}catch(t){throw this.parseError(t)}return r}async registerAndEnroll(t,e=!1,r="",i,a,n){const s=await this.register(t,e,r,i,a,n),{userName:o}=t;return this.enroll(o,s)}async revoke(t){const e=await this.CA(),r=await this.User(),i=await this.read(t);if(!i)throw new y("Could not find enrollment with id "+t);let a;try{a=await e.revoke({enrollmentID:i.id,reason:"User Deletation"},r)}catch(e){throw new d(`Could not revoke enrollment with id ${t}: ${e}`)}if(!a.success)throw new d(`Could not revoke enrollment with id ${t}: ${a.errors.join("\n")}`);return a}}const tr="##VERSION##",er="##PACKAGE##";Ft.registerLibrary(er,tr);export{Ke as ContractLogger,_e as CoreUtils,Wt as FabricClientAdapter,Vt as FabricClientDispatch,Te as FabricContractAdapter,Qt as FabricContractContext,we as FabricContractRepository,Xt as FabricContractRepositoryObservableHandler,ye as FabricContractSequence,Ie as FabricCrudContract,Ze as FabricEnrollmentService,Ht as FabricFlavour,Jt as FabricModelKeys,me as FabricStatement,Ve as HFCAIdentityAttributes,Ye as HFCAIdentityType,Ue as Identity,Ut as IdentityType,ee as OwnedBy,Zt as Owner,er as PACKAGE_NAME,Fe as SerializedCrudContract,tr as VERSION,xt as contentOfLoadFile,Me as contracts,Re as createdByOnFabricCreateUpdate,Kt as extractPrivateKey,Gt as generateFabricEventName,zt as getCAUser,re as getFabricModelKey,Bt as getFirstDirFileName,Lt as getFirstDirFileNameContent,jt as getIdentity,Mt as getSigner,te as ownedByOnCreate,Yt as parseEventName,Ne as pkFabricOnCreate,ie as privateData,Dt as readFile};
|
|
1
|
+
import{Repository as t,PersistenceKeys as e,final as r,Adapter as i,Dispatch as a,UnsupportedError as s,pk as n,BaseModel as o,oneToOne as c,Cascade as l,AuthorizationError as d,column as p,table as h,Sequence as u,ObserverHandler as g,index as f,Condition as y,repositoryFromTypeMetadata as w,cacheModelForPopulate as m,createOrUpdate as b,getPopulateKey as v,OrderDirection as A,NumericSequence as S,sequenceNameForModel as E,oneToManyOnUpdate as C}from"@decaf-ts/core";import{__decorate as O,__metadata as T}from"tslib";import{CouchDBAdapter as N,CouchDBKeys as R,CouchDBStatement as $,CouchDBGroupOperator as k,CouchDBOperator as I}from"@decaf-ts/for-couchdb";import*as F from"@grpc/grpc-js";import{Client as P}from"@grpc/grpc-js";import{JSONSerializer as x,getMetadata as D,ModelKeys as z,Model as j,required as B,model as L,stringFormat as M,Decoration as _,propMetadata as K,prop as J,type as U,list as H}from"@decaf-ts/decorator-validation";import{Logging as q,isBrowser as G,debug as Y,MiniLogger as V,NumericLogLevels as W,LogLevel as Q}from"@decaf-ts/logging";import{signers as X,connect as Z}from"@hyperledger/fabric-gateway";import{normalizeImport as tt}from"@decaf-ts/utils";import{User as et}from"fabric-common";import{InternalError as rt,Context as it,OperationKeys as at,SerializationError as st,BulkCrudOperationKeys as nt,modelToTransient as ot,NotFoundError as ct,transient as lt,readonly as dt,onCreate as pt,getAllPropertyDecoratorsRecursive as ht,BaseError as ut,ConflictError as gt,enforceDBDecorators as ft,ValidationError as yt,findPrimaryKey as wt,onCreateUpdate as mt,DBKeys as bt,onUpdate as vt,onDelete as At,afterAny as St}from"@decaf-ts/db-decorators";import Et from"fabric-ca-client";import*as Ct from"@peculiar/x509";import{Crypto as Ot}from"@peculiar/webcrypto";import{apply as Tt}from"@decaf-ts/reflection";import{Property as Nt,Object as Rt,Contract as $t,Transaction as kt,Context as It}from"fabric-contract-api";import{Metadata as Ft}from"@decaf-ts/decoration";const Pt=q.for("fabric-fs");async function xt(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function Dt(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await tt(import("fs"));return await e.readFile(t)})(t)}async function zt(t,e,r,i){Pt.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const a=new et(t),s=et.newCryptoSuite();a.setCryptoSuite(s);const n=s.createKeyFromRaw(e);return await a.setEnrollment(n,r,i),a}async function jt(t,e){return{mspId:t,credentials:await xt(e,async t=>{const{promises:e}=await tt(import("fs")),r=await Bt(t);return await e.readFile(r)})}}async function Bt(t){const{promises:e}=await tt(import("fs")),{join:r}=await tt(import("path"));return r(t,(await e.readdir(t))[0])}async function Lt(t){const{promises:e}=await tt(import("fs")),{join:r}=await tt(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function Mt(t){const e=await xt(t,async t=>{const{promises:e}=await tt(import("fs")),r=await Bt(t);return await e.readFile(r)}),r=await _t(e),i=r[Object.getOwnPropertySymbols(r)[0]];return X.newPrivateKeySigner(i)}async function _t(t){let e;if(G())e=globalThis.crypto.subtle;else{const t=await tt(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));try{return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(t){throw new rt(t)}}class Kt extends t{constructor(t,e){super(t,e)}async createPrefix(t,...e){const r=await it.args(at.CREATE,this.class,e,this.adapter,this._overrides||{});return[t=new this.class(t),...r.args]}async createAllPrefix(t,...e){return[t,...(await it.args(at.CREATE,this.class,e,this.adapter,this._overrides||{})).args]}async readPrefix(t,...e){return[t,...(await it.args(at.READ,this.class,e,this.adapter,this._overrides||{})).args]}async readAllPrefix(t,...e){return[t,...(await it.args(at.READ,this.class,e,this.adapter,this._overrides||{})).args]}async updatePrefix(t,...e){return[t,...(await it.args(at.UPDATE,this.class,e,this.adapter,this._overrides||{})).args]}async updateAllPrefix(t,...e){return[t,...(await it.args(at.UPDATE,this.class,e,this.adapter,this._overrides||{})).args]}async deletePrefix(t,...e){const r=await it.args(at.DELETE,this.class,e,this.adapter,this._overrides||{});return await this.read(t,...r.args),[t,...r.args]}async deleteAllPrefix(t,...e){const r=await it.args(at.DELETE,this.class,e,this.adapter,this._overrides||{});return await this.readAll(t,...r.args),[t,...r.args]}}var Jt,Ut;(t=>{t.PRIVATE="private",t.FABRIC="fabric.",t.OWNEDBY="owned-by"})(Jt||(Jt={})),(t=>{t.X509="X.509"})(Ut||(Ut={}));const Ht="hlf-fabric";class qt extends x{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i;try{i=D(t)}catch(t){i=e}if(!i)throw new st("Could not find metadata for "+t.constructor.name);return r[z.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[z.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return j.build(e,r)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class Gt extends N{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new qt}static{this.log=q.for(Gt)}get log(){return Gt.log}constructor(t,e){super(t,Ht,e),this.serializer=Gt.serializer}decode(t){return Gt.decoder.decode(t)}repository(){return Kt}async createAll(t,e,r,i){const a=this.log.for(this.createAll);if(e.length!==r.length)throw new rt(`Ids and models must have the same length: ${e.length} != ${r.length}`);a.info(`adding ${e.length} entries to ${t} table`),a.verbose("pks: "+e);const s=await this.submitTransaction(nt.CREATE_ALL,[e,r.map(e=>this.serializer.serialize(e,t))],i);try{return JSON.parse(this.decode(s)).map(t=>JSON.parse(t))}catch(t){throw new st(t)}}async readAll(t,e){const r=this.log.for(this.readAll);r.info(`reading ${e.length} entries to ${t} table`),r.verbose("pks: "+e);const i=await this.submitTransaction(nt.READ_ALL,[e]);try{return JSON.parse(this.decode(i)).map(t=>JSON.parse(t))}catch(t){throw new st(t)}}async updateAll(t,e,r,i){const a=this.log.for(this.updateAll);if(e.length!==r.length)throw new rt(`Ids and models must have the same length: ${e.length} != ${r.length}`);a.info(`updating ${e.length} entries to ${t} table`),a.verbose("pks: "+e);const s=await this.submitTransaction(nt.UPDATE_ALL,[e,r.map(e=>this.serializer.serialize(e,t))],i);try{return JSON.parse(this.decode(s)).map(t=>JSON.parse(t))}catch(t){throw new st(t)}}async deleteAll(t,e){const r=this.log.for(this.deleteAll);r.info(`deleting ${e.length} entries to ${t} table`),r.verbose("pks: "+e);const i=await this.submitTransaction(nt.DELETE_ALL,[e]);try{return JSON.parse(this.decode(i)).map(t=>JSON.parse(t))}catch(t){throw new st(t)}}prepare(t,r){const i=this.log.for(this.prepare),a=ot(t);return t[e.METADATA]&&(i.silly("Passing along persistence metadata for "+t[e.METADATA]),Object.defineProperty(a.model,e.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:t[e.METADATA]})),{record:a.model,id:t[r],transient:a.transient}}revert(t,r,i,a,s){const n=this.log.for(this.revert),o={};o[i]=a;const c="string"==typeof r?j.build(o,r):new r(o);n.silly(`Rebuilding model ${c.constructor.name} id ${a}`);const l=t[e.METADATA],d=Object.keys(c).reduce((e,r)=>(e[r]=t[r],e),c);return s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in d&&void 0!==d[t])throw new rt(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);d[t]=e})),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${a}: ${l}`),Object.defineProperty(d,e.METADATA,{enumerable:!1,configurable:!1,writable:!1,value:l})),d}index(t){throw Error()}async create(t,e,r,i){const a=this.log.for(this.create);a.verbose(`adding entry to ${t} table`),a.debug("pk: "+e);const s=await this.submitTransaction(at.CREATE,[this.serializer.serialize(r,t)],i);return this.serializer.deserialize(this.decode(s))}async read(t,e){const r=this.log.for(this.read);r.verbose(`reading entry from ${t} table`),r.debug("pk: "+e);const i=await this.evaluateTransaction(at.READ,[e.toString()]);return this.serializer.deserialize(this.decode(i))}async update(t,e,r,i){const a=this.log.for(this.update);a.verbose(`updating entry to ${t} table`),a.debug("pk: "+e);const s=await this.submitTransaction(at.UPDATE,[this.serializer.serialize(r,t)],i);return this.serializer.deserialize(this.decode(s))}async delete(t,e){const r=this.log.for(this.delete);r.verbose(`deleting entry from ${t} table`),r.debug("pk: "+e);const i=await this.submitTransaction(at.DELETE,[t,e]);return this.serializer.deserialize(this.decode(i))}async raw(t,e){const r=this.log.for(this.raw);let i,a,s;r.info("Performing raw query on table"),r.debug("processing raw input for query: "+JSON.stringify(t));try{i=JSON.stringify(t)}catch(t){throw new st("Failed to process raw input for query: "+t)}try{a=await this.evaluateTransaction("query",[i])}catch(t){throw this.parseError(t)}try{s=JSON.parse(this.decode(a))}catch(t){throw new st("Failed to process result: "+t)}if(Array.isArray(s)){if(!s.length)return s;const t=s[0];return j.isModel(t)?s.map(t=>j.build(t)):s}return n=s,j.isModel(n)?j.build(n):n;var n}getClient(){return this._client||(this._client=Gt.getClient(this.config)),this._client}async Gateway(){return Gt.getGateway(this.config,this.client)}async Contract(){return Gt.getContract(await this.Gateway(),this.config)}async transaction(t,e=!0,r,i,a){const s=this.log.for(this.transaction),n=await this.Gateway();try{const n=await this.Contract();s.verbose(`${e?"Submit":"Evaluate"}ting transaction ${this.config.contractName}.${t}`),s.debug("args: "+(r?.map(t=>t.toString()).join("\n")||"none"));const o=e?n.submit:n.evaluate;a=a?.length?a:void 0;const c={arguments:r||[],transientData:i};return await o.call(n,t,c)}catch(t){if(10===t.code)throw Error(""+t.details[0].message);throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),n.close()}}parseError(t,e){return Gt.parseError(t,e)}async submitTransaction(t,e,r,i){return this.transaction(t,!0,e,r,i)}async evaluateTransaction(t,e,r,i){return this.transaction(t,!1,e,r,i)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e){const r=this.log.for(this.getContract),i=this.getNetwork(t,e.channel);let a;try{r.debug(`Retrieving chaincode ${e.chaincodeName} contract ${e.contractName} from network ${e.channel}`),a=i.getContract(e.chaincodeName,e.contractName)}catch(t){throw this.parseError(t)}return a}static getNetwork(t,e){const r=this.log.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+e),i=t.getNetwork(e)}catch(t){throw this.parseError(t)}return i}static async getGateway(t,e){return await this.getConnection(e||await this.getClient(t),t)}static getClient(t){const e=this.log.for(this.getClient);e.debug("generating TLS credentials for msp "+t.mspId);const r=F.credentials.createSsl("string"==typeof t.tlsCert?Buffer.from(t.tlsCert):t.tlsCert);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new P(t.peerEndpoint,r)}static async getConnection(t,e){const r=this.log.for(this.getConnection);r.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const i=await jt(e.mspId,e.certCertOrDirectoryPath);r.debug("Retrieving signer key from "+e.keyCertOrDirectoryPath);const a={client:t,identity:i,signer:await Mt(e.keyCertOrDirectoryPath),evaluateOptions:()=>({deadline:Date.now()+5e3}),endorseOptions:()=>({deadline:Date.now()+15e3}),submitOptions:()=>({deadline:Date.now()+5e3}),commitStatusOptions:()=>({deadline:Date.now()+6e4})};return r.debug("Connecting to "+e.mspId),Z(a)}Dispatch(){return new Gt._baseDispatch}static parseError(t,e){return super.parseError(t,e)}}function Yt(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function Vt(t){const e=t.split("_");return 2>e.length||e.length>3?{table:void 0,event:t,owner:void 0}:{table:e[0],event:e[1],owner:e[2]}}O([Y(),T("design:type",Function),T("design:paramtypes",[Object]),T("design:returntype",Promise)],Gt.prototype,"index",null),O([Y(),r(),T("design:type",Function),T("design:paramtypes",[String,Object,Object,Object]),T("design:returntype",Promise)],Gt.prototype,"create",null),O([Y(),r(),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],Gt.prototype,"read",null),O([Y(),r(),T("design:type",Function),T("design:paramtypes",[String,Object,Object,Object]),T("design:returntype",Promise)],Gt.prototype,"update",null),O([Y(),r(),T("design:type",Function),T("design:paramtypes",[String,Object]),T("design:returntype",Promise)],Gt.prototype,"delete",null),O([Y(),T("design:type",Function),T("design:paramtypes",[Object,Boolean]),T("design:returntype",Promise)],Gt.prototype,"raw",null),Gt.decoration(),i.setCurrent(Ht);class Wt extends a{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof Gt))throw new s("Only FabricClientAdapter can be observed by dispatch");this.adapter=t,this.models=i.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))}async updateObservers(t,e,r){if(this.adapter)try{await this.adapter.refresh(t,e,r.id?r.id:void 0,r)}catch(t){throw new rt("Failed to refresh dispatch: "+t)}else this.log.verbose(`No adapter observed for dispatch; skipping observer update for ${t}:${e}`)}async handleEvents(){if(!this.listeningStack)throw new rt('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new rt("No adapter found. should be impossible");const e=this.log.for(this.handleEvents);e.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const r of this.listeningStack){const{table:i,event:a,owner:s}=Vt(r.eventName);if(s&&s!==this.adapter.config?.mspId)continue;const n=this.parsePayload(r.payload);try{await this.updateObservers(i||t.table(j.get(this.models[0].name)),a,n)}catch(t){e.error(`Failed update observables for table ${i} event ${a} id: ${n.id}: ${t}`)}}}catch(t){e.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${t}`),await this.close()}}async initialize(){if(!this.adapter)throw new rt("No adapter or config observed for dispatch");const t=(await Gt.getGateway(this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new rt("No adapter observed for dispatch");this.listeningStack=await t.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents()}}Gt&&(Gt._baseDispatch=Wt);let Qt=class extends o{constructor(t){super(t),this.id=void 0,this.certificate=void 0,this.rootCertificate=void 0,this.privateKey=void 0}};O([n(),T("design:type",String)],Qt.prototype,"id",void 0),O([B(),T("design:type",String)],Qt.prototype,"certificate",void 0),O([B(),T("design:type",String)],Qt.prototype,"rootCertificate",void 0),O([B(),T("design:type",String)],Qt.prototype,"privateKey",void 0),Qt=O([L(),T("design:paramtypes",[Object])],Qt);let Xt=class extends o{constructor(t){super(t),this.id=void 0,this.credentials=void 0,this.mspId=void 0,this.type=Ut.X509}};O([n(),T("design:type",String)],Xt.prototype,"id",void 0),O([c(Qt,{update:l.CASCADE,delete:l.CASCADE}),T("design:type",Qt)],Xt.prototype,"credentials",void 0),O([B(),T("design:type",String)],Xt.prototype,"mspId",void 0),O([B(),T("design:type",String)],Xt.prototype,"type",void 0),Xt=O([L(),T("design:paramtypes",[Object])],Xt);class Zt{static{this.logger=q.for(Zt.name)}constructor(){}static async contentOfLoadFile(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}static async readFile(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await tt(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i){this.logger.debug(M("Creating CA {0} user {1} with certificate {2}",i,t,r));const a=new et(t),s=et.newCryptoSuite();a.setCryptoSuite(s);const n=s.createKeyFromRaw(e);return await a.setEnrollment(n,r,i),a}static async getIdentity(t,e){return{mspId:t,credentials:await this.contentOfLoadFile(e,async t=>{const{promises:e}=await tt(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)})}}static async getFirstDirFileName(t){const{promises:e}=await tt(import("fs")),{join:r}=await tt(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await tt(import("fs")),{join:r}=await tt(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await tt(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await tt(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return X.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await tt(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}const te=new Ot;var ee,re;Ct.cryptoProvider.set(te),(t=>{t.BASE2="01",t.BASE8="01234567",t.BASE11="0123456789a",t.BASE16="0123456789abcdef",t.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",t.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",t.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",t.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})(ee||(ee={})),(t=>{t.HASH="SHA-256",t[t.ITERATIONS=1e3]="ITERATIONS",t[t.KEYLENGTH=48]="KEYLENGTH",t[t.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",t[t.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",t.ALGORYTHM="AES-GCM",t.KEY_ALGORYTHM="PBKDF2"})(re||(re={}));class ie{constructor(t){if(this.alphabet=t,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let t=0;t<this.baseMap.length;t++)this.baseMap[t]=255;for(let e=0;e<t.length;e++){const r=t.charAt(e),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=e}this.base=this.alphabet.length,this.leader=this.alphabet.charAt(0),this.factor=Math.log(this.base)/Math.log(256),this.iFactor=Math.log(256)/Math.log(this.base)}encode(t){if("string"==typeof t?t=Buffer.from(t):ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t)),0===t.length)return"";let e=0,r=0,i=0;const a=t.length;for(;i!==a&&0===t[i];)i++,e++;const s=(a-i)*this.iFactor+1>>>0,n=new Uint8Array(s);for(;i!==a;){let e=t[i],a=0;for(let t=s-1;(0!==e||r>a)&&-1!==t;t--,a++)e+=256*n[t]>>>0,n[t]=e%this.base>>>0,e=e/this.base>>>0;if(0!==e)throw Error("Non-zero carry");r=a,i++}let o=s-r;for(;o!==s&&0===n[o];)o++;let c=this.leader.repeat(e);for(;s>o;++o)c+=this.alphabet.charAt(n[o]);return c}decodeUnsafe(t){if(0===t.length)return new Uint8Array(0);let e=0,r=0,i=0;for(;t[e]===this.leader;)r++,e++;const a=(t.length-e)*this.factor+1>>>0,s=new Uint8Array(a);for(;t[e];){let r=this.baseMap[t.charCodeAt(e)];if(255===r)return;let n=0;for(let t=a-1;(0!==r||i>n)&&-1!==t;t--,n++)r+=this.base*s[t]>>>0,s[t]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=n,e++}let n=a-i;for(;n!==a&&0===s[n];)n++;const o=new Uint8Array(r+(a-n));let c=r;for(;n!==a;)o[c++]=s[n++];return o}decode(t){const e=this.decodeUnsafe(t);if(e)return e;throw Error("Non-base"+this.base+" character")}}class ae{static{this.b58encoder=new ie(ee.BASE58)}static{this.logger=q.for(ae.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(M("Parsing certificate: {0}",t));const e=new Ct.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(M("Certificate parsed with subject {0} and issuer {1}",r,i)),`x509::/${r.replaceAll(", ","/")}::/${i.replaceAll(", ","/")}`}static encode(t){return this.b58encoder.encode(t)}static decode(t){const e=this.b58encoder.decode(t);return(new TextDecoder).decode(e)}static stringToArrayBuffer(t){const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e}static async extractKey(t,e,r){const i=te.subtle,a=e.toString("utf8").replace(RegExp(`-----BEGIN (${t.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${t.toUpperCase()} KEY|CERTIFICATE)-----`),""),s=Buffer.from(a,"base64").toString("binary"),n=this.stringToArrayBuffer(s);return await i.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(t,e){return this.extractKey("private",t,e)}static async extractPublicKey(t,e){return this.extractKey("public",t,e)}static async sign(t,e){const r=await this.extractPrivateKey(t),i=await te.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,e);return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}static async verify(t,e,r){const i=new Ct.X509Certificate(t),a=await i.publicKey.export();return e="string"==typeof e?Buffer.from(e,"hex"):e,r="string"==typeof r?Buffer.from(r):r,te.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,e,r)}static async encrypt(t,e){const r=new Ct.X509Certificate(t),i=await r.publicKey.export();e="string"==typeof e?Buffer.from(e):e;const a=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,e);return Array.from(new Uint8Array(a)).map(t=>t.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return G()?globalThis.window.crypto.subtle:te.subtle}static async decrypt(t,e){const r=await this.extractPrivateKey(t);return e="string"==typeof e?Buffer.from(e,"hex"):e,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,e)}static async getMaster(t){const e=new TextEncoder;if(void 0===t){const r=te.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,re.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,e){const r=(new TextEncoder).encode(t),i=await this.getSubtleCrypto().digest("SHA-256",r),a={name:re.KEY_ALGORYTHM,hash:re.HASH,salt:i,iterations:re.ITERATIONS},s=await this.getSubtleCrypto().deriveBits(a,e,8*re.KEYLENGTH);return this.getKey(s)}static async getKey(t){const e=t.slice(0,32),r=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",e,{name:re.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:re.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:re.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}function se(){return function(t,e,r){const i=r.value;return r.value=async function(...t){const r=t[0],a=r.clientIdentity.getID(),s=await this.tokenRepository.selectWithContext(void 0,r),n=await s.execute();if(0==n.length)throw new ct("No tokens avaialble");if(n.length>1)throw new ct("To many token available : "+n.length);if(n[0].owner!=a)throw new d(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function ne(t,e,r,i){const{stub:a}=t,s=(await a.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:s})}function oe(){const t=ce(Jt.OWNEDBY);return _.for(t).define({decorator:()=>(t,e)=>Tt(B(),dt(),pt(ne),K(ce(Jt.OWNEDBY),e))(t,e),args:[]}).apply()}function ce(t){return j.key(Jt.FABRIC+t)}function le(t){if(!t)throw Error("Collection name is required");const e=ce(Jt.PRIVATE);return(r,i)=>{const a=i||void 0,s=Reflect.getMetadata(e,r[z.ANCHOR]||r,a),n=s?.collections||[];K(ce(Jt.PRIVATE),{...!i&&{collections:n?[...new Set([...n,t])]:[t]},isPrivate:!i})(i?r.constructor:r[z.ANCHOR]||r),i&&(K(ce(Jt.PRIVATE),{collections:n?[...new Set([...n,t])]:[t]})(r,i),lt()(r,i))}}const de=/private\s+data\s+matching\s+public\s+hash\s+version\s+is\s+not\s+available/i;function pe(t){let e=Reflect.getMetadata(ce(Jt.PRIVATE),t);return e=e||Reflect.getMetadata(ce(Jt.PRIVATE),t.constructor),e}function he(t){const e=pe(t);return!(!e||void 0===e.isPrivate)&&e.isPrivate}function ue(t){if(!(t=>!!pe(t))(t))return{model:t};const e=ht(t,void 0,ce(Jt.PRIVATE)),r=he(t),i=pe(t);let a={model:t,private:void 0};if(a=r?Object.keys(t).reduce((e,r)=>{const a=i.collections;e.private=e.private||{};for(const i of a)try{e.private[i]=e.private[i]||{},e.private[i][r]=t[r]}catch(t){throw new st(`Failed to serialize private property ${r}: ${t}`)}return e},{model:{}}):Object.entries(e).reduce((e,[r,i])=>{const a=i.find(t=>""===t.key);if(a){const i=a.props.collections;e.private=e.private||{};for(const a of i)try{e.private[a]=e.private[a]||{},e.private[a][r]=t[r]}catch(t){throw new st(`Failed to serialize private property ${r}: ${t}`)}}else e.model=e.model||{},e.model[r]=t[r];return e},{}),a.model=a.model||{},a.model=j.build(a.model,t.constructor.name),a.private){const e=Object.keys(a.private);for(const r of e)a.private[r]=j.build(a.private[r],t.constructor.name)}return a}class ge extends rt{constructor(t){super(t,ge.name)}}class fe extends rt{constructor(t){super(t,fe.name)}}class ye extends rt{constructor(t){super(t,ye.name)}}class we extends d{constructor(t){super(t,we.name)}}class me extends rt{constructor(t){super(t,me.name,500)}}class be extends ut{constructor(t="private data matching public hash version is not available ..."){super(be.name,t,403)}}class ve extends ut{constructor(t){super(ve.name,t,409)}}class Ae{constructor(){}get log(){return this._log||(this._log=q.for(this.constructor.name)),this._log}static get log(){return Ae._log||(Ae._log=q.get()),Ae._log}}var Se,Ee;(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(Se||(Se={})),(t=>{t.HFREGISTRARROLES="hf.Registrar.Roles",t.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",t.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",t.HFINTERMEDIATECA="hf.IntermediateCA",t.HFREVOKER="hf.Revoker",t.HFAFFILIATIONMGR="hf.AffiliationMgr",t.HFGENCRL="hf.GenCRL"})(Ee||(Ee={}));class Ce extends Ae{constructor(t){super(),this.caConfig=t}async User(){if(this.user)return this.user;const{caName:t,caCert:e,caKey:r,url:i}=this.caConfig,a=this.log.for(this.User);a.debug(`Creating CA user for ${t} at ${i}`),a.debug("Retrieving CA certificate from "+e);const s=await Zt.getFirstDirFileNameContent(e);a.debug("Retrieving CA key from "+r);const n=await Zt.getFirstDirFileNameContent(r);return a.debug("Loading Admin user for ca "+t),this.user=await Zt.getCAUser("admin",n,s,t),this.user}async CA(){if(this.ca)return this.ca;const t=this.log.for(this.CA),{url:e,tls:r,caName:i}=this.caConfig;let{trustedRoots:a,verify:s}=r;s=!1;const n=a[0];t.debug(`Retrieving CA certificate from ${n}. cwd: ${process.cwd()}`);const o=await Zt.getFileContent(n);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new Et(e,{trustedRoots:Buffer.from(o),verify:s},i),this.ca}async Client(){if(this.client)return this.client;const t=await this.CA();return this.client=t._FabricCAServices,this.client}async Certificate(){return this.certificateService||(this.certificateService=(await this.Client()).newCertificateService()),this.certificateService}async Affiliations(){return this.affiliationService||(this.affiliationService=(await this.CA()).newAffiliationService()),this.affiliationService}async Identities(){return this.identityService||(this.identityService=(await this.CA()).newIdentityService()),this.identityService}async getCertificates(t,e=!0){const r=await this.Certificate(),i=await this.User(),a=this.log.for(this.getCertificates);a.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.caConfig.caName}`);const s=(await r.getCertificates(t||{},i)).result;return a.debug(`Found ${s.certs.length} certificates: ${JSON.stringify(s)}`),e?s.certs.map(t=>t.PEM):s}async getIdentities(){const t=await this.Identities(),e=this.log.for(this.getIdentities);e.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new we(t);const[,r,i]=e;switch(r){case"74":case"71":return new gt(i);case"20":return new d(i);default:return new we(i)}}async getAffiliations(){const t=await this.Affiliations(),e=this.log.for(this.getAffiliations);e.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(t){const e=await this.CA(),r=await this.User();let i;try{i=await e.newIdentityService().getOne(t,r)}catch(e){throw new ct(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new ct(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,a,s){let n;const o=this.log.for(this.register);try{const{userName:c,password:l}=t,d=await this.CA(),p=await this.User(),h={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:s};n=await d.register(h,p),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return n}static identityFromEnrollment(t,e){const{certificate:r,key:i,rootCertificate:a}=t,s=this.log.for(this.identityFromEnrollment);s.debug(`Generating Identity from certificate ${r} in msp ${e}`);const n=ae.fabricIdFromCertificate(r),o=ae.encode(n);s.debug(`Identity ${n} and encodedId ${o}`);const c=new Date;return new Xt({id:o,credentials:{id:o,certificate:r,privateKey:i.toBytes(),rootCertificate:a,createdOn:c,updatedOn:c},mspId:e,createdOn:c,updatedOn:c})}async enroll(t,e){let r;const i=this.log.for(this.enroll);try{const a=await this.CA();i.debug("Enrolling "+t);const s=await a.enroll({enrollmentID:t,enrollmentSecret:e});r=Ce.identityFromEnrollment(s,this.caConfig.caName),i.info(`Successfully enrolled ${t} under ${this.caConfig.caName} as ${r.id}`)}catch(t){throw this.parseError(t)}return r}async registerAndEnroll(t,e=!1,r="",i,a,s){const n=await this.register(t,e,r,i,a,s),{userName:o}=t;return this.enroll(o,n)}async revoke(t){const e=await this.CA(),r=await this.User(),i=await this.read(t);if(!i)throw new ct("Could not find enrollment with id "+t);let a;try{a=await e.revoke({enrollmentID:i.id,reason:"User Deletation"},r)}catch(e){throw new rt(`Could not revoke enrollment with id ${t}: ${e}`)}if(!a.success)throw new rt(`Could not revoke enrollment with id ${t}: ${a.errors.join("\n")}`);return a}}let Oe=class extends o{constructor(t){super(t)}};O([n({type:"String"}),T("design:type",String)],Oe.prototype,"name",void 0),O([p(),B(),T("design:type",String)],Oe.prototype,"owner",void 0),O([p(),B(),T("design:type",String)],Oe.prototype,"symbol",void 0),O([p(),B(),T("design:type",Number)],Oe.prototype,"decimals",void 0),Oe=O([h("erc20_tokens"),L(),T("design:paramtypes",[Object])],Oe);let Te=class extends o{constructor(t){super(t)}};O([n({type:"String"}),T("design:type",String)],Te.prototype,"id",void 0),O([p(),B(),T("design:type",String)],Te.prototype,"token",void 0),O([p(),B(),T("design:type",Number)],Te.prototype,"balance",void 0),O([p(),T("design:type",String)],Te.prototype,"captive",void 0),Te=O([h("erc20_wallets"),L(),T("design:paramtypes",[Object])],Te);let Ne=class extends o{constructor(t){super(t)}};O([n({type:"String"}),p(),B(),T("design:type",String)],Ne.prototype,"owner",void 0),O([p(),B(),T("design:type",String)],Ne.prototype,"spender",void 0),O([p(),B(),T("design:type",Number)],Ne.prototype,"value",void 0),Ne=O([h("erc20_allowances"),L(),T("design:paramtypes",[Object])],Ne);class Re extends Kt{static{this.serializer=new qt}static{this.decoder=new TextDecoder("utf8")}async updateObservers(t,e,r,...i){if(!this.observerHandler)throw new rt("ObserverHandler not initialized. Did you register any observables?");let a;this.log.for(this.updateObservers).verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),a=void 0===r?void 0:Array.isArray(r)?r.map(t=>u.parseValue(this.pkProps.type,t)):u.parseValue(this.pkProps.type,r),await this.observerHandler.updateObservers(this.log,t,e,a,...i)}decode(t){return Re.decoder.decode(t)}get adapter(){return super.adapter}constructor(t){super(t,Te),this.serializer=Re.serializer}async tokenName(){const t=await this.adapter.submitTransaction("TokenName");return this.decode(t)}async symbol(){const t=await this.adapter.submitTransaction("Symbol");return this.decode(t)}async decimals(){const t=await this.adapter.submitTransaction("Decimals");return Number(this.decode(t))}async totalSupply(){const t=await this.adapter.submitTransaction("TotalSupply");return Number(this.decode(t))}async balanceOf(t){const e=await this.adapter.submitTransaction("BalanceOf",[t]);return Number(this.decode(e))}async transfer(t,e){const r=await this.adapter.submitTransaction("Transfer",[t,e.toString()]);return"true"===this.decode(r)}async transferFrom(t,e,r){const i=await this.adapter.submitTransaction("TransferFrom",[t,e,r.toString()]);return"true"===this.decode(i)}async approve(t,e){const r=await this.adapter.submitTransaction("Approve",[t,e.toString()]);return"true"===this.decode(r)}async allowance(t,e){const r=await this.adapter.submitTransaction("Allowance",[t,e]);return Number(this.decode(r))}async initialize(t){const e=await this.adapter.submitTransaction("Initialize",[Re.serializer.serialize(t)]);return"true"===this.decode(e)}async checkInitialized(){await this.adapter.submitTransaction("CheckInitialized")}async mint(t){await this.adapter.submitTransaction("Mint",[t.toString()])}async burn(t){await this.adapter.submitTransaction("Burn",[t.toString()])}async burnFrom(t,e){await this.adapter.submitTransaction("BurnFrom",[t,e.toString()])}async clientAccountBalance(){const t=await this.adapter.submitTransaction("ClientAccountBalance");return Number(this.decode(t))}async clientAccountID(){const t=await this.adapter.submitTransaction("ClientAccountID");return this.decode(t)}}class $e extends it{constructor(){super()}get stub(){return this.get("stub")}get timestamp(){return this.stub.getDateTimestamp()}get identity(){try{return this.get("clientIdentity")}catch(t){return this.get("identity")}}get logger(){return this.get("logger")}}class ke extends g{constructor(t=[at.CREATE,at.UPDATE,at.DELETE,nt.CREATE_ALL,nt.UPDATE_ALL,nt.DELETE_ALL]){super(),this.supportedEvents=t}async updateObservers(t,e,r,i,a,s,n){const{stub:o}=a;if(-1!==this.supportedEvents.indexOf(r)){t.debug(`Emitting ${r} event`);const a=Yt(e,r,s);o.setEvent(a,Buffer.from(JSON.stringify({id:i})))}else o.setEvent(r,Buffer.from(JSON.stringify(n)))}}let Ie=class extends o{constructor(t){super(t)}};O([n(),T("design:type",String)],Ie.prototype,"id",void 0),O([B(),f(),T("design:type",Object)],Ie.prototype,"current",void 0),Ie=O([h(R.SEQUENCE),L(),T("design:paramtypes",[Object])],Ie);class Fe extends u{constructor(e,r,i){super(e);for(const t of i||[])le(t)(Ie);this.repo=t.forModel(Ie,r.alias)}async current(t){if(!t)throw new me("Context is required");const{name:e,startWith:r}=this.options;try{const r=await this.repo.read(e,t);return this.parse(r.current)}catch(t){if(t instanceof ct){if(void 0===r)throw new rt("Starting value is not defined for a non existing sequence");try{return this.parse(r)}catch(t){throw new rt(`Failed to parse initial value for sequence ${r}: ${t}`)}}throw new rt(`Failed to retrieve current value for sequence ${e}: ${t}`)}}parse(t){return u.parseValue(this.options.type,t)}async increment(t,e,r){if(!r)throw new me("Context is required");const{type:i,incrementBy:a,name:s}=this.options;let n;const o=e||a;if(o%a!==0)throw new rt("Value to increment does not consider the incrementBy setting: "+a);switch(i){case"Number":n=this.parse(t)+o;break;case"BigInt":n=this.parse(t)+BigInt(o);break;default:throw new rt("Should never happen")}let c;try{c=await this.repo.update(new Ie({id:s,current:n}),r)}catch(t){if(!(t instanceof ct))throw t;c=await this.repo.create(new Ie({id:s,current:n}),r)}return c.current}async next(t){if(!t)throw new me("Context is required");const e=await this.current(t);return this.increment(e,void 0,t)}async range(t,e){if(!e)throw new me("Context is required");const r=await this.current(e),i=this.parse(this.options.incrementBy),a=await this.increment(r,this.parse(t)*i,e),s=[];for(let e=1;t>=e;e++)s.push(r+i*this.parse(e));if(s[s.length-1]!==a)throw new rt("Miscalculation of range");return s}}class Pe extends t{constructor(t,e,r){super(t,e),this.trackedEvents=r}logFor(t){return q.for(Pe,{},t)}async create(t,...e){const r=e[e.length-1],i=this.logFor(r).for(this.create);i.info("Preparing model: "+JSON.stringify(t));let a,{record:s,id:n,transient:o}=this.adapter.prepare(t,this.pk,this.tableName,...e);return i.info("Creating model: "+JSON.stringify(t)),s=await this.adapter.create(this.tableName,n,s,...e),e.length&&(a=e[e.length-1]),i.info("Reverting model: "+JSON.stringify(t)),this.adapter.revert(s,this.class,this.pk,n,a&&a.get("rebuildWithTransient")?o:void 0)}async read(t,...e){const r=await this.adapter.read(this.tableName,t,new this.class,...e);return this.adapter.revert(r,this.class,this.pk,t)}async delete(t,...e){const r=await this.adapter.delete(this.tableName,t,new this.class,...e);return this.adapter.revert(r,this.class,this.pk,t)}async update(t,...e){const r=e[e.length-1],i=this.logFor(r).for(this.update);i.info("Preparing model: "+JSON.stringify(t));let a,{record:s,id:n,transient:o}=this.adapter.prepare(t,this.pk,this.tableName,...e);return i.info("Updating model: "+JSON.stringify(t)),s=await this.adapter.update(this.tableName,n,s,...e),e.length&&(a=e[e.length-1]),i.info("Reverting model: "+JSON.stringify(t)),this.adapter.revert(s,this.class,this.pk,n,a&&a.get("rebuildWithTransient")?o:void 0)}ObserverHandler(){return new ke}async createAll(t,...e){if(!t.length)return t;const r=t.map(t=>this.adapter.prepare(t,this.pk,this.tableName,...e)),i=r.map(t=>t.id);let a=r.map(t=>t.record);const s=r.map(t=>t.transient).filter(t=>!!t);let n;return e.length&&(n=e[e.length-1]),a=await this.adapter.createAll(this.tableName,i,a,...e),a.map((t,e)=>this.adapter.revert(t,this.class,this.pk,i[e],n&&n.get("rebuildWithTransient")?s:void 0))}async updateAll(t,...e){if(!t.length)return t;const r=t.map(t=>this.adapter.prepare(t,this.pk,this.tableName,...e)),i=r.map(t=>t.transient).filter(t=>!!t);let a;return e.length&&(a=e[e.length-1]),(await this.adapter.updateAll(this.tableName,r.map(t=>t.id),r.map(t=>t.record),...e)).map((t,e)=>this.adapter.revert(t,this.class,this.pk,r[e].id,a&&a.get("rebuildWithTransient")?i:void 0))}async raw(t,e,...r){const i=r.pop(),a=await it.args("QUERY",this.class,[i],this.adapter,{});return this.adapter.raw(t,e,new this.class,...a.args)}async updateObservers(t,e,r,i,...a){if(!this.trackedEvents||-1!==this.trackedEvents.indexOf(e))return await super.updateObservers(t,e,r,i,...a)}async selectWithContext(t,e){let r;return e instanceof $e?r.context=e:r=await it.args(at.CREATE,this.class,[e],this.adapter,this._overrides||{}),t?this.adapter.Statement(r.context).select(t).from(this.class):this.adapter.Statement(r.context).select().from(this.class)}async createAllPrefix(e,...r){const i=r[r.length-1],a=await it.args(at.CREATE,this.class,r,this.adapter,this._overrides||{});if(!e.length)return[e,...a.args];const s=t.getSequenceOptions(e[0]);let n=[];s.type?(s.name||(s.name=Fe.pk(e[0])),n=await(await this.adapter.Sequence(s)).range(e.length,i)):n=e.map((t,e)=>{if(void 0===t[this.pk])throw new rt("Primary key is not defined for model in position "+e);return t[this.pk]}),e=await Promise.all(e.map(async(t,e)=>(t=new this.class(t),s.type&&(t[this.pk]=n[e]),await ft(this,a.context,t,at.CREATE,at.ON),t)));const o=a.context.get("ignoredValidationProperties")||[],c=(await Promise.all(e.map(t=>Promise.resolve(t.hasErrors(...o))))).reduce((t,e,r)=>(e&&(t="string"==typeof t?t+`\n - ${r}: ${e.toString()}`:` - ${r}: ${e.toString()}`),t),void 0);if(c)throw new yt(c);return[e,...a.args]}async createPrefix(t,...e){const r=await super.createPrefix(t,...e),i=r[0][this.pk];try{if(await this.read(i+"",...e))throw new gt(`Conflict detected while creating model with id: ${i} already exists`)}catch(t){if(404!==t.code)throw t;this.logFor(e[e.length-1]).info(`Record entry with pk ${i} does not exist, creating it now...`)}return r}}class xe extends ${constructor(t,e){super(t),this.ctx=e}async raw(t){const e=await this.adapter.raw(t,!0,this.ctx),r=wt(new this.fromSelector),i=r.id,a=r.props.type;return this.selectSelector?e:e.map(t=>this.processRecord(t,i,a))}build(){const e={};e[R.TABLE]={},e[R.TABLE]=t.table(this.fromSelector);const r={selector:e};if(this.selectSelector&&(r.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(y.and(this.whereCondition,y.attribute(R.TABLE).eq(r.selector[R.TABLE]))).selector,e=Object.keys(t);if(1===e.length&&-1!==Object.values(k).indexOf(e[0]))switch(e[0]){case k.AND:t[k.AND]=[...Object.values(t[k.AND]).reduce((t,e)=>{const r=Object.keys(e);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const i=r[0];return i===k.AND?t.push(...e[i]):t.push(e),t},[])],r.selector=t;break;case k.OR:{const e={};e[k.AND]=[t,...Object.entries(r.selector).map(([t,e])=>{const r={};return r[t]=e,r})],r.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,e])=>{r.selector[t],r.selector[t]=e})}if(this.orderBySelector){r.sort=r.sort||[],r.selector=r.selector||{};const[t,e]=this.orderBySelector,i={};i[t]=e,r.sort.push(i),r.selector[t]||(r.selector[t]={},r.selector[t][I.BIGGER]=null)}return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),r}}class De extends x{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}preSerialize(t){return Object.assign({},t)}}async function ze(e,r,i,a){const s=a[i];if(!s)return;if("object"!=typeof s){const t=w(a,i,this.adapter.alias),r=await t.read(s,e);return await m(e,a,i,s,r),void(a[i]=s)}r.class="string"==typeof r.class?r.class:r.class().name;const n=j.get(r.class);if(!n)throw new rt("Could not find model "+r.class);const o=t.forModel(n,this.adapter.alias),c=await o.create(s,e),l=wt(c).id;await m(e,a,i,c[l],c),a[i]=c[l]}async function je(t,e,r,i){const a=i[r];if(!a)return;if(e.cascade.update!==l.CASCADE)return;if("object"!=typeof a){const e=w(i,r,this.adapter.alias),s=await e.read(a,t);return await m(t,i,r,a,s),void(i[r]=a)}const s=await b(i[r],t,this.adapter.alias),n=wt(s).id;await m(t,i,r,s[n],s),i[r]=s[n]}async function Be(t,e,r,i){const a=i[r];if(!a)return;if(e.cascade.update!==l.CASCADE)return;const s=w(i,r,this.adapter.alias);let n;n=a instanceof j?await s.delete(i[r][s.pk],t):await s.delete(i[r],t),await m(t,i,r,n[s.pk],n)}async function Le(t,e,r,i){const a=i[r];if(!a||!a.length)return;const s=typeof a[0];if(!a.every(t=>typeof t===s))throw new rt(`Invalid operation. All elements of property ${r} must match the same type.`);const n=new Set([...a]);if("object"!==s){const e=w(i,r,this.adapter.alias);for(const a of n){const s=await e.read(a,t);await m(t,i,r,a,s)}return void(i[r]=[...n])}const o=wt(a[0]).id,c=new Set;for(const e of a){const a=await b(e,t,this.adapter.alias);await m(t,i,r,a[o],a),c.add(a[o])}i[r]=[...c]}async function Me(e,r,i,a){if(r.cascade.delete!==l.CASCADE)return;const s=a[i];if(!s||!s.length)return;const n=typeof s[0];if(!s.every(t=>typeof t===n))throw new rt(`Invalid operation. All elements of property ${i} must match the same type.`);const o="object"===n,c=o?t.forModel(s[0],this.adapter.alias):w(a,i,this.adapter.alias),d=new Set([...o?s.map(t=>t[c.pk]):s]);for(const t of d.values()){const r=await c.delete(t,e);await m(e,a,i,t,r)}a[i]=[...d]}async function _e(t,e,r,i){if(!e.populate)return;const a=i[r],s=Array.isArray(a);if(void 0===a||s&&0===a.length)return;const n=await(async(e,r,i,a,s)=>{let n,o;const c=[];for(const l of a){n=v(r.constructor.name,i,l);try{o=await e.get(n)}catch(e){const a=w(r,i,s);if(!a)throw new rt("Could not find repo");o=await a.read(l,t)}c.push(o)}return c})(t,i,r,s?a:[a],this.adapter.alias);i[r]=s?n:n[0]}async function Ke(t,e,r,i){try{const e=t.get("clientIdentity");i[r]=e.getID()}catch(t){throw new s("No User found in context. Please provide a user in the context")}}async function Je(t,e,r,i){if(!e.type||i[r])return;let a;e.name||(e.name=E(i,"pk"));try{a=await this.adapter.Sequence(e)}catch(t){throw new rt(`Failed to instantiate Sequence ${e.name}: ${t}`)}const s=await a.next(t);Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:s})}class Ue extends N{getClient(){throw new s("Client is not supported in Fabric contracts")}static{this.textDecoder=new TextDecoder("utf8")}static{this.serializer=new De}logFor(t){return q.for(Ue,{},t)}repository(){return Pe}constructor(t,e){super(t,Ht,e),this.Context=$e}for(t,...e){return super.for(t,...e)}async create(t,e,r,...i){const{stub:a,logger:s}=i.pop(),n=s.for(this.create);try{n.info(`adding entry to ${t} table with pk ${e}`),r=await this.putState(a,e.toString(),r)}catch(t){throw this.parseError(t)}return r}async read(t,e,...r){const{stub:i,logger:a}=r.pop(),s=a.for(this.read);let n;try{const r=await this.readState(i,t,e.toString());if(1>r.length)throw s.debug(`No record found for id ${e} in ${t} table`),new ct(`No record found for id ${e} in ${t} table`);2>r.length?(s.debug(`No record found for id ${e} in ${t} table`),n=r.pop()):n=this.mergeModels(r)}catch(t){throw this.parseError(t)}return n}async update(t,e,r,...i){const{stub:a,logger:s}=i.pop(),n=s.for(this.update);try{n.info(`updating entry to ${t} table with pk ${e}`),r=await this.putState(a,e.toString(),r)}catch(t){throw this.parseError(t)}return r}async delete(t,e,...r){const i=r.pop(),{stub:a,logger:s}=i,n=s.for(this.delete);let o;r.push(i);try{o=await this.read(t,e,...r),n.verbose(`deleting entry with pk ${e} from ${t} table`),this.deleteState(a,t,e.toString())}catch(t){throw this.parseError(t)}return o}async deleteState(t,e,r,...i){const a=t.createCompositeKey(e,[r+""]);await t.deleteState(a)}async putState(t,e,r,...i){let a;try{a=Buffer.from(Ue.serializer.serialize(r))}catch(t){throw new st(`Failed to serialize record with id ${e}: ${t}`)}return await t.putState(e.toString(),a),r}async readState(t,e,r,...i){const a=t.createCompositeKey(e,[r+""]),s=[];let n=await t.getState(a);if(""===n.toString())throw new ct(`Record with id ${r} not found`);try{n=Ue.serializer.deserialize(n.toString())}catch(t){throw new st("Failed to parse record: "+t)}return s.push(n),s}async queryResult(t,e,...r){return await t.getQueryResult(JSON.stringify(e))}async queryResultPaginated(t,e,r=250,i,...a){return await t.getQueryResultWithPagination(JSON.stringify(e),r,i?.toString())}mergeModels(t){const e=t=>Object.entries(t).reduce((t,[e,r])=>(void 0!==r&&(t[e]=r),t),{});let r=t.pop();for(const i of t)r=Object.assign({},e(r),e(i));return r}decode(t){return Ue.textDecoder.decode(t)}async flags(t,e,r,i,...a){return Object.assign(await super.flags(t,e,r,...a),{stub:i.stub,identity:i.clientIdentity,logger:this.logFor(i)})}index(t){return Promise.resolve(void 0)}async resultIterator(t,e,r=!1){const i=[];let a=await e.next();for(;!a.done;){if(a.value&&a.value.value.toString()){let e={};if(t.debug(a.value.value.toString("utf8")),r){e.TxId=a.value.txId,e.Timestamp=a.value.timestamp;try{e.Value=JSON.parse(a.value.value.toString("utf8"))}catch(r){t.error(r),e.Value=a.value.value.toString("utf8")}}else try{e=JSON.parse(a.value.value.toString("utf8"))}catch(r){t.error(r),e=a.value.value.toString("utf8")}i.push(e)}a=await e.next()}return t.debug(`Closing iterator after ${i.length} results`),e.close(),i}async raw(t,e,...r){const{stub:i,logger:a}=r.pop(),s=a.for(this.raw),{skip:n,limit:o}=t;let c;o||n?(delete t.limit,delete t.skip,s.debug(`Retrieving paginated iterator: limit: ${o}/ skip: ${n}`),c=(await this.queryResultPaginated(i,t,o||250,n?.toString())).iterator):(s.debug("Retrieving iterator"),c=await this.queryResult(i,t)),s.debug("Iterator acquired");const l=await this.resultIterator(s,c);return s.debug("returning {0} results",""+(Array.isArray(l)?l.length:1)),l}Statement(t){if(!t)throw new me("Context is required");return new xe(this,t)}async Sequence(t){return new Fe(t,this)}async createAll(t,e,r,...i){if(e.length!==r.length)throw new rt("Ids and models must have the same length");const{logger:a}=i[i.length-1],s=a.for(this.createAll);return s.info(`Creating ${e.length} entries ${t} table`),s.debug("pks: "+e),Promise.all(e.map(async(e,a)=>this.create(t,e,r[a],...i)))}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new rt("Ids and models must have the same length");const{logger:a}=i[i.length-1],s=a.for(this.createAll);return s.info(`Updating ${e.length} entries ${t} table`),s.debug("pks: "+e),Promise.all(e.map(async(e,a)=>this.update(t,e,r[a],...i)))}prepare(r,i,...a){const{stub:s,logger:n}=a.pop(),o=a.shift(),c=n.for(this.prepare),l=ot(r),d=Object.entries(l.model).reduce((e,[i,a])=>{if(void 0===a)return e;const s=t.column(r,i);if(this.isReserved(s))throw new rt(`Property name ${s} is reserved`);return e[s]=a,e},{});return r[e.METADATA]&&(c.silly("Passing along persistence metadata for "+r[e.METADATA]),Object.defineProperty(d,e.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:r[e.METADATA]})),c.info(`Preparing record for ${o} table with pk ${r[i]}`),{record:d,id:s.createCompositeKey(o,[r[i]+""]),transient:l.transient}}revert(r,i,a,s,n){const o=this.log.for(this.revert),c={};c[a]=s;const l="string"==typeof i?j.build(c,i):new i(c);o.silly(`Rebuilding model ${l.constructor.name} id ${s}`);const d=r[e.METADATA],p=Object.keys(l).reduce((e,i)=>(e[i]=r[t.column(e,i)],e),l);return n&&(o.verbose("re-adding transient properties: "+Object.keys(n).join(", ")),Object.entries(n).forEach(([t,e])=>{if(t in p&&void 0!==p[t])throw new rt(`Transient property ${t} already exists on model ${l.constructor.name}. should be impossible`);p[t]=e})),d&&(o.silly(`Passing along ${this.flavour} persistence metadata for ${l.constructor.name} id ${s}: ${d}`),Object.defineProperty(p,e.METADATA,{enumerable:!1,configurable:!1,writable:!1,value:d})),p}createPrefix(t,e,r,...i){const a=i.pop(),s={};return s[R.TABLE]=t,Object.assign(s,r),[t,e,s,a]}updatePrefix(t,e,r,...i){const a=i.pop(),s={};return s[R.TABLE]=t,Object.assign(s,r),[t,e,s,a]}createAllPrefix(t,e,r,...i){if(e.length!==r.length)throw new rt("Ids and models must have the same length");const a=i.pop(),s=e.map((e,i)=>{const a={};return a[R.TABLE]=t,Object.assign(a,r[i]),a});return[t,e,s,a]}updateAllPrefix(t,e,r,...i){if(e.length!==r.length)throw new rt("Ids and models must have the same length");const a=i.pop(),s=e.map((e,i)=>{const a={};return a[R.TABLE]=t,Object.assign(a,r[i]),a});return[t,e,s,a]}static decoration(){super.decoration();const r=t.key(e.CREATED_BY),a=t.key(e.UPDATED_BY);_.flavouredAs(Ht).for(r).define(pt(Ke),K(r,{})).apply(),_.flavouredAs(Ht).for(a).define(mt(Ke),K(a,{})).apply();const s=t.key(bt.ID);_.flavouredAs(Ht).for(s).define(f([A.ASC,A.DSC]),B(),dt(),K(s,S),pt(Je,S)).apply();const n=i.key(e.COLUMN);_.flavouredAs(Ht).for(n).extend(Nt()).apply();const o=i.key(e.TABLE);_.flavouredAs(Ht).for(o).extend(t=>Rt()(t)).apply();const c=t.key(e.ONE_TO_ONE);_.flavouredAs(Ht).for(c).define({decorator:(t,r,i,a,s)=>{const n={class:t.name?t.name:t,cascade:r,populate:i};return a&&(n.joinTable=a),s&&(n.name=s),Tt(J(e.RELATIONS),U([t.name?t.name:t,String.name,Number.name,BigInt.name]),pt(ze,n),vt(je,n),At(Be,n),St(_e,n),K(c,n))}}).apply();const l=t.key(e.ONE_TO_MANY);_.for(l).define({decorator:(t,r,i,a,s)=>{const n={class:t.name?t.name:t,cascade:r,populate:i};return a&&(n.joinTable=a),s&&(n.name=s),Tt(J(e.RELATIONS),H([t,String,Number]),pt(Le,n),vt(C,n),At(Me,n),St(_e,n),K(l,n))}}).apply()}}Ue.decoration(),i.setCurrent(Ht);class He extends x{constructor(){super()}deserialize(t){return super.deserialize(t)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}class qe extends Ue{constructor(t,e,r){super(t,e),this.collections=r,this.collections=r||[]}async Sequence(t){return new Fe(t,this,this.collections)}async read(t,e,r,...i){const{stub:a,logger:s}=i.pop(),n=s.for(this.read);let o;try{const i=await this.readState(a,t,e.toString(),r);if(1>i.length)throw n.debug(`No record found for id ${e} in ${t} table`),new ct(`No record found for id ${e} in ${t} table`);2>i.length?(n.debug(`No record found for id ${e} in ${t} table`),o=i.pop()):o=this.mergeModels(i)}catch(t){throw this.parseError(t)}return o}async delete(t,e,r,...i){const a=i.pop(),{stub:s,logger:n}=a,o=n.for(this.delete);let c;i.push(a);try{c=await this.read(t,e,r,...i),o.verbose(`deleting entry with pk ${e} from ${t} table`),this.deleteState(s,t,e.toString(),r)}catch(t){throw this.parseError(t)}return c}prepare(e,r,...i){const{stub:a,logger:s}=i.pop(),n=i.shift(),o=s.for(this.prepare),c=((e,r)=>{const i=ot(r),a=ue(r),s=r=>Object.entries(r).reduce((i,[a,s])=>{if(void 0===s)return i;const n=t.column(r,a);if(e.isReserved(n))throw new rt(`Property name ${n} is reserved`);return i[n]=s,i},{});if(a.private){const t=Object.keys(a.private);for(const e of t)a.private[e]=s(a.private[e])}return{model:i.model,transient:i.transient,privateData:a.private,result:s(i.model)}})(this,e);return o.info(`Preparing record for ${n} table with pk ${e[r]}`),{record:c.privateData,id:a.createCompositeKey(n,[e[r]+""]),transient:c.transient}}createPrefix(t,e,r,...i){const a=i.pop(),s=Object.keys(r);for(const e of s)r[e][R.TABLE]=t;return[t,e,r,a]}updatePrefix(t,e,r,...i){const a=i.pop(),s=Object.keys(r);for(const e of s)r[e][R.TABLE]=t;return[t,e,r,a]}async putState(t,e,r,...i){const a=Object.keys(r);let s,n={};for(const i of a){n=r[i];try{s=Buffer.from(Ue.serializer.serialize(r[i]))}catch(t){throw new st(`Failed to serialize record with id ${e}: ${t}`)}await t.putPrivateData(i,e.toString(),s)}return n}async readState(t,e,r,i,...a){const s=t.createCompositeKey(e,[r+""]),n=ue(i),o=Object.keys(n.private),c=[];for(const e of o)try{let i=await t.getPrivateData(e,s);if(""===i.toString())throw new ct(`Entry with id ${r} doesn't exist...`);try{i=Ue.serializer.deserialize(i.toString())}catch(t){throw new st("Failed to parse private data: "+t)}c.push(i)}catch(t){if(de.test(t.message))throw new be(t);throw t}return c}async deleteState(t,e,r,i,...a){const s=t.createCompositeKey(e,[r+""]),n=ue(i),o=Object.keys(n.private);for(const e of o)await t.deletePrivateData(e,s)}async queryResult(t,e,r){const i=ue(r).private,a=Object.keys(i)[0]||"";return(await t.getPrivateDataQueryResult(a,JSON.stringify(e))).iterator}async queryResultPaginated(t,e,r=250,i=void 0,a){const s=ue(a).private,n=Object.keys(s)[0]||"",o=await t.getPrivateDataQueryResult(n,JSON.stringify(e)),c=[];let l=0,d=!i,p=null;for(;;){const t=await o.next();if(t.value&&t.value.value.toString()){const e=t.value.key,a=t.value.value.toString("utf8");if(!d){e===i?.toString()&&(d=!0);continue}if(c.push({Key:e,Record:JSON.parse(a)}),p=e,l++,l>=r)return await o.close(),{iterator:c,metadata:{fetchedRecordsCount:c.length,bookmark:p}}}if(t.done)return await o.close(),{iterator:c,metadata:{fetchedRecordsCount:c.length,bookmark:""}}}}async raw(t,e,...r){const{stub:i,logger:a}=r.pop(),s=a.for(this.raw),{skip:n,limit:o}=t,c=r.shift();let l;o||n?(delete t.limit,delete t.skip,s.debug(`Retrieving paginated iterator: limit: ${o}/ skip: ${n}`),l=(await this.queryResultPaginated(i,t,o||250,n?.toString(),c)).iterator):(s.debug("Retrieving iterator"),l=await this.queryResult(i,t,c)),s.debug("Iterator acquired");const d=await this.resultIterator(s,l);return s.debug("returning {0} results",""+(Array.isArray(d)?d.length:1)),d}}class Ge extends $t{static{this.serializer=new He}constructor(e,r){super(e),this.clazz=r,this.initialized=!1,Ge.adapter=this.getAdapter(r),this.repo=t.forModel(r,Ge.adapter.alias)}getAdapter(t){const e=new t;if(he(e)){const t=ue(e),r=Object.keys(t.private);return new qe(void 0,"fabric-private-data-adapter",r)}return new Ue(void 0,"fabric-public-data-adapter")}logFor(t){return q.for(Ge.name,{},t)}async create(t,e,...r){const i=this.logFor(t).for(this.create);"string"==typeof e&&(e=this.deserialize(e)),i.info("Creating model: "+JSON.stringify(e));const a=this.getTransientData(t);return i.info("Merging transient data..."),e=this.repo.merge(e,a),this.repo.create(e,t,...r)}async read(t,e,...r){return this.logFor(t).for(this.read).info(`reading entry with pk ${e} `),this.repo.read(e,t,...r)}getTransientData(t){const e=t.stub.getTransient();let r={};return e.has(this.repo.tableName)&&(r=JSON.parse(e.get(this.repo.tableName)?.toString("utf8"))),r}async update(t,e,...r){const i=this.logFor(t).for(this.update);"string"==typeof e&&(e=this.deserialize(e)),i.info("Updating model: "+JSON.stringify(e));const a=this.getTransientData(t);return i.info("Merging transient data..."),e=this.repo.merge(e,a),this.repo.update(e,t,...r)}async delete(t,e,...r){return this.logFor(t).for(this.delete).info(`deleting entry with pk ${e} `),this.repo.delete(e+"",t,...r)}async deleteAll(t,e,...r){return"string"==typeof e&&(e=JSON.parse(e)),this.repo.deleteAll(e,t,...r)}async readAll(t,e,...r){return"string"==typeof e&&(e=JSON.parse(e)),this.repo.readAll(e,t,...r)}async updateAll(t,e,...r){const i=this.logFor(t).for(this.updateAll);return"string"==typeof e&&(e=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t))),i.info(`updating ${e.length} entries to the table`),this.repo.updateAll(e,t,...r)}async raw(t,e,r,...i){return"string"==typeof e&&(e=JSON.parse(e)),this.repo.raw(e,r,t,...i)}serialize(t){return Ge.serializer.serialize(t)}deserialize(t){return Ge.serializer.deserialize(t)}async init(t){const e=this.logFor(t).for(this.init);e.info("Running contract initialization..."),this.initialized=!0,e.info("Contract initialization completed.")}async healthcheck(t){return this.logFor(t).for(this.healthcheck).info(`Running Healthcheck: ${this.initialized}...`),{healthcheck:this.initialized}}async createAll(t,e,...r){const i=this.logFor(t).for(this.createAll);return"string"==typeof e&&(e=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t))),i.info(`adding ${e.length} entries to the table`),this.repo.createAll(e,t,...r)}}class Ye extends Ge{constructor(t,e){super(t,e)}logFor(t){return q.for(Ye,{},t)}async create(t,e){const r=this.logFor(t).for(this.create);r.info("Creating model: "+e);const i=this.deserialize(e);return r.info("Model deserialized: "+JSON.stringify(i)),this.serialize(await super.create(t,i))}async read(t,e){return this.logFor(t).for(this.read).info("Reading id: "+e),this.serialize(await super.read(t,e))}async update(t,e){return this.logFor(t).for(this.update).info("Updating model: "+e),this.serialize(await super.update(t,e))}async delete(t,e){return this.logFor(t).for(this.delete).info("Deleting id: "+e),this.serialize(await super.delete(t,e))}async deleteAll(t,e){const r=JSON.parse(e);return this.logFor(t).for(this.deleteAll).info(`deleting ${r.length} entries from the table`),JSON.stringify((await super.deleteAll(t,r)).map(t=>this.serialize(t)))}async readAll(t,e){const r=JSON.parse(e);return this.logFor(t).for(this.readAll).info(`reading ${r.length} entries from the table`),JSON.stringify((await super.readAll(t,r)).map(t=>this.serialize(t)))}async updateAll(t,e){const r=this.logFor(t).for(this.updateAll),i=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t));return r.info(`Updating ${i.length} entries to the table`),JSON.stringify((await super.updateAll(t,i)).map(t=>this.serialize(t)))}async raw(t,e,r){const i=JSON.parse(e);return super.raw(t,i,r)}async init(t){await super.init(t)}async healthcheck(t){return JSON.stringify(await super.healthcheck(t))}async createAll(t,e){const r=this.logFor(t).for(this.createAll),i=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t));return r.info(`Adding ${i.length} entries to the table`),JSON.stringify((await super.createAll(t,i)).map(t=>this.serialize(t)))}}function Ve(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new ge(`Addition overflow: ${t} + ${e}`);return r}function We(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new ge(`Subtraction overflow: ${t} - ${e}`);return r}var Qe;O([kt(),T("design:type",Function),T("design:paramtypes",[It,String]),T("design:returntype",Promise)],Ye.prototype,"create",null),O([kt(!1),T("design:type",Function),T("design:paramtypes",[It,String]),T("design:returntype",Promise)],Ye.prototype,"read",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It,String]),T("design:returntype",Promise)],Ye.prototype,"update",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It,String]),T("design:returntype",Promise)],Ye.prototype,"delete",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It,String]),T("design:returntype",Promise)],Ye.prototype,"deleteAll",null),O([kt(!1),T("design:type",Function),T("design:paramtypes",[It,String]),T("design:returntype",Promise)],Ye.prototype,"readAll",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It,String]),T("design:returntype",Promise)],Ye.prototype,"updateAll",null),O([kt(!1),T("design:type",Function),T("design:paramtypes",[It,String,Boolean]),T("design:returntype",Promise)],Ye.prototype,"raw",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It]),T("design:returntype",Promise)],Ye.prototype,"init",null),O([kt(!1),T("design:type",Function),T("design:paramtypes",[It]),T("design:returntype",Promise)],Ye.prototype,"healthcheck",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It,String]),T("design:returntype",Promise)],Ye.prototype,"createAll",null),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(Qe||(Qe={}));class Xe extends Ge{constructor(t){super(t,Te),Xe.adapter=Xe.adapter||new Ue,this.walletRepository=Pe.forModel(Te,Xe.adapter.alias),this.tokenRepository=Pe.forModel(Oe,Xe.adapter.alias),this.allowanceRepository=Pe.forModel(Ne,Xe.adapter.alias)}async TokenName(t){await this.CheckInitialized(t);const e=await this.tokenRepository.selectWithContext(void 0,t);return(await e.execute())[0].name}async Symbol(t){await this.CheckInitialized(t);const e=await this.tokenRepository.selectWithContext(void 0,t);return(await e.execute())[0].symbol}async Decimals(t){await this.CheckInitialized(t);const e=await this.tokenRepository.selectWithContext(void 0,t);return(await e.execute())[0].decimals}async TotalSupply(t){await this.CheckInitialized(t);const e=await this.walletRepository.selectWithContext(void 0,t),r=await e.execute();if(0==r.length)throw new ct(`The token ${this.getName()} does not exist`);let i=0;return r.forEach(t=>{i+=t.balance}),i}async BalanceOf(t,e){return await this.CheckInitialized(t),(await this.walletRepository.read(e,t)).balance}async Transfer(t,e,r){await this.CheckInitialized(t);const i=t.clientIdentity.getID();if(!await this._transfer(t,i,e,r))throw new rt("Failed to transfer");return!0}async TransferFrom(t,e,r,i){await this.CheckInitialized(t);const a=t.clientIdentity.getID(),s=await this._getAllowance(t,e,a);if(!s||0>s.value)throw new ye(`spender ${a} has no allowance from ${e}`);const n=s.value;if(i>n)throw new fe("The spender does not have enough allowance to spend.");const o=We(n,i),c=Object.assign({},s,{value:o});if(await this.allowanceRepository.update(c,t),!await this._transfer(t,e,r,i))throw new rt("Failed to transfer");return!0}async _transfer(t,e,r,i){const a=this.logFor(t).for(this._transfer);if(e===r)throw new d("cannot transfer to and from same client account");if(0>i)throw new fe("transfer amount cannot be negative");const s=await this.walletRepository.read(e,t),n=s.balance;if(i>n)throw new fe(`client account ${e} has insufficient funds.`);let o,c=!1;try{o=await this.walletRepository.read(r,t)}catch(e){if(!(e instanceof ut))throw new rt(e);if(404!==e.code)throw new rt(e.message);o=new Te({id:r,balance:0,token:await this.TokenName(t)}),c=!0}const l=o.balance,p=We(n,i),h=Ve(l,i),u=Object.assign({},s,{balance:p});await this.walletRepository.update(u,t);const g=Object.assign({},o,{balance:h});c?await this.walletRepository.create(g,t):await this.walletRepository.update(g,t);const f={from:e,to:r,value:i};return this.repo.ObserverHandler().updateObservers(a,"",Qe.TRANSFER,"",t,"",f),!0}async Approve(t,e,r){await this.CheckInitialized(t);const i=this.logFor(t).for(this.Approve),a=t.clientIdentity.getID();let s=await this._getAllowance(t,a,e);if((await this.walletRepository.read(a,t)).balance<r)throw new fe(`client account ${a} has insufficient funds.`);s?(s.value=r,await this.allowanceRepository.update(s,t)):(s=new Ne({owner:a,spender:e,value:r}),await this.allowanceRepository.create(s,t));const n={owner:a,spender:e,value:r};return this.repo.ObserverHandler().updateObservers(i,"",Qe.APPROVAL,"",t,"",n),!0}async Allowance(t,e,r){await this.CheckInitialized(t);const i=await this._getAllowance(t,e,r);if(!i)throw new ye(`spender ${r} has no allowance from ${e}`);return i.value}async _getAllowance(t,e,r){const i=y.and(y.attribute("owner").eq(e),y.attribute("spender").eq(r)),a=await this.allowanceRepository.selectWithContext(void 0,t),s=await a.where(i).execute();return s?.[0]}async Initialize(t,e){const r=await this.tokenRepository.selectWithContext(void 0,t);if((await r.execute()).length>0)throw new d("contract options are already set, client is not authorized to change them");return e.owner=t.clientIdentity.getID(),await this.tokenRepository.create(e,t),!0}async CheckInitialized(t){const e=await this.tokenRepository.selectWithContext(void 0,t);if(0==(await e.execute()).length)throw new ve("contract options need to be set before calling any function, call Initialize() to initialize contract")}async Mint(t,e){await this.CheckInitialized(t);const r=this.logFor(t).for(this.Mint),i=t.clientIdentity.getID();if(0>=e)throw new yt("mint amount must be a positive integer");let a;try{a=await this.walletRepository.read(i,t);const r=Ve(a.balance,e),s=Object.assign({},a,{balance:r});await this.walletRepository.update(s,t)}catch(r){if(!(r instanceof ut))throw new rt(r);if(404!==r.code)throw new rt(r.message);{const r=new Te({id:i,balance:e,token:await this.TokenName(t)});await this.walletRepository.create(r,t)}}const s={from:"0x0",to:i,value:e};this.repo.ObserverHandler().updateObservers(r,"",Qe.TRANSFER,"",t,"",s)}async Burn(t,e){await this.CheckInitialized(t);const r=this.logFor(t).for(this.Burn),i=t.clientIdentity.getID(),a=await this.walletRepository.read(i,t),s=a.balance;if(e>s)throw new fe("Minter has insufficient funds.");const n=We(s,e),o=Object.assign({},a,{balance:n});await this.walletRepository.update(o,t),r.info(e+" tokens were burned");const c={from:i,to:"0x0",value:e};this.repo.ObserverHandler().updateObservers(r,"",Qe.TRANSFER,"",t,"",c)}async BurnFrom(t,e,r){await this.CheckInitialized(t);const i=this.logFor(t).for(this.BurnFrom),a=await this.walletRepository.read(e,t),s=a.balance;if(r>s)throw new fe(e+" has insufficient funds.");const n=We(s,r),o=Object.assign({},a,{balance:n});await this.walletRepository.update(o,t),i.info(`${r} tokens were berned from ${e}`);const c={from:e,to:"0x0",value:r};this.repo.ObserverHandler().updateObservers(i,"",Qe.TRANSFER,"",t,"",c)}async ClientAccountBalance(t){await this.CheckInitialized(t);const e=t.clientIdentity.getID(),r=await this.walletRepository.read(e,t);if(!r)throw new fe(`The account ${e} does not exist`);return r.balance}async ClientAccountID(t){return await this.CheckInitialized(t),t.clientIdentity.getID()}}O([kt(!1),T("design:type",Function),T("design:paramtypes",[It]),T("design:returntype",Promise)],Xe.prototype,"TokenName",null),O([kt(!1),T("design:type",Function),T("design:paramtypes",[It]),T("design:returntype",Promise)],Xe.prototype,"Symbol",null),O([kt(!1),T("design:type",Function),T("design:paramtypes",[It]),T("design:returntype",Promise)],Xe.prototype,"Decimals",null),O([kt(!1),T("design:type",Function),T("design:paramtypes",[It]),T("design:returntype",Promise)],Xe.prototype,"TotalSupply",null),O([kt(!1),T("design:type",Function),T("design:paramtypes",[It,String]),T("design:returntype",Promise)],Xe.prototype,"BalanceOf",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It,String,Number]),T("design:returntype",Promise)],Xe.prototype,"Transfer",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It,String,String,Number]),T("design:returntype",Promise)],Xe.prototype,"TransferFrom",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It,String,Number]),T("design:returntype",Promise)],Xe.prototype,"Approve",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It,String,String]),T("design:returntype",Promise)],Xe.prototype,"Allowance",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It,Oe]),T("design:returntype",Promise)],Xe.prototype,"Initialize",null),O([kt(!1),T("design:type",Function),T("design:paramtypes",[It]),T("design:returntype",Promise)],Xe.prototype,"CheckInitialized",null),O([se(),kt(),T("design:type",Function),T("design:paramtypes",[It,Number]),T("design:returntype",Promise)],Xe.prototype,"Mint",null),O([se(),kt(),T("design:type",Function),T("design:paramtypes",[It,Number]),T("design:returntype",Promise)],Xe.prototype,"Burn",null),O([se(),kt(),T("design:type",Function),T("design:paramtypes",[It,String,Number]),T("design:returntype",Promise)],Xe.prototype,"BurnFrom",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It]),T("design:returntype",Promise)],Xe.prototype,"ClientAccountBalance",null),O([kt(),T("design:type",Function),T("design:paramtypes",[It]),T("design:returntype",Promise)],Xe.prototype,"ClientAccountID",null);const Ze=[Xe];class tr extends V{constructor(t,e,r){super(t,e),this.logger=r?r.logger:new V(t,e)}log(t,e,r){if(W[this.config("level")]<W[t])return;let i;switch(t){case Q.info:i=this.logger.info;break;case Q.verbose:i=this.logger.verbose;break;case Q.debug:i=this.logger.debug;break;case Q.error:i=this.logger.error;break;case Q.silly:i=this.logger.silly;break;default:throw Error("Invalid log level")}i.call(this.logger,this.createLog(t,e,r))}}q.setFactory((t,e,r)=>new tr(t,e||{},r));const er="##VERSION##",rr="##PACKAGE##";Ft.registerLibrary(rr,er);export{tr as ContractLogger,Zt as CoreUtils,Gt as FabricClientAdapter,Wt as FabricClientDispatch,Ue as FabricContractAdapter,$e as FabricContractContext,Pe as FabricContractRepository,ke as FabricContractRepositoryObservableHandler,Fe as FabricContractSequence,Ge as FabricCrudContract,Re as FabricERC20ClientRepository,Ce as FabricEnrollmentService,Ht as FabricFlavour,Jt as FabricModelKeys,xe as FabricStatement,Ee as HFCAIdentityAttributes,Se as HFCAIdentityType,Xt as Identity,Ut as IdentityType,oe as OwnedBy,se as Owner,rr as PACKAGE_NAME,Ye as SerializedCrudContract,er as VERSION,xt as contentOfLoadFile,Ze as contracts,Ke as createdByOnFabricCreateUpdate,_t as extractPrivateKey,Yt as generateFabricEventName,zt as getCAUser,ce as getFabricModelKey,Bt as getFirstDirFileName,Lt as getFirstDirFileNameContent,jt as getIdentity,Mt as getSigner,ne as ownedByOnCreate,Vt as parseEventName,Je as pkFabricOnCreate,le as privateData,Dt as readFile};
|
|
2
2
|
//# sourceMappingURL=for-fabric.js.map
|