@leofcoin/chain 1.3.4 → 1.3.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/chain.js CHANGED
@@ -81,27 +81,27 @@ class Machine {
81
81
  case 'contractError': {
82
82
  console.warn(`removing contract ${await data.hash}`);
83
83
  await contractStore.delete(await data.hash);
84
- break
84
+ break
85
85
  }
86
86
 
87
87
  case 'executionError': {
88
88
  // console.warn(`error executing transaction ${data.message}`);
89
89
  pubsub.publish(data.id, {error: data.message});
90
- break
90
+ break
91
91
  }
92
92
 
93
93
  case 'debug': {
94
94
  for (const message of data.messages) debug(message);
95
- break
95
+ break
96
96
  }
97
97
  case 'machine-ready': {
98
98
  this.lastBlock = data.lastBlock;
99
99
  pubsub.publish('machine.ready', true);
100
- break
100
+ break
101
101
  }
102
102
  case 'response': {
103
103
  pubsub.publish(data.id, data.value);
104
- break
104
+ break
105
105
  }
106
106
  }
107
107
 
@@ -159,18 +159,18 @@ class Machine {
159
159
  * @params {ContractMessage} - contractMessage
160
160
  */
161
161
  async addContract(contractMessage) {
162
- if (!await contractStore.has(contractMessage.hash)) {
163
- await contractStore.put(contractMessage.hash, contractMessage.encoded);
164
- await this.#runContract(contractMessage);
165
- return contractMessage.hash
166
- }
167
- throw new Error('duplicate contract')
162
+ if (await contractStore.has(await contractMessage.hash)) throw new Error('duplicate contract')
163
+
164
+ await contractStore.put(await contractMessage.hash, contractMessage.encoded);
165
+ await this.#runContract(contractMessage);
166
+ return contractMessage.hash
168
167
  }
169
168
 
170
169
  async execute(contract, method, parameters) {
171
170
  return new Promise((resolve, reject) => {
172
171
  const id = node_crypto.randomBytes(20).toString('hex');
173
172
  const message = message => {
173
+ pubsub.unsubscribe(id, message);
174
174
  if (message?.error) reject(message.error);
175
175
  else resolve(message);
176
176
  };
@@ -1163,20 +1163,19 @@ async #signTransaction (transaction, wallet) {
1163
1163
  }
1164
1164
 
1165
1165
  /**
1166
- *
1167
- * @param {String} contract - a contract string (see plugins/deployContract)
1166
+ *
1167
+ * @param {String} contract
1168
+ * @param {Array} parameters
1169
+ * @returns
1168
1170
  */
1169
1171
  async deployContract(contract, parameters = []) {
1170
- globalThis.msg = {sender: peernet.selectedAccount, call: this.call};
1171
-
1172
- const hash = await this.createContractAddress(creator, contract, parameters);
1173
- console.log(hash);
1172
+ const message = await createContractMessage(peernet.selectedAccount, contract, parameters);
1174
1173
  try {
1175
- const tx = await this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'deployContract', [hash, creator, contract, constructorParameters]);
1174
+ await this.#machine.addContract(message);
1176
1175
  } catch (error) {
1177
1176
  throw error
1178
1177
  }
1179
- return this.#machine.addContract(message)
1178
+ return this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'registerContract', [await message.hash])
1180
1179
  }
1181
1180
 
1182
1181
  #createMessage(sender = peernet.selectedAccount) {
@@ -1230,6 +1229,19 @@ console.log(hash);
1230
1229
  return this.staticCall(addresses.nativeToken, 'balances')
1231
1230
  }
1232
1231
 
1232
+ get contracts() {
1233
+ return this.staticCall(addresses.contractFactory, 'contracts')
1234
+ }
1235
+ /**
1236
+ *
1237
+ * @param {Address} address old contract address
1238
+ * @param {Address} newAddress new contract address
1239
+ * @returns
1240
+ */
1241
+ async updateImplementation(address, newAddress) {
1242
+ return this.call(addresses.contractFactory, 'updateImplementation', [address, newAddress])
1243
+ }
1244
+
1233
1245
  deleteAll() {
1234
1246
  return this.#machine.deleteAll()
1235
1247
  }
@@ -1 +1 @@
1
- class Factory{#name="ArtOnlineContractFactory";#totalContracts=0;#contracts=[];#implementations={};constructor(state){state&&(this.#contracts=state.contracts,this.#totalContracts=state.totalContracts,this.#implementations=state.implementations)}get state(){return{totalContracts:this.#totalContracts,contracts:this.#contracts,implementations:this.#implementations}}get name(){return this.#name}get contracts(){return[...this.#contracts]}get totalContracts(){return this.#totalContracts}get implementations(){return{...this.#implementations}}async registerContract(address){let isAllowed=!1;if(isAllowed=await msg.staticCall(address,"hasRole",[msg.sender,"IMPLEMENTATION_MANAGER"]),!isAllowed)throw new Error("only the implementation manager can update");if(this.#implementations[address])throw new Error("already registered");this.#totalContracts+=1,this.#implementations[address]=[],this.#implementations[address].push(address),this.#contracts.push(address)}async updateImplementation(address,newAddress){let isAllowed=!1;if(isAllowed=await msg.staticCall(address,"hasRole",[msg.sender,"IMPLEMENTATION_MANAGER"]),!isAllowed)throw new Error("only the implementation manager can update");if(!this.#implementations[address])throw new Error(`register ${address} before updating to ${newAddress}`);this.#implementations[address].push(newAddress)}getImplementations(address){return this.#implementations[address]}getImplementation(address,index){return index=index||this.#implementations[address].length-1,this.#implementations[address][index]}}export{Factory as default};
1
+ class Factory{#name="ArtOnlineContractFactory";#totalContracts=0;#contracts=[];#implementations={};constructor(state){state&&(this.#contracts=state.contracts,this.#totalContracts=state.totalContracts,this.#implementations=state.implementations)}get state(){return{totalContracts:this.#totalContracts,contracts:this.#contracts,implementations:this.#implementations}}get name(){return this.#name}get contracts(){return[...this.#contracts]}get totalContracts(){return this.#totalContracts}get implementations(){return{...this.#implementations}}async registerContract(address){if(await msg.staticCall(address,"hasRole",[msg.sender,"OWNER"]),this.#implementations[address])throw new Error("already registered");this.#totalContracts+=1,this.#contracts.push(address)}}export{Factory as default};
@@ -1 +1 @@
1
- class Roles{#roles={IMPLEMENTATION_MANAGER:[],OWNER:[],MINT:[],BURN:[]};constructor(roles){if(roles){if(!(roles instanceof Object))throw new TypeError("expected roles to be an object");this.#roles={...roles,...this.#roles}}else this.#grantRole(msg.sender,"OWNER"),this.#grantRole(msg.sender,"IMPLEMENTATION_MANAGER")}get state(){return{roles:this.roles}}get roles(){return{...this.#roles}}hasRole(address,role){return!!this.#roles[role]&&this.#roles[role].includes(address)}#grantRole(address,role){if(this.hasRole(address,role))throw new Error(`${role} role already granted for ${address}`);this.#roles[role].push(address)}#revokeRole(address,role){if(!this.hasRole(address,role))throw new Error(`${role} role already revoked for ${address}`);if("OWNER"===role&&1===this.#roles[role].length)throw new Error("atleast one owner is needed!");this.#roles[role].splice(this.#roles[role].indexOf(address))}grantRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#grantRole(address,role)}revokeRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#revokeRole(address,role)}}class Token extends Roles{#name;#symbol;#holders=0;#balances={};#approvals={};#decimals=18;#totalSupply=BigNumber.from(0);constructor(name,symbol,decimals=18,state){if(!name)throw new Error("name undefined");if(!symbol)throw new Error("symbol undefined");super(state?.roles),this.#name=name,this.#symbol=symbol,this.#decimals=decimals}get state(){return{...super.state,holders:this.holders,balances:this.balances,approvals:{...this.#approvals},totalSupply:this.totalSupply}}get totalSupply(){return this.#totalSupply}get name(){return this.#name}get symbol(){return this.#symbol}get holders(){return this.#holders}get balances(){return{...this.#balances}}mint(to,amount){if(!this.hasRole(msg.sender,"MINT"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.add(amount),this.#increaseBalance(to,amount)}burn(to,amount){if(!this.hasRole(msg.sender,"BURN"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.sub(amount),this.#decreaseBalance(to,amount)}#beforeTransfer(from,to,amount){if(!this.#balances[from]||this.#balances[from]<amount)throw new Error("amount exceeds balance")}#updateHolders(address,previousBalance){"0x00"===this.#balances[address].toHexString()?this.#holders-=1:"0x00"!==this.#balances[address].toHexString()&&"0x00"===previousBalance.toHexString()&&(this.#holders+=1)}#increaseBalance(address,amount){this.#balances[address]||(this.#balances[address]=BigNumber.from(0));const previousBalance=this.#balances[address];this.#balances[address]=this.#balances[address].add(amount),this.#updateHolders(address,previousBalance)}#decreaseBalance(address,amount){const previousBalance=this.#balances[address];this.#balances[address]=this.#balances[address].sub(amount),this.#updateHolders(address,previousBalance)}balanceOf(address){return this.#balances[address]}setApproval(operator,amount){const owner=globalThis.msg.sender;this.#approvals[owner]||(this.#approvals[owner]={}),this.#approvals[owner][operator]=amount}approved(owner,operator,amount){return this.#approvals[owner][operator]===amount}transfer(from,to,amount){amount=BigNumber.from(amount),this.#beforeTransfer(from,to,amount),this.#decreaseBalance(from,amount),this.#increaseBalance(to,amount)}}class ArtOnline extends Token{constructor(state){super("ArtOnline","ART",18,state)}}export{ArtOnline as default};
1
+ class Roles{#roles={OWNER:[],MINT:[],BURN:[]};constructor(roles){if(roles){if(!(roles instanceof Object))throw new TypeError("expected roles to be an object");this.#roles={...roles,...this.#roles}}else this.#grantRole(msg.sender,"OWNER"),this.#grantRole(msg.sender,"IMPLEMENTATION_MANAGER")}get state(){return{roles:this.roles}}get roles(){return{...this.#roles}}hasRole(address,role){return!!this.#roles[role]&&this.#roles[role].includes(address)}#grantRole(address,role){if(this.hasRole(address,role))throw new Error(`${role} role already granted for ${address}`);this.#roles[role].push(address)}#revokeRole(address,role){if(!this.hasRole(address,role))throw new Error(`${role} role already revoked for ${address}`);if("OWNER"===role&&1===this.#roles[role].length)throw new Error("atleast one owner is needed!");this.#roles[role].splice(this.#roles[role].indexOf(address))}grantRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#grantRole(address,role)}revokeRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#revokeRole(address,role)}}class Token extends Roles{#name;#symbol;#holders=0;#balances={};#approvals={};#decimals=18;#totalSupply=BigNumber.from(0);constructor(name,symbol,decimals=18,state){if(!name)throw new Error("name undefined");if(!symbol)throw new Error("symbol undefined");super(state?.roles),this.#name=name,this.#symbol=symbol,this.#decimals=decimals}get state(){return{...super.state,holders:this.holders,balances:this.balances,approvals:{...this.#approvals},totalSupply:this.totalSupply}}get totalSupply(){return this.#totalSupply}get name(){return this.#name}get symbol(){return this.#symbol}get holders(){return this.#holders}get balances(){return{...this.#balances}}mint(to,amount){if(!this.hasRole(msg.sender,"MINT"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.add(amount),this.#increaseBalance(to,amount)}burn(from,amount){if(!this.hasRole(msg.sender,"BURN"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.sub(amount),this.#decreaseBalance(from,amount)}#beforeTransfer(from,to,amount){if(!this.#balances[from]||this.#balances[from]<amount)throw new Error("amount exceeds balance")}#updateHolders(address,previousBalance){"0x00"===this.#balances[address].toHexString()?this.#holders-=1:"0x00"!==this.#balances[address].toHexString()&&"0x00"===previousBalance.toHexString()&&(this.#holders+=1)}#increaseBalance(address,amount){this.#balances[address]||(this.#balances[address]=BigNumber.from(0));const previousBalance=this.#balances[address];this.#balances[address]=this.#balances[address].add(amount),this.#updateHolders(address,previousBalance)}#decreaseBalance(address,amount){const previousBalance=this.#balances[address];this.#balances[address]=this.#balances[address].sub(amount),this.#updateHolders(address,previousBalance)}balanceOf(address){return this.#balances[address]}setApproval(operator,amount){const owner=globalThis.msg.sender;this.#approvals[owner]||(this.#approvals[owner]={}),this.#approvals[owner][operator]=amount}approved(owner,operator,amount){return this.#approvals[owner][operator]===amount}transfer(from,to,amount){amount=BigNumber.from(amount),this.#beforeTransfer(from,to,amount),this.#decreaseBalance(from,amount),this.#increaseBalance(to,amount)}}class ArtOnline extends Token{constructor(state){super("ArtOnline","ART",18,state)}}export{ArtOnline as default};
@@ -1 +1 @@
1
- class Roles{#roles={IMPLEMENTATION_MANAGER:[],OWNER:[],MINT:[],BURN:[]};constructor(roles){if(roles){if(!(roles instanceof Object))throw new TypeError("expected roles to be an object");this.#roles={...roles,...this.#roles}}else this.#grantRole(msg.sender,"OWNER"),this.#grantRole(msg.sender,"IMPLEMENTATION_MANAGER")}get state(){return{roles:this.roles}}get roles(){return{...this.#roles}}hasRole(address,role){return!!this.#roles[role]&&this.#roles[role].includes(address)}#grantRole(address,role){if(this.hasRole(address,role))throw new Error(`${role} role already granted for ${address}`);this.#roles[role].push(address)}#revokeRole(address,role){if(!this.hasRole(address,role))throw new Error(`${role} role already revoked for ${address}`);if("OWNER"===role&&1===this.#roles[role].length)throw new Error("atleast one owner is needed!");this.#roles[role].splice(this.#roles[role].indexOf(address))}grantRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#grantRole(address,role)}revokeRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#revokeRole(address,role)}}class Validators extends Roles{#name="ArtOnlineValidators";#totalValidators=0;#activeValidators=0;#validators={};#currency;#minimumBalance;get state(){return{...super.state,minimumBalance:this.#minimumBalance,currency:this.#currency,totalValidators:this.#totalValidators,activeValidators:this.#activeValidators,validators:this.#validators}}constructor(tokenAddress,state){super(state?.roles),state?(this.#minimumBalance=state.minimumBalance,this.#currency=state.currency,this.#totalValidators=state.totalValidators,this.#activeValidators=state.activeValidators,this.#validators=state.validators):(this.#minimumBalance=5e4,this.#currency=tokenAddress,this.#totalValidators+=1,this.#activeValidators+=1,this.#validators[msg.sender]={firstSeen:Date.now(),lastSeen:Date.now(),active:!0})}get name(){return this.#name}get currency(){return this.#currency}get validators(){return{...this.#validators}}get totalValidators(){return this.#totalValidators}get minimumBalance(){return this.#minimumBalance}changeCurrency(currency){if(!this.hasRole(msg.sender,"OWNER"))throw new Error("not an owner");this.#currency=currency}has(validator){return Boolean(void 0!==this.#validators[validator])}#isAllowed(address){if(msg.sender!==address&&!this.hasRole(msg.sender,"OWNER"))throw new Error("sender is not the validator or owner");return!0}async addValidator(validator){if(this.#isAllowed(validator),this.has(validator))throw new Error("already a validator");const balance=await msg.staticCall(this.currency,"balanceOf",[validator]);if(balance<this.minimumBalance)throw new Error(`balance to low! got: ${balance} need: ${this.#minimumBalance}`);this.#totalValidators+=1,this.#activeValidators+=1,this.#validators[validator]={firstSeen:Date.now(),lastSeen:Date.now(),active:!0}}removeValidator(validator){if(this.#isAllowed(validator),!this.has(validator))throw new Error("validator not found");this.#totalValidators-=1,this.#validators[validator].active&&(this.#activeValidators-=1),delete this.#validators[validator]}async updateValidator(validator,active){if(this.#isAllowed(validator),!this.has(validator))throw new Error("validator not found");const balance=await msg.staticCall(this.currency,"balanceOf",[validator]);if(balance<this.minimumBalance&&active)throw new Error(`balance to low! got: ${balance} need: ${this.#minimumBalance}`);if(this.#validators[validator].active===active)throw new Error("already "+(active?"activated":"deactivated"));active?this.#activeValidators+=1:this.#activeValidators-=1,this.#validators[validator].active=active}}export{Validators as default};
1
+ class Roles{#roles={OWNER:[],MINT:[],BURN:[]};constructor(roles){if(roles){if(!(roles instanceof Object))throw new TypeError("expected roles to be an object");this.#roles={...roles,...this.#roles}}else this.#grantRole(msg.sender,"OWNER"),this.#grantRole(msg.sender,"IMPLEMENTATION_MANAGER")}get state(){return{roles:this.roles}}get roles(){return{...this.#roles}}hasRole(address,role){return!!this.#roles[role]&&this.#roles[role].includes(address)}#grantRole(address,role){if(this.hasRole(address,role))throw new Error(`${role} role already granted for ${address}`);this.#roles[role].push(address)}#revokeRole(address,role){if(!this.hasRole(address,role))throw new Error(`${role} role already revoked for ${address}`);if("OWNER"===role&&1===this.#roles[role].length)throw new Error("atleast one owner is needed!");this.#roles[role].splice(this.#roles[role].indexOf(address))}grantRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#grantRole(address,role)}revokeRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#revokeRole(address,role)}}class Validators extends Roles{#name="ArtOnlineValidators";#totalValidators=0;#activeValidators=0;#validators={};#currency;#minimumBalance;get state(){return{...super.state,minimumBalance:this.#minimumBalance,currency:this.#currency,totalValidators:this.#totalValidators,activeValidators:this.#activeValidators,validators:this.#validators}}constructor(tokenAddress,state){super(state?.roles),state?(this.#minimumBalance=state.minimumBalance,this.#currency=state.currency,this.#totalValidators=state.totalValidators,this.#activeValidators=state.activeValidators,this.#validators=state.validators):(this.#minimumBalance=5e4,this.#currency=tokenAddress,this.#totalValidators+=1,this.#activeValidators+=1,this.#validators[msg.sender]={firstSeen:Date.now(),lastSeen:Date.now(),active:!0})}get name(){return this.#name}get currency(){return this.#currency}get validators(){return{...this.#validators}}get totalValidators(){return this.#totalValidators}get minimumBalance(){return this.#minimumBalance}changeCurrency(currency){if(!this.hasRole(msg.sender,"OWNER"))throw new Error("not an owner");this.#currency=currency}has(validator){return Boolean(void 0!==this.#validators[validator])}#isAllowed(address){if(msg.sender!==address&&!this.hasRole(msg.sender,"OWNER"))throw new Error("sender is not the validator or owner");return!0}async addValidator(validator){if(this.#isAllowed(validator),this.has(validator))throw new Error("already a validator");const balance=await msg.staticCall(this.currency,"balanceOf",[validator]);if(balance<this.minimumBalance)throw new Error(`balance to low! got: ${balance} need: ${this.#minimumBalance}`);this.#totalValidators+=1,this.#activeValidators+=1,this.#validators[validator]={firstSeen:Date.now(),lastSeen:Date.now(),active:!0}}removeValidator(validator){if(this.#isAllowed(validator),!this.has(validator))throw new Error("validator not found");this.#totalValidators-=1,this.#validators[validator].active&&(this.#activeValidators-=1),delete this.#validators[validator]}async updateValidator(validator,active){if(this.#isAllowed(validator),!this.has(validator))throw new Error("validator not found");const balance=await msg.staticCall(this.currency,"balanceOf",[validator]);if(balance<this.minimumBalance&&active)throw new Error(`balance to low! got: ${balance} need: ${this.#minimumBalance}`);if(this.#validators[validator].active===active)throw new Error("already "+(active?"activated":"deactivated"));active?this.#activeValidators+=1:this.#activeValidators-=1,this.#validators[validator].active=active}}export{Validators as default};
@@ -72,27 +72,27 @@ class Machine {
72
72
  case 'contractError': {
73
73
  console.warn(`removing contract ${await data.hash}`);
74
74
  await contractStore.delete(await data.hash);
75
- break
75
+ break
76
76
  }
77
77
 
78
78
  case 'executionError': {
79
79
  // console.warn(`error executing transaction ${data.message}`);
80
80
  pubsub.publish(data.id, {error: data.message});
81
- break
81
+ break
82
82
  }
83
83
 
84
84
  case 'debug': {
85
85
  for (const message of data.messages) debug(message);
86
- break
86
+ break
87
87
  }
88
88
  case 'machine-ready': {
89
89
  this.lastBlock = data.lastBlock;
90
90
  pubsub.publish('machine.ready', true);
91
- break
91
+ break
92
92
  }
93
93
  case 'response': {
94
94
  pubsub.publish(data.id, data.value);
95
- break
95
+ break
96
96
  }
97
97
  }
98
98
 
@@ -150,18 +150,18 @@ class Machine {
150
150
  * @params {ContractMessage} - contractMessage
151
151
  */
152
152
  async addContract(contractMessage) {
153
- if (!await contractStore.has(contractMessage.hash)) {
154
- await contractStore.put(contractMessage.hash, contractMessage.encoded);
155
- await this.#runContract(contractMessage);
156
- return contractMessage.hash
157
- }
158
- throw new Error('duplicate contract')
153
+ if (await contractStore.has(await contractMessage.hash)) throw new Error('duplicate contract')
154
+
155
+ await contractStore.put(await contractMessage.hash, contractMessage.encoded);
156
+ await this.#runContract(contractMessage);
157
+ return contractMessage.hash
159
158
  }
160
159
 
161
160
  async execute(contract, method, parameters) {
162
161
  return new Promise((resolve, reject) => {
163
162
  const id = randomBytes(20).toString('hex');
164
163
  const message = message => {
164
+ pubsub.unsubscribe(id, message);
165
165
  if (message?.error) reject(message.error);
166
166
  else resolve(message);
167
167
  };
@@ -1154,20 +1154,19 @@ async #signTransaction (transaction, wallet) {
1154
1154
  }
1155
1155
 
1156
1156
  /**
1157
- *
1158
- * @param {String} contract - a contract string (see plugins/deployContract)
1157
+ *
1158
+ * @param {String} contract
1159
+ * @param {Array} parameters
1160
+ * @returns
1159
1161
  */
1160
1162
  async deployContract(contract, parameters = []) {
1161
- globalThis.msg = {sender: peernet.selectedAccount, call: this.call};
1162
-
1163
- const hash = await this.createContractAddress(creator, contract, parameters);
1164
- console.log(hash);
1163
+ const message = await createContractMessage(peernet.selectedAccount, contract, parameters);
1165
1164
  try {
1166
- const tx = await this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'deployContract', [hash, creator, contract, constructorParameters]);
1165
+ await this.#machine.addContract(message);
1167
1166
  } catch (error) {
1168
1167
  throw error
1169
1168
  }
1170
- return this.#machine.addContract(message)
1169
+ return this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'registerContract', [await message.hash])
1171
1170
  }
1172
1171
 
1173
1172
  #createMessage(sender = peernet.selectedAccount) {
@@ -1221,6 +1220,19 @@ console.log(hash);
1221
1220
  return this.staticCall(addresses.nativeToken, 'balances')
1222
1221
  }
1223
1222
 
1223
+ get contracts() {
1224
+ return this.staticCall(addresses.contractFactory, 'contracts')
1225
+ }
1226
+ /**
1227
+ *
1228
+ * @param {Address} address old contract address
1229
+ * @param {Address} newAddress new contract address
1230
+ * @returns
1231
+ */
1232
+ async updateImplementation(address, newAddress) {
1233
+ return this.call(addresses.contractFactory, 'updateImplementation', [address, newAddress])
1234
+ }
1235
+
1224
1236
  deleteAll() {
1225
1237
  return this.#machine.deleteAll()
1226
1238
  }
@@ -1 +1 @@
1
- class Roles{#roles={IMPLEMENTATION_MANAGER:[],OWNER:[],MINT:[],BURN:[]};constructor(roles){if(roles){if(!(roles instanceof Object))throw new TypeError("expected roles to be an object");this.#roles={...roles,...this.#roles}}else this.#grantRole(msg.sender,"OWNER"),this.#grantRole(msg.sender,"IMPLEMENTATION_MANAGER")}get state(){return{roles:this.roles}}get roles(){return{...this.#roles}}hasRole(address,role){return!!this.#roles[role]&&this.#roles[role].includes(address)}#grantRole(address,role){if(this.hasRole(address,role))throw new Error(`${role} role already granted for ${address}`);this.#roles[role].push(address)}#revokeRole(address,role){if(!this.hasRole(address,role))throw new Error(`${role} role already revoked for ${address}`);if("OWNER"===role&&1===this.#roles[role].length)throw new Error("atleast one owner is needed!");this.#roles[role].splice(this.#roles[role].indexOf(address))}grantRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#grantRole(address,role)}revokeRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#revokeRole(address,role)}}class Token extends Roles{#name;#symbol;#holders=0;#balances={};#approvals={};#decimals=18;#totalSupply=BigNumber.from(0);constructor(name,symbol,decimals=18,state){if(!name)throw new Error("name undefined");if(!symbol)throw new Error("symbol undefined");super(state?.roles),this.#name=name,this.#symbol=symbol,this.#decimals=decimals}get state(){return{...super.state,holders:this.holders,balances:this.balances,approvals:{...this.#approvals},totalSupply:this.totalSupply}}get totalSupply(){return this.#totalSupply}get name(){return this.#name}get symbol(){return this.#symbol}get holders(){return this.#holders}get balances(){return{...this.#balances}}mint(to,amount){if(!this.hasRole(msg.sender,"MINT"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.add(amount),this.#increaseBalance(to,amount)}burn(to,amount){if(!this.hasRole(msg.sender,"BURN"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.sub(amount),this.#decreaseBalance(to,amount)}#beforeTransfer(from,to,amount){if(!this.#balances[from]||this.#balances[from]<amount)throw new Error("amount exceeds balance")}#updateHolders(address,previousBalance){"0x00"===this.#balances[address].toHexString()?this.#holders-=1:"0x00"!==this.#balances[address].toHexString()&&"0x00"===previousBalance.toHexString()&&(this.#holders+=1)}#increaseBalance(address,amount){this.#balances[address]||(this.#balances[address]=BigNumber.from(0));const previousBalance=this.#balances[address];this.#balances[address]=this.#balances[address].add(amount),this.#updateHolders(address,previousBalance)}#decreaseBalance(address,amount){const previousBalance=this.#balances[address];this.#balances[address]=this.#balances[address].sub(amount),this.#updateHolders(address,previousBalance)}balanceOf(address){return this.#balances[address]}setApproval(operator,amount){const owner=globalThis.msg.sender;this.#approvals[owner]||(this.#approvals[owner]={}),this.#approvals[owner][operator]=amount}approved(owner,operator,amount){return this.#approvals[owner][operator]===amount}transfer(from,to,amount){amount=BigNumber.from(amount),this.#beforeTransfer(from,to,amount),this.#decreaseBalance(from,amount),this.#increaseBalance(to,amount)}}export{Token as default};
1
+ class Roles{#roles={OWNER:[],MINT:[],BURN:[]};constructor(roles){if(roles){if(!(roles instanceof Object))throw new TypeError("expected roles to be an object");this.#roles={...roles,...this.#roles}}else this.#grantRole(msg.sender,"OWNER"),this.#grantRole(msg.sender,"IMPLEMENTATION_MANAGER")}get state(){return{roles:this.roles}}get roles(){return{...this.#roles}}hasRole(address,role){return!!this.#roles[role]&&this.#roles[role].includes(address)}#grantRole(address,role){if(this.hasRole(address,role))throw new Error(`${role} role already granted for ${address}`);this.#roles[role].push(address)}#revokeRole(address,role){if(!this.hasRole(address,role))throw new Error(`${role} role already revoked for ${address}`);if("OWNER"===role&&1===this.#roles[role].length)throw new Error("atleast one owner is needed!");this.#roles[role].splice(this.#roles[role].indexOf(address))}grantRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#grantRole(address,role)}revokeRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#revokeRole(address,role)}}class Token extends Roles{#name;#symbol;#holders=0;#balances={};#approvals={};#decimals=18;#totalSupply=BigNumber.from(0);constructor(name,symbol,decimals=18,state){if(!name)throw new Error("name undefined");if(!symbol)throw new Error("symbol undefined");super(state?.roles),this.#name=name,this.#symbol=symbol,this.#decimals=decimals}get state(){return{...super.state,holders:this.holders,balances:this.balances,approvals:{...this.#approvals},totalSupply:this.totalSupply}}get totalSupply(){return this.#totalSupply}get name(){return this.#name}get symbol(){return this.#symbol}get holders(){return this.#holders}get balances(){return{...this.#balances}}mint(to,amount){if(!this.hasRole(msg.sender,"MINT"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.add(amount),this.#increaseBalance(to,amount)}burn(from,amount){if(!this.hasRole(msg.sender,"BURN"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.sub(amount),this.#decreaseBalance(from,amount)}#beforeTransfer(from,to,amount){if(!this.#balances[from]||this.#balances[from]<amount)throw new Error("amount exceeds balance")}#updateHolders(address,previousBalance){"0x00"===this.#balances[address].toHexString()?this.#holders-=1:"0x00"!==this.#balances[address].toHexString()&&"0x00"===previousBalance.toHexString()&&(this.#holders+=1)}#increaseBalance(address,amount){this.#balances[address]||(this.#balances[address]=BigNumber.from(0));const previousBalance=this.#balances[address];this.#balances[address]=this.#balances[address].add(amount),this.#updateHolders(address,previousBalance)}#decreaseBalance(address,amount){const previousBalance=this.#balances[address];this.#balances[address]=this.#balances[address].sub(amount),this.#updateHolders(address,previousBalance)}balanceOf(address){return this.#balances[address]}setApproval(operator,amount){const owner=globalThis.msg.sender;this.#approvals[owner]||(this.#approvals[owner]={}),this.#approvals[owner][operator]=amount}approved(owner,operator,amount){return this.#approvals[owner][operator]===amount}transfer(from,to,amount){amount=BigNumber.from(amount),this.#beforeTransfer(from,to,amount),this.#decreaseBalance(from,amount),this.#increaseBalance(to,amount)}}export{Token as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leofcoin/chain",
3
- "version": "1.3.4",
3
+ "version": "1.3.6",
4
4
  "description": "Official javascript implementation",
5
5
  "main": "./dist/node.js",
6
6
  "module": "./dist/chain.esm",
package/src/chain.js CHANGED
@@ -764,20 +764,19 @@ async #signTransaction (transaction, wallet) {
764
764
  }
765
765
 
766
766
  /**
767
- *
768
- * @param {String} contract - a contract string (see plugins/deployContract)
767
+ *
768
+ * @param {String} contract
769
+ * @param {Array} parameters
770
+ * @returns
769
771
  */
770
772
  async deployContract(contract, parameters = []) {
771
- globalThis.msg = {sender: peernet.selectedAccount, call: this.call}
772
-
773
- const hash = await this.createContractAddress(creator, contract, parameters)
774
- console.log(hash);
773
+ const message = await createContractMessage(peernet.selectedAccount, contract, parameters)
775
774
  try {
776
- const tx = await this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'deployContract', [hash, creator, contract, constructorParameters])
775
+ await this.#machine.addContract(message)
777
776
  } catch (error) {
778
777
  throw error
779
778
  }
780
- return this.#machine.addContract(message)
779
+ return this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'registerContract', [await message.hash])
781
780
  }
782
781
 
783
782
  #createMessage(sender = peernet.selectedAccount) {
@@ -831,6 +830,19 @@ console.log(hash);
831
830
  return this.staticCall(addresses.nativeToken, 'balances')
832
831
  }
833
832
 
833
+ get contracts() {
834
+ return this.staticCall(addresses.contractFactory, 'contracts')
835
+ }
836
+ /**
837
+ *
838
+ * @param {Address} address old contract address
839
+ * @param {Address} newAddress new contract address
840
+ * @returns
841
+ */
842
+ async updateImplementation(address, newAddress) {
843
+ return this.call(addresses.contractFactory, 'updateImplementation', [address, newAddress])
844
+ }
845
+
834
846
  deleteAll() {
835
847
  return this.#machine.deleteAll()
836
848
  }
@@ -54,49 +54,10 @@ export default class Factory {
54
54
  * @param {Address} address contract address to register
55
55
  */
56
56
  async registerContract(address) {
57
- let isAllowed = false
58
- isAllowed = await msg.staticCall(address, 'hasRole', [msg.sender, 'IMPLEMENTATION_MANAGER'])
59
- if (!isAllowed) throw new Error('only the implementation manager can update')
57
+ await msg.staticCall(address, 'hasRole', [msg.sender, 'OWNER'])
60
58
  if (this.#implementations[address]) throw new Error('already registered')
61
59
 
62
60
  this.#totalContracts += 1
63
- this.#implementations[address] = []
64
- this.#implementations[address].push(address)
65
61
  this.#contracts.push(address)
66
62
  }
67
-
68
- /**
69
- * updates the current implementation to a new address
70
- *
71
- * @param {Address} address the current contract address
72
- * @param {Address} newAddress the new contract address
73
- */
74
- async updateImplementation(address, newAddress) {
75
- let isAllowed = false
76
- isAllowed = await msg.staticCall(address, 'hasRole', [msg.sender, 'IMPLEMENTATION_MANAGER'])
77
- if (!isAllowed) throw new Error('only the implementation manager can update')
78
- if (!this.#implementations[address]) throw new Error(`register ${address} before updating to ${newAddress}`)
79
-
80
- this.#implementations[address].push(newAddress)
81
- }
82
-
83
- /**
84
- *
85
- * @param {Address} address the original contract address
86
- * @returns {Address} all implementations of the original contract
87
- */
88
- getImplementations(address) {
89
- return this.#implementations[address]
90
- }
91
-
92
- /**
93
- *
94
- * @param {Address} address the original contract address
95
- * @param {Number} index the index of the implmentation item or undefined (returns the latest implementation when undefined)
96
- * @returns {Address} the latest/selected implementation of the original contract
97
- */
98
- getImplementation(address, index) {
99
- index = index || this.#implementations[address].length - 1
100
- return this.#implementations[address][index]
101
- }
102
63
  }
@@ -1,7 +1,7 @@
1
- import Token from '../standards/token.js'
1
+ import Token from './../standards/token.js'
2
2
 
3
3
  export default class ArtOnline extends Token {
4
4
  constructor(state) {
5
5
  super('ArtOnline', 'ART', 18, state)
6
6
  }
7
- }
7
+ }
package/src/machine.js CHANGED
@@ -3,7 +3,6 @@ import { formatBytes } from './../../utils/src/utils'
3
3
  import { randomBytes } from 'node:crypto'
4
4
  import { join } from 'node:path'
5
5
  import EasyWorker from '@vandeurenglenn/easy-worker'
6
-
7
6
  // import State from './state'
8
7
 
9
8
  export default class Machine {
@@ -28,27 +27,27 @@ export default class Machine {
28
27
  case 'contractError': {
29
28
  console.warn(`removing contract ${await data.hash}`);
30
29
  await contractStore.delete(await data.hash)
31
- break
30
+ break
32
31
  }
33
32
 
34
33
  case 'executionError': {
35
34
  // console.warn(`error executing transaction ${data.message}`);
36
35
  pubsub.publish(data.id, {error: data.message})
37
- break
36
+ break
38
37
  }
39
38
 
40
39
  case 'debug': {
41
40
  for (const message of data.messages) debug(message)
42
- break
41
+ break
43
42
  }
44
43
  case 'machine-ready': {
45
44
  this.lastBlock = data.lastBlock
46
45
  pubsub.publish('machine.ready', true)
47
- break
46
+ break
48
47
  }
49
48
  case 'response': {
50
49
  pubsub.publish(data.id, data.value)
51
- break
50
+ break
52
51
  }
53
52
  }
54
53
 
@@ -106,18 +105,18 @@ export default class Machine {
106
105
  * @params {ContractMessage} - contractMessage
107
106
  */
108
107
  async addContract(contractMessage) {
109
- if (!await contractStore.has(contractMessage.hash)) {
110
- await contractStore.put(contractMessage.hash, contractMessage.encoded)
111
- await this.#runContract(contractMessage)
112
- return contractMessage.hash
113
- }
114
- throw new Error('duplicate contract')
108
+ if (await contractStore.has(await contractMessage.hash)) throw new Error('duplicate contract')
109
+
110
+ await contractStore.put(await contractMessage.hash, contractMessage.encoded)
111
+ await this.#runContract(contractMessage)
112
+ return contractMessage.hash
115
113
  }
116
114
 
117
115
  async execute(contract, method, parameters) {
118
116
  return new Promise((resolve, reject) => {
119
117
  const id = randomBytes(20).toString('hex')
120
118
  const message = message => {
119
+ pubsub.unsubscribe(id, message)
121
120
  if (message?.error) reject(message.error)
122
121
  else resolve(message)
123
122
  }
@@ -4,7 +4,6 @@ export default class Roles {
4
4
  * Object => Array
5
5
  */
6
6
  #roles = {
7
- 'IMPLEMENTATION_MANAGER': [],
8
7
  'OWNER': [],
9
8
  'MINT': [],
10
9
  'BURN': []
@@ -81,11 +81,11 @@ export default class Token extends Roles {
81
81
  this.#increaseBalance(to, amount)
82
82
  }
83
83
 
84
- burn(to, amount) {
84
+ burn(from, amount) {
85
85
  if (!this.hasRole(msg.sender, 'BURN')) throw new Error('not allowed')
86
86
 
87
87
  this.#totalSupply = this.#totalSupply.sub(amount)
88
- this.#decreaseBalance(to, amount)
88
+ this.#decreaseBalance(from, amount)
89
89
  }
90
90
 
91
91
  #beforeTransfer(from, to, amount) {
@@ -1,12 +0,0 @@
1
- import Proxy from '../../standards/proxy.js'
2
-
3
- export default class FactoryProxy extends Proxy {
4
- /**
5
- * string
6
- */
7
- #name = 'ArtOnlineContractFactoryProxy'
8
-
9
- constructor(proxyManager, state) {
10
- super(proxyManager, state)
11
- }
12
- }
@@ -1,12 +0,0 @@
1
- import Proxy from '../../standards/proxy.js'
2
-
3
- export default class NameServiceProxy extends Proxy {
4
- /**
5
- * string
6
- */
7
- #name = 'ArtOnlineNameServiceProxy'
8
-
9
- constructor(proxyManager, state) {
10
- super(proxyManager, state)
11
- }
12
- }
@@ -1,12 +0,0 @@
1
- import Proxy from '../../standards/proxy.js'
2
-
3
- export default class NativeTokenProxy extends Proxy {
4
- /**
5
- * string
6
- */
7
- #name = 'ArtOnlineNativeTokenProxy'
8
-
9
- constructor(proxyManager, state) {
10
- super(proxyManager, state)
11
- }
12
- }
@@ -1,12 +0,0 @@
1
- import Proxy from '../../standards/proxy.js'
2
-
3
- export default class ValidatorsProxy extends Proxy {
4
- /**
5
- * string
6
- */
7
- #name = 'ArtOnlineValidatorsProxy'
8
-
9
- constructor(proxyManager, state) {
10
- super(proxyManager, state)
11
- }
12
- }
@@ -1,12 +0,0 @@
1
- import Proxy from '../../standards/proxy.js'
2
-
3
- export default class VotingProxy extends Proxy {
4
- /**
5
- * string
6
- */
7
- #name = 'ArtOnlineVotingProxy'
8
-
9
- constructor(proxyManager, state) {
10
- super(proxyManager, state)
11
- }
12
- }
@@ -1,7 +0,0 @@
1
- import ProxyManager from '../standards/proxy-manager.js'
2
-
3
- export default class ArtOnlineProxyManager extends ProxyManager {
4
- constructor(state) {
5
- super('ArtOnlineProxyManager', state)
6
- }
7
- }
@@ -1,66 +0,0 @@
1
- import Roles from './roles.js'
2
-
3
- export default class ProxyManager extends Roles {
4
- #name
5
- #proxies = {}
6
- #manager
7
-
8
-
9
- constructor(name, state) {
10
- super(state?.roles)
11
- this.#name = name
12
-
13
- if (state) {
14
- this.#proxies = state.proxies
15
- this.#manager = state.manager
16
- } else {
17
- this.#manager = msg.sender
18
- }
19
- }
20
-
21
- /**
22
- *
23
- */
24
- async #upgradeProxy(proxy, address) {
25
- await msg.internalCall(this.#manager, proxy, 'setImplementation', [address])
26
- this.#proxies[proxy] = address
27
- }
28
-
29
- /**
30
- *
31
- */
32
- upgradeProxy(proxy, address) {
33
- if (!this.hasRole(msg.sender, 'MANAGER')) throw new Error('Not allowed, expected MANAGER')
34
- this.#upgradeProxy(proxy, address)
35
- }
36
-
37
- async #changeManager(address) {
38
- this.#revokeRole(this.#manager, 'MANAGER')
39
- this.#grantRole(address, 'MANAGER')
40
- for (const proxy of Object.keys(this.#proxies)) {
41
- await msg.internalCall(this.#manager, proxy, 'changeProxyManager', [address])
42
- }
43
- this.#manager = address
44
- }
45
-
46
- changeManager(address) {
47
- if (!this.hasRole(msg.sender, 'OWNER')) throw new Error('Not allowed, expected OWNER')
48
- return this.#changeManager(address)
49
- }
50
-
51
- get state() {
52
- return {
53
- ...super.state,
54
- proxies: this.proxies,
55
- manager: this.manager
56
- }
57
- }
58
-
59
- get manager() {
60
- return this.#manager
61
- }
62
-
63
- get proxies() {
64
- return { ...this.#proxies }
65
- }
66
- }
@@ -1,38 +0,0 @@
1
- import Roles from './roles.js'
2
-
3
- export default class Proxy extends Roles {
4
- #proxyManager
5
- #implementation
6
-
7
- constructor(proxyManager, state) {
8
- super(state?.roles)
9
- this.#proxyManager = state ? state.proxyManager : proxyManager;
10
- }
11
-
12
- get state() {
13
- return {
14
- ...super.state,
15
- proxyManager: this.#proxyManager,
16
- implementation: this.#implementation
17
- }
18
- }
19
-
20
- async setImplementation(address) {
21
- if (msg.sender !== this.#proxyManager) throw new Error(`not allowed, expected proxy manager`)
22
-
23
- const state = await stateStore.get(this.#implementation)
24
- await stateStore.put(address, state)
25
- stateStore.delete(this.#implementation)
26
- this.#implementation = address
27
- }
28
-
29
- async changeProxyManager(address) {
30
- if (msg.sender !== this.#proxyManager) throw new Error(`not allowed, expected proxy manager`)
31
- this.#proxyManager = address
32
- }
33
-
34
- fallback(method, parameters) {
35
- if (msg.sender === this.proxyManager) return this[method](...parameters)
36
- return msg.internalCall(msg.sender, this.#implementation, method, parameters)
37
- }
38
- }