@linealqorum/js 0.0.0-stage → 0.0.1

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.
Files changed (151) hide show
  1. package/package.json +16 -5
  2. package/src/artifact-service.js +94 -0
  3. package/src/artifacts/artifacts.d.ts +13 -0
  4. package/src/artifacts/build-info/solc-0_8_30-e703f2fe389268a2246aec69fef2175182b7b532.json +392 -0
  5. package/src/artifacts/build-info/solc-0_8_30-e703f2fe389268a2246aec69fef2175182b7b532.output.json +1 -0
  6. package/src/artifacts/contracts/Counter.sol/Counter.json +60 -0
  7. package/src/artifacts/contracts/Counter.sol/artifacts.d.ts +27 -0
  8. package/src/artifacts/contracts/core/BaseAccount.sol/BaseAccount.json +116 -0
  9. package/src/artifacts/contracts/core/BaseAccount.sol/artifacts.d.ts +27 -0
  10. package/src/artifacts/contracts/core/BasePaymaster.sol/BasePaymaster.json +281 -0
  11. package/src/artifacts/contracts/core/BasePaymaster.sol/artifacts.d.ts +27 -0
  12. package/src/artifacts/contracts/core/EntryPoint.sol/EntryPoint.json +1019 -0
  13. package/src/artifacts/contracts/core/EntryPoint.sol/artifacts.d.ts +27 -0
  14. package/src/artifacts/contracts/core/EntryPointSimulations.sol/EntryPointSimulations.json +1324 -0
  15. package/src/artifacts/contracts/core/EntryPointSimulations.sol/artifacts.d.ts +27 -0
  16. package/src/artifacts/contracts/core/Groth16Verifier.sol/Groth16Verifier.json +48 -0
  17. package/src/artifacts/contracts/core/Groth16Verifier.sol/artifacts.d.ts +27 -0
  18. package/src/artifacts/contracts/core/Helpers.sol/artifacts.d.ts +0 -0
  19. package/src/artifacts/contracts/core/LinealDeployer.sol/LinealDeployer.json +51 -0
  20. package/src/artifacts/contracts/core/LinealDeployer.sol/artifacts.d.ts +27 -0
  21. package/src/artifacts/contracts/core/NonceManager.sol/NonceManager.json +75 -0
  22. package/src/artifacts/contracts/core/NonceManager.sol/artifacts.d.ts +27 -0
  23. package/src/artifacts/contracts/core/SenderCreator.sol/SenderCreator.json +33 -0
  24. package/src/artifacts/contracts/core/SenderCreator.sol/artifacts.d.ts +27 -0
  25. package/src/artifacts/contracts/core/StakeManager.sol/StakeManager.json +299 -0
  26. package/src/artifacts/contracts/core/StakeManager.sol/artifacts.d.ts +27 -0
  27. package/src/artifacts/contracts/core/UserOperationLib.sol/UserOperationLib.json +53 -0
  28. package/src/artifacts/contracts/core/UserOperationLib.sol/artifacts.d.ts +27 -0
  29. package/src/artifacts/contracts/economy/Liquidity/LinealDex.sol/LinealDex.json +530 -0
  30. package/src/artifacts/contracts/economy/Liquidity/LinealDex.sol/artifacts.d.ts +27 -0
  31. package/src/artifacts/contracts/economy/Liquidity/LinealLiquidity.sol/LinealLiquidity.json +876 -0
  32. package/src/artifacts/contracts/economy/Liquidity/LinealLiquidity.sol/artifacts.d.ts +27 -0
  33. package/src/artifacts/contracts/economy/Liquidity/LinealMilestones.sol/ILinealCitizens.json +46 -0
  34. package/src/artifacts/contracts/economy/Liquidity/LinealMilestones.sol/LinealMilestones.json +986 -0
  35. package/src/artifacts/contracts/economy/Liquidity/LinealMilestones.sol/artifacts.d.ts +43 -0
  36. package/src/artifacts/contracts/economy/Liquidity/LinealSeed.sol/LinealSeed.json +808 -0
  37. package/src/artifacts/contracts/economy/Liquidity/LinealSeed.sol/artifacts.d.ts +27 -0
  38. package/src/artifacts/contracts/economy/accounts/LinealAccount.sol/LinealAccount.json +591 -0
  39. package/src/artifacts/contracts/economy/accounts/LinealAccount.sol/artifacts.d.ts +27 -0
  40. package/src/artifacts/contracts/economy/accounts/LinealAccountFactory.sol/LinealAccountFactory.json +101 -0
  41. package/src/artifacts/contracts/economy/accounts/LinealAccountFactory.sol/artifacts.d.ts +27 -0
  42. package/src/artifacts/contracts/economy/accounts/callback/TokenCallbackHandler.sol/TokenCallbackHandler.json +145 -0
  43. package/src/artifacts/contracts/economy/accounts/callback/TokenCallbackHandler.sol/artifacts.d.ts +27 -0
  44. package/src/artifacts/contracts/economy/banks/LinealBank.sol/IBankDeposit.json +56 -0
  45. package/src/artifacts/contracts/economy/banks/LinealBank.sol/ICitizensAccounts.json +33 -0
  46. package/src/artifacts/contracts/economy/banks/LinealBank.sol/IInstitutionIdentity.json +27 -0
  47. package/src/artifacts/contracts/economy/banks/LinealBank.sol/ILinealTransactions.json +53 -0
  48. package/src/artifacts/contracts/economy/banks/LinealBank.sol/LinealBank.json +1072 -0
  49. package/src/artifacts/contracts/economy/banks/LinealBank.sol/artifacts.d.ts +91 -0
  50. package/src/artifacts/contracts/economy/banks/LinealQantum.sol/LinealQantum.json +496 -0
  51. package/src/artifacts/contracts/economy/banks/LinealQantum.sol/artifacts.d.ts +27 -0
  52. package/src/artifacts/contracts/economy/banks/LinealTransaction.sol/ILinealBank.json +27 -0
  53. package/src/artifacts/contracts/economy/banks/LinealTransaction.sol/LinealTransactions.json +1352 -0
  54. package/src/artifacts/contracts/economy/banks/LinealTransaction.sol/artifacts.d.ts +43 -0
  55. package/src/artifacts/contracts/economy/interfaces/ICLPStablecoin.sol/ICLPStablecoin.json +459 -0
  56. package/src/artifacts/contracts/economy/interfaces/ICLPStablecoin.sol/artifacts.d.ts +27 -0
  57. package/src/artifacts/contracts/economy/interfaces/IDEXRouter.sol/IDEXRouter.json +117 -0
  58. package/src/artifacts/contracts/economy/interfaces/IDEXRouter.sol/artifacts.d.ts +27 -0
  59. package/src/artifacts/contracts/economy/interfaces/IFeeSplitter.sol/IFeeSplitter.json +40 -0
  60. package/src/artifacts/contracts/economy/interfaces/IFeeSplitter.sol/artifacts.d.ts +27 -0
  61. package/src/artifacts/contracts/economy/interfaces/IIncomeToken.sol/IIncomeToken.json +197 -0
  62. package/src/artifacts/contracts/economy/interfaces/IIncomeToken.sol/artifacts.d.ts +27 -0
  63. package/src/artifacts/contracts/economy/interfaces/ILinealIdentity.sol/ILinealIdentity.json +90 -0
  64. package/src/artifacts/contracts/economy/interfaces/ILinealIdentity.sol/artifacts.d.ts +27 -0
  65. package/src/artifacts/contracts/economy/interfaces/IMetricsAdapter.sol/IMetricsAdapter.json +32 -0
  66. package/src/artifacts/contracts/economy/interfaces/IMetricsAdapter.sol/artifacts.d.ts +27 -0
  67. package/src/artifacts/contracts/economy/interfaces/IQorumsToken.sol/IQorumsToken.json +267 -0
  68. package/src/artifacts/contracts/economy/interfaces/IQorumsToken.sol/artifacts.d.ts +27 -0
  69. package/src/artifacts/contracts/economy/paymasters/LinealPaymaster.sol/LinealPaymaster.json +487 -0
  70. package/src/artifacts/contracts/economy/paymasters/LinealPaymaster.sol/artifacts.d.ts +27 -0
  71. package/src/artifacts/contracts/economy/paymasters/LinealRouter.sol/LinealRouter.json +945 -0
  72. package/src/artifacts/contracts/economy/paymasters/LinealRouter.sol/artifacts.d.ts +27 -0
  73. package/src/artifacts/contracts/economy/token/LinealToken.sol/LinealToken.json +1567 -0
  74. package/src/artifacts/contracts/economy/token/LinealToken.sol/artifacts.d.ts +27 -0
  75. package/src/artifacts/contracts/governance/LinealQorum.sol/LinealQorum.json +567 -0
  76. package/src/artifacts/contracts/governance/LinealQorum.sol/artifacts.d.ts +27 -0
  77. package/src/artifacts/contracts/institution/LinealCitizens.sol/LinealCitizens.json +986 -0
  78. package/src/artifacts/contracts/institution/LinealCitizens.sol/artifacts.d.ts +27 -0
  79. package/src/artifacts/contracts/institution/LinealInstitution.sol/LinealInstitution.json +1607 -0
  80. package/src/artifacts/contracts/institution/LinealInstitution.sol/artifacts.d.ts +27 -0
  81. package/src/artifacts/contracts/institution/LinealTender.sol/LinealTender.json +1055 -0
  82. package/src/artifacts/contracts/institution/LinealTender.sol/artifacts.d.ts +27 -0
  83. package/src/artifacts/contracts/interfaces/IAccount.sol/IAccount.json +90 -0
  84. package/src/artifacts/contracts/interfaces/IAccount.sol/artifacts.d.ts +27 -0
  85. package/src/artifacts/contracts/interfaces/IAccountExecute.sol/IAccountExecute.json +79 -0
  86. package/src/artifacts/contracts/interfaces/IAccountExecute.sol/artifacts.d.ts +27 -0
  87. package/src/artifacts/contracts/interfaces/IAggregator.sol/IAggregator.json +211 -0
  88. package/src/artifacts/contracts/interfaces/IAggregator.sol/artifacts.d.ts +27 -0
  89. package/src/artifacts/contracts/interfaces/IEntryPoint.sol/IEntryPoint.json +809 -0
  90. package/src/artifacts/contracts/interfaces/IEntryPoint.sol/artifacts.d.ts +27 -0
  91. package/src/artifacts/contracts/interfaces/IEntryPointSimulations.sol/IEntryPointSimulations.json +1097 -0
  92. package/src/artifacts/contracts/interfaces/IEntryPointSimulations.sol/artifacts.d.ts +27 -0
  93. package/src/artifacts/contracts/interfaces/IMetricsAdapter.sol/IMetricsAdapter.json +32 -0
  94. package/src/artifacts/contracts/interfaces/IMetricsAdapter.sol/artifacts.d.ts +27 -0
  95. package/src/artifacts/contracts/interfaces/INonceManager.sol/INonceManager.json +51 -0
  96. package/src/artifacts/contracts/interfaces/INonceManager.sol/artifacts.d.ts +27 -0
  97. package/src/artifacts/contracts/interfaces/IPaymaster.sol/IPaymaster.json +123 -0
  98. package/src/artifacts/contracts/interfaces/IPaymaster.sol/artifacts.d.ts +27 -0
  99. package/src/artifacts/contracts/interfaces/IQorumsToken.sol/IQorumsToken.json +267 -0
  100. package/src/artifacts/contracts/interfaces/IQorumsToken.sol/artifacts.d.ts +27 -0
  101. package/src/artifacts/contracts/interfaces/IStakeManager.sol/IStakeManager.json +256 -0
  102. package/src/artifacts/contracts/interfaces/IStakeManager.sol/artifacts.d.ts +27 -0
  103. package/src/artifacts/contracts/interfaces/PackedUserOperation.sol/artifacts.d.ts +0 -0
  104. package/src/artifacts/contracts/kernel/LinealEconomy.sol/LinealEconomicKernel.json +743 -0
  105. package/src/artifacts/contracts/kernel/LinealEconomy.sol/artifacts.d.ts +27 -0
  106. package/src/artifacts/contracts/social/LinealStorage.sol/PostBoard.json +1317 -0
  107. package/src/artifacts/contracts/social/LinealStorage.sol/artifacts.d.ts +27 -0
  108. package/src/artifacts/contracts/test.sol/LinealSecureStorage.json +634 -0
  109. package/src/artifacts/contracts/test.sol/artifacts.d.ts +27 -0
  110. package/src/artifacts/contracts/utils/Exec.sol/Exec.json +13 -0
  111. package/src/artifacts/contracts/utils/Exec.sol/artifacts.d.ts +27 -0
  112. package/src/artifacts/contracts/utils/IOracle.sol/IOracle.json +60 -0
  113. package/src/artifacts/contracts/utils/IOracle.sol/artifacts.d.ts +27 -0
  114. package/src/artifacts/contracts/utils/OracleHelper.sol/OracleHelper.json +84 -0
  115. package/src/artifacts/contracts/utils/OracleHelper.sol/artifacts.d.ts +27 -0
  116. package/src/artifacts/contracts/utils/UniswapHelper.sol/UniswapHelper.json +132 -0
  117. package/src/artifacts/contracts/utils/UniswapHelper.sol/artifacts.d.ts +27 -0
  118. package/src/contract-service.js +53 -0
  119. package/src/database/mongodb.js +181 -0
  120. package/src/index.js +11 -0
  121. package/src/middleware/actionMiddleware.js +17 -0
  122. package/src/middleware/actionsMiddleware.js +18 -0
  123. package/src/middleware/authMachineMiddleware.js +34 -0
  124. package/src/middleware/middleware.js +36 -0
  125. package/src/middleware/onlyQorum.js +57 -0
  126. package/src/middleware/onlyServer.js +36 -0
  127. package/src/middleware/readStateMiddleware.js +19 -0
  128. package/src/middleware/unauthorizeMiddleware.js +37 -0
  129. package/src/middleware/userOperation.js +25 -0
  130. package/src/operation-service.js +71 -0
  131. package/src/schemas/abiFolderSchema.js +9 -0
  132. package/src/schemas/abiSchema.js +16 -0
  133. package/src/schemas/applicationSchema.js +32 -0
  134. package/src/schemas/authorizedWalletSchema.js +9 -0
  135. package/src/schemas/deploySchema.js +11 -0
  136. package/src/schemas/expenseSchema.js +17 -0
  137. package/src/schemas/feeSchema.js +17 -0
  138. package/src/schemas/fixedExpenseSchema.js +18 -0
  139. package/src/schemas/fixedFeeSchema.js +17 -0
  140. package/src/schemas/identitySchema.js +33 -0
  141. package/src/schemas/institutionSchema.js +28 -0
  142. package/src/schemas/onlyQorumSchema.js +27 -0
  143. package/src/schemas/onlyServerSchema.js +26 -0
  144. package/src/schemas/serverWalletSchema.js +9 -0
  145. package/src/schemas/subaccountSchema.js +31 -0
  146. package/src/schemas/tenderSchema.js +36 -0
  147. package/src/schemas/transactionSchema.js +29 -0
  148. package/src/schemas/userOperationSchema.js +15 -0
  149. package/src/schemas/valuationSchema.js +10 -0
  150. package/src/signer-client.js +280 -0
  151. package/README.md +0 -3
@@ -0,0 +1,181 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const REQUIRED_SIGNATURES = 3;
4
+ const POOL_SIZE = 1;
5
+ const HASHES_PER_SERVER = 3;
6
+ const TRAIN = ['demos', 'nomos', 'kritos', 'ekklesia'];
7
+
8
+ const REQUIRED_HASHES = REQUIRED_SIGNATURES * HASHES_PER_SERVER;
9
+ const STALE_SIGNING_MS = 4 * 60 * 1000;
10
+
11
+ class Mongodb {
12
+ constructor(uri) {
13
+ this.mongoose = mongoose;
14
+ // Promesa de conexión por separado: getDatabase() debe devolver la instancia, no la promesa
15
+ this.ready = mongoose.connect(uri).catch(err => {
16
+ console.error('[mongodb] error de conexión:', err?.message || err);
17
+ throw err;
18
+ });
19
+
20
+ if (this.ready) {
21
+ console.log("Database connected");
22
+ }
23
+ }
24
+
25
+ getDatabase() {
26
+ return this.mongoose;
27
+ }
28
+
29
+ // mongoose.model(name, schema) lanza OverwriteModelError si se llama dos veces con el mismo nombre
30
+ getModel(name, schema) {
31
+ return this.mongoose.models[name] || this.mongoose.model(name, schema);
32
+ }
33
+
34
+ walletOf(remoteUser) {
35
+ return String(remoteUser?.smartAccountAddress || '').toLowerCase();
36
+ }
37
+
38
+ isBusy(doc) {
39
+ const staleLimit = Date.now() - STALE_SIGNING_MS;
40
+ return (doc.steps || []).some(s =>
41
+ s.status === 'signing' && s.claimedAt && new Date(s.claimedAt).getTime() > staleLimit);
42
+ }
43
+
44
+ signedCount(doc) {
45
+ return (doc.steps || []).filter(s => s.status === 'signed').length;
46
+ }
47
+
48
+ // Elige el siguiente pool: continúa después del último servidor intentado (por claimedAt),
49
+ // salta los ya firmados y, si llegó al final de TRAIN, vuelve al primero.
50
+ nextPool(doc) {
51
+ if (this.isBusy(doc)) return [];
52
+
53
+ let lastIdx = -1;
54
+ let lastTs = 0;
55
+ TRAIN.forEach((server, i) => {
56
+ const step = (doc.steps || []).find(s => s.server === server);
57
+ const t = step?.claimedAt ? new Date(step.claimedAt).getTime() : 0;
58
+ if (t > lastTs) { lastTs = t; lastIdx = i; }
59
+ });
60
+
61
+ const rotated = [...TRAIN.slice(lastIdx + 1), ...TRAIN.slice(0, lastIdx + 1)];
62
+ const pending = rotated.filter(server => {
63
+ const step = (doc.steps || []).find(s => s.server === server);
64
+ return step && step.status !== 'signed';
65
+ });
66
+
67
+ // No pedir más servidores de los que faltan para llegar a REQUIRED_SIGNATURES
68
+ const needed = Math.max(REQUIRED_SIGNATURES - this.signedCount(doc), 0);
69
+ return pending.slice(0, Math.min(POOL_SIZE, needed));
70
+ }
71
+
72
+ async signWithServer(remoteUser, result, Model, docId, server) {
73
+ const wallet = this.walletOf(remoteUser);
74
+ if (!wallet) {
75
+ console.error('[signWithServer] remoteUser sin smartAccountAddress');
76
+ return false;
77
+ }
78
+
79
+ // 1) Reclamar el paso de forma atómica (waiting / failed / signing vencido)
80
+ const staleBefore = new Date(Date.now() - STALE_SIGNING_MS);
81
+ const claimed = await Model.findOneAndUpdate(
82
+ {
83
+ _id: docId,
84
+ steps: {
85
+ $elemMatch: {
86
+ server,
87
+ $or: [
88
+ { status: { $in: ['waiting', 'failed'] } },
89
+ { status: 'signing', claimedAt: { $lte: staleBefore } },
90
+ { status: 'signing', claimedAt: { $exists: false } },
91
+ ],
92
+ },
93
+ },
94
+ },
95
+ {
96
+ $set: {
97
+ 'steps.$[s].status': 'signing',
98
+ 'steps.$[s].error': null,
99
+ 'steps.$[s].claimedAt': new Date(),
100
+ },
101
+ },
102
+ { new: true, arrayFilters: [{ 's.server': server }] },
103
+ );
104
+ if (!claimed) return false;
105
+
106
+ try {
107
+ const hashes = this.extractHashes(result.receipt);
108
+ if (hashes.length !== HASHES_PER_SERVER) {
109
+ throw new Error(`${server}: se esperaban ${HASHES_PER_SERVER} hashes y llegaron ${hashes.length}`);
110
+ }
111
+
112
+ // 2) Marcar como firmado y guardar quién firmó (solo si el paso sigue en 'signing')
113
+ const now = new Date();
114
+ const res = await Model.updateOne(
115
+ { _id: docId, steps: { $elemMatch: { server, status: 'signing' } } },
116
+ {
117
+ $set: {
118
+ 'steps.$[s].status': 'signed',
119
+ 'steps.$[s].receipt': hashes,
120
+ 'steps.$[s].error': null,
121
+ 'steps.$[s].signedAt': now,
122
+ },
123
+ $inc: { signCount: 1 },
124
+ $addToSet: { 'steps.$[s].users': wallet },
125
+ $push: { signatures: { wallet, receipt: hashes, signedAt: now } },
126
+ },
127
+ { arrayFilters: [{ 's.server': server, 's.status': 'signing' }] },
128
+ );
129
+ if (res.modifiedCount === 0) return false;
130
+
131
+ // 3) Cerrar el documento cuando se alcanzan las firmas requeridas
132
+ const fresh = await Model.findById(docId);
133
+ if (fresh && fresh.status === 'pending' && this.signedCount(fresh) >= REQUIRED_SIGNATURES) {
134
+ await Model.updateOne({ _id: docId, status: 'pending' }, { $set: { status: 'completed' } });
135
+ }
136
+ return true;
137
+ } catch (err) {
138
+ const error = err?.message || String(err);
139
+ console.error(`[signWithServer] ${server} falló:`, error);
140
+ await Model.updateOne(
141
+ { _id: docId },
142
+ { $set: { 'steps.$[s].status': 'failed', 'steps.$[s].error': error } },
143
+ { arrayFilters: [{ 's.server': server }] },
144
+ );
145
+ return false;
146
+ }
147
+ }
148
+
149
+ async runTrain(remoteUser, Model, docId, result) {
150
+ const doc = await Model.findById(docId);
151
+ if (!doc || doc.status !== 'pending' || this.totalHashes(doc) >= REQUIRED_HASHES) return;
152
+
153
+ let pool;
154
+ if (result.server && TRAIN.includes(result.server)) {
155
+ const step = (doc.steps || []).find(s => s.server === result.server);
156
+ pool = step && step.status !== 'signed' && !this.isBusy(doc) ? [result.server] : [];
157
+ } else {
158
+ pool = this.nextPool(doc);
159
+ }
160
+ if (pool.length > 0) {
161
+ await Promise.all(pool.map(server => this.signWithServer(remoteUser, result, Model, docId, server)));
162
+ }
163
+ }
164
+
165
+ extractHashes(receipt) {
166
+ const list = Array.isArray(receipt)
167
+ ? receipt
168
+ : (receipt?.hashes || receipt?.transactionHashes || receipt?.receipt || []);
169
+ return Array.isArray(list) ? list.filter(h => typeof h === 'string' && h.length > 0) : [];
170
+ }
171
+
172
+ totalHashes(doc) {
173
+ return (doc.steps || [])
174
+ .filter(s => s.status === 'signed')
175
+ .reduce((acc, s) => acc + this.extractHashes(s.receipt).length, 0);
176
+ }
177
+ }
178
+
179
+ const mongodbInstance = new Mongodb(process.env.MONGODB_URI);
180
+
181
+ module.exports = { Mongodb, mongodbInstance };
package/src/index.js ADDED
@@ -0,0 +1,11 @@
1
+ const { Operation } = require("./operation-service");
2
+ const { Signer } = require("./signer-client");
3
+ const { Contract } = require("./contract-service");
4
+ const ArtifactService = require("./artifact-service");
5
+
6
+ module.exports = {
7
+ Operation,
8
+ Signer,
9
+ Contract,
10
+ ArtifactService,
11
+ };
@@ -0,0 +1,17 @@
1
+ const {Signer} = require("../signer-client");
2
+ const {mongodbInstance} = require("../database/mongodb");
3
+ const {onlyQorumSchema} = require("../schemas/onlyQorumSchema");
4
+
5
+ const actionMiddleware = async (req, res, next) => {
6
+ const authHeader = req.headers['authorization'];
7
+ const { contractName, id } = req.params;
8
+ const signer = new Signer();
9
+ const mongoose = mongodbInstance.getDatabase();
10
+ const model = mongoose.model(contractName, onlyQorumSchema);
11
+ const doc = await model.findById(id);
12
+ req.wallet = await signer.getUserWallet(authHeader);
13
+ req.doc = doc;
14
+ next();
15
+ };
16
+
17
+ module.exports = { actionMiddleware };
@@ -0,0 +1,18 @@
1
+ const {Signer} = require("../signer-client");
2
+ const {mongodbInstance} = require("../database/mongodb");
3
+ const {onlyQorumSchema} = require("../schemas/onlyQorumSchema");
4
+
5
+ const actionsMiddleware = async (req, res, next) => {
6
+ const authHeader = req.headers['authorization'];
7
+ const { contractName, contractAddress } = req.params;
8
+ const signer = new Signer();
9
+ const mongoose = mongodbInstance.getDatabase();
10
+ const model = mongoose.model(contractName, onlyQorumSchema);
11
+ const doc = await model.findOne({ contractAddress });
12
+ const TRAIN = ['demos', 'nomos', 'kritos', 'ekklesia'];
13
+ req.wallet = await signer.getDevUserWallet(authHeader);
14
+ req.doc = doc;
15
+ next();
16
+ };
17
+
18
+ module.exports = { actionsMiddleware };
@@ -0,0 +1,34 @@
1
+ const {Signer} = require("../signer-client");
2
+ const {AuthorizedServer} = require("../schemas/serverWalletSchema");
3
+
4
+ const get = async (model, address) => {
5
+ const addr = address?.toLowerCase();
6
+ return await model.findOne({address: addr});
7
+ };
8
+
9
+ const authMachineMiddleware = async (req, res, next) => {
10
+ try {
11
+ const signer = new Signer();
12
+ const authHeader = req.headers['authorization'];
13
+ console.log(authHeader);
14
+ const remoteUser = await signer.getDevUserWallet(authHeader);
15
+ console.log(remoteUser);
16
+ if (!remoteUser?.res.smartAccountAddress) {
17
+ return res.status(401).json({error: 'No se pudo identificar la máquina.'});
18
+ }
19
+
20
+ const doc = await get(AuthorizedServer, remoteUser.res.smartAccountAddress);
21
+ if (!doc?.authorized) {
22
+ return res.status(403).json({error: 'Servidor no autorizado'});
23
+ }
24
+
25
+ req.address = remoteUser.res.smartAccountAddress;
26
+ req.doc = doc;
27
+ next();
28
+ } catch (err) {
29
+ console.error('[authMachineMiddleware]', err?.message || err);
30
+ return res.status(500).json({error: 'Error de autenticación de la máquina'});
31
+ }
32
+ };
33
+
34
+ module.exports = {authMachineMiddleware};
@@ -0,0 +1,36 @@
1
+ const {Signer} = require("../signer-client");
2
+ const {AuthorizedServer} = require("../schemas/serverWalletSchema");
3
+
4
+ const authMiddleware = async (req, res, next) => {
5
+ const authHeader = req.headers['authorization'];
6
+ console.log(req.headers);
7
+ const signer = new Signer();
8
+ if (!authHeader) {
9
+ return res.status(401).json({ error: 'Acceso denegado. Token no proporcionado.' });
10
+ }
11
+ const remoteUser = await signer.getDevUserWallet(authHeader);
12
+
13
+ if (!remoteUser) {
14
+ return res.status(401).json({ error: 'Token inválido o expirado.' });
15
+ }
16
+ const address = remoteUser.res.smartAccountAddress;
17
+
18
+ console.log(address);
19
+
20
+ const doc = await AuthorizedServer.findOneAndUpdate(
21
+ { address: address.toLowerCase() },
22
+ { $setOnInsert: { address: address.toLowerCase(), authorized: true } },
23
+ { upsert: true, new: true }
24
+ );
25
+
26
+ console.log(doc);
27
+
28
+ if (!doc || !doc.authorized) {
29
+ return res.status(402).json({ error: 'Usuario no autorizado' });
30
+ }
31
+
32
+ req.address = address;
33
+ next();
34
+ };
35
+
36
+ module.exports = { authMiddleware };
@@ -0,0 +1,57 @@
1
+ const {Operation} = require("../operation-service");
2
+ const {Signer} = require("../signer-client");
3
+ const {mongodbInstance} = require("../database/mongodb");
4
+ const {onlyQorumSchema} = require("../schemas/onlyQorumSchema");
5
+
6
+ const TRAIN = ['demos', 'nomos', 'kritos', 'ekklesia'];
7
+ const INSTITUION_TRAIN = ['demos', 'nomos', 'kritos', 'ekklesia'];
8
+
9
+ const onlyQorum = async (req, res, next) => {
10
+ try {
11
+ const authHeader = req.headers['q-user-token'];
12
+ const {contractName, contractAddress, functionName, args, servers} = req.body;
13
+
14
+ if (!authHeader) {
15
+ return res.status(401).json({error: 'Token no proporcionado.'});
16
+ }
17
+ if (!Array.isArray(args)) {
18
+ return res.status(400).json({error: 'args debe ser un arreglo'});
19
+ }
20
+ // contractName se usa como nombre de colección: no aceptar cualquier cosa del cliente
21
+ if (typeof contractName !== 'string' || !/^[A-Za-z0-9_]{1,64}$/.test(contractName)) {
22
+ return res.status(400).json({error: 'contractName inválido'});
23
+ }
24
+
25
+ const signer = new Signer();
26
+ const remoteUser = await signer.getDevUserWallet(authHeader);
27
+ if (!remoteUser) {
28
+ return res.status(401).json({error: 'Token inválido o expirado.'});
29
+ }
30
+
31
+ const model = mongodbInstance.getModel(contractName, onlyQorumSchema);
32
+
33
+ // Crea el documento con sus 4 pasos en 'waiting' la primera vez; si ya existe, lo devuelve intacto
34
+ const doc = await model.findOneAndUpdate(
35
+ {contractAddress, functionName, args},
36
+ {$setOnInsert: {contractName, steps: TRAIN.map(server => ({server}))}},
37
+ {upsert: true, new: true}
38
+ );
39
+
40
+ const operationService = new Operation();
41
+ const result = await operationService.sendQorumOperation(
42
+ servers, authHeader, contractName, contractAddress, functionName, args
43
+ );
44
+
45
+ await mongodbInstance.runTrain(remoteUser, model, doc._id, result);
46
+
47
+ req.wallet = remoteUser;
48
+ req.server = result.servers;
49
+ req.result = result;
50
+ next();
51
+ } catch (err) {
52
+ console.error('[onlyQorum]', err?.message || err);
53
+ return res.status(500).json({error: 'Error procesando la operación'});
54
+ }
55
+ };
56
+
57
+ module.exports = {onlyQorum};
@@ -0,0 +1,36 @@
1
+ const {Operation} = require('../operation-service');
2
+ const {Signer} = require("../signer-client");
3
+ const {mongodbInstance} = require("../database/mongodb");
4
+ const {onlyServerSchema} = require("../schemas/onlyServerSchema");
5
+
6
+ const onlyServers = async (req, res, next) => {
7
+ const authHeader = req.headers['q-user-token'] || req.headers['q-institution-token'];
8
+ const operationService = new Operation();
9
+ const { contractName, contractAddress, functionName, args } = req.body;
10
+ const signer = new Signer();
11
+ const mongoose = mongodbInstance.getDatabase();
12
+ if (!Array.isArray(args)) {
13
+ return res.status(400).json({ error: 'args debe ser un arreglo' });
14
+ }
15
+ const remoteUser = await signer.getDevUserWallet(authHeader);
16
+
17
+ if (!remoteUser) {
18
+ return res.status(401).json({ error: 'Token inválido o expirado.' });
19
+ }
20
+ const model = mongoose.model(contractName, onlyServerSchema);
21
+ // crear o actualizar el documento en la base de datos
22
+ const doc = await model.findOneAndUpdate(
23
+ { contractAddress, functionName, args },
24
+ { $set: args },
25
+ { upsert: true, new: true }
26
+ );
27
+ const servers = ['3000', '3001', '3002', '3003'];
28
+
29
+ const result = await operationService.sendServerOperation(servers, authHeader, contractName, contractAddress, functionName, args);
30
+ await mongodbInstance.runTrain(model, doc._id, result.servers);
31
+ req.wallet = remoteUser;
32
+ req.server = result.servers;
33
+ req.result = result;
34
+ next();
35
+ };
36
+ module.exports = { onlyServers };
@@ -0,0 +1,19 @@
1
+ const {Signer} = require("../signer-client");
2
+ const {Contract} = require("../contract-service");
3
+
4
+ const readStateMiddleware = async (req, res, next) => {
5
+ const authHeader = req.headers['q-user-token'];
6
+ if (!authHeader) {
7
+ return res.status(401).json({ error: 'Acceso denegado. Token no proporcionado.' });
8
+ }
9
+ const signer = new Signer();
10
+ const { contractName, contractAddress, functionName, args} = req.body;
11
+ const contract = new Contract();
12
+ const receipt = await contract.readState(contractName, contractAddress, functionName, args);
13
+ const TRAIN = ['demos', 'nomos', 'kritos', 'ekklesia'];
14
+ req.wallet = await signer.getDevUserWallet(authHeader);
15
+ req.doc = receipt;
16
+ next();
17
+ };
18
+
19
+ module.exports = { readStateMiddleware };
@@ -0,0 +1,37 @@
1
+ const {Signer} = require("../signer-client");
2
+ const {AuthorizedServer} = require("../schemas/serverWalletSchema");
3
+ const {AuthorizedWallet} = require("../schemas/authorizedWalletSchema");
4
+
5
+ const unauthorizedMiddleware = async (req, res, next) => {
6
+ const token = req.headers['q-server-token'];
7
+ if (!token) {
8
+ return res.status(401).json({ error: 'Acceso denegado. Token no proporcionado.' });
9
+ }
10
+
11
+ const signer = new Signer();
12
+ const TRAIN = ['demos', 'nomos', 'kritos', 'ekklesia'];
13
+ const remoteUser = await signer.getUserWallet(TRAIN, token);
14
+ if (!remoteUser) {
15
+ return res.status(401).json({ error: 'Token inválido o expirado.' });
16
+ }
17
+
18
+ const wallet = req.params.wallet.toLowerCase();
19
+
20
+ // Ajusta esto a la forma real de remoteUser
21
+ // if (remoteUser.wallet?.toLowerCase() !== wallet) {
22
+ // return res.status(403).json({ error: 'La wallet no coincide con el token.' });
23
+ // }
24
+
25
+ const [server, walletDoc] = await Promise.all([
26
+ AuthorizedServer.findOne({ address: wallet }),
27
+ AuthorizedWallet.findOne({ address: wallet }),
28
+ ]);
29
+
30
+ if (!server?.authorized || !walletDoc?.authorized) {
31
+ return res.status(403).json({ error: 'Usuario no autorizado' });
32
+ }
33
+
34
+ req.user = remoteUser;
35
+ next();
36
+ };
37
+ module.exports = { unauthorizedMiddleware };
@@ -0,0 +1,25 @@
1
+ const {Operation} = require('../operation-service');
2
+ const {Signer} = require("../signer-client");
3
+ const {AuthorizedWallet} = require("../schemas/authorizedWalletSchema");
4
+ const TRAIN = ['demos', 'nomos', 'kritos', 'ekklesia'];
5
+
6
+ const userOperation = async (req, res, next) => {
7
+ const authHeader = req.headers['q-user-token'];
8
+ const operationService = new Operation();
9
+ const { contractName, contractAddress, functionName, args } = req.body;
10
+ const signer = new Signer();
11
+ const wallet = await signer.getUserWallet(authHeader);
12
+ const doc = await AuthorizedWallet.findOneAndUpdate(
13
+ { wallet: wallet.smartAccountAddress },
14
+ { upsert: true, new: true }
15
+ );
16
+
17
+ if (!doc.authorized) {
18
+ return res.status(402).json({ error: 'Usuario no autorizado' });
19
+ }
20
+
21
+ req.wallet = wallet.smartAccountAddress;
22
+ req.result = await operationService.sendUserOperation(TRAIN, authHeader, contractName, contractAddress, functionName, args);
23
+ next();
24
+ };
25
+ module.exports = { userOperation };
@@ -0,0 +1,71 @@
1
+ const { Signer } = require("./signer-client");
2
+ const ArtifactService = require("./artifact-service");
3
+ const { createPublicClient, http, parseAbi, parseEventLogs } = require('viem');
4
+
5
+ class Operation {
6
+
7
+ constructor() {
8
+ this.signerClient = new Signer();
9
+ this.artifactService = new ArtifactService();
10
+ this.publicClient = createPublicClient({ transport: http('https://sepolia.base.org') });
11
+ }
12
+
13
+ async sendUserOperation(servers, userKey, contractName, contractAddress, functionName, args) {
14
+ const body = {
15
+ contractName,
16
+ contractAddress,
17
+ functionName,
18
+ args
19
+ };
20
+ return await this.signerClient.initPoolRequest(servers, "POST", "operation/send-transaction", body, userKey);
21
+ }
22
+
23
+ async sendServerOperation(servers, userKey, contractName, contractAddress, functionName, args) {
24
+ const body = {
25
+ contractName,
26
+ contractAddress,
27
+ functionName,
28
+ args
29
+ };
30
+ return await this.signerClient.initDevPoolRequest(servers, "POST", "operation/only-servers", body);
31
+ }
32
+
33
+ async sendQorumOperation(server, userKey, contractName, contractAddress, functionName, args) {
34
+ const body = {
35
+ contractName,
36
+ contractAddress,
37
+ functionName,
38
+ args
39
+ };
40
+ return await this.signerClient.initPoolRequest(server,"POST", "operation/send-operation", body, userKey);
41
+ }
42
+
43
+
44
+ async readState(contractName, contractAddress, functionName, args = []) {
45
+ const artifact = this.artifactService.getArtifactByName(contractName);
46
+ const state = await this.publicClient.readContract({
47
+ address: contractAddress,
48
+ abi: artifact.abi,
49
+ functionName,
50
+ args
51
+ });
52
+
53
+ return this.serializeBigInt(state);
54
+ }
55
+ serializeBigInt(value) {
56
+ if (typeof value === 'bigint') {
57
+ return value.toString();
58
+ }
59
+ if (Array.isArray(value)) {
60
+ return value.map((v) => this.serializeBigInt(v));
61
+ }
62
+ if (value !== null && typeof value === 'object') {
63
+ return Object.fromEntries(
64
+ Object.entries(value).map(([k, v]) => [k, this.serializeBigInt(v)]),
65
+ );
66
+ }
67
+ return value;
68
+ }
69
+ }
70
+
71
+ module.exports = { Operation };
@@ -0,0 +1,9 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ // Carpeta lógica para organizar ABIs (se crea on-demand)
4
+ const abiFolderSchema = new mongoose.Schema({
5
+ name: { type: String, required: true, unique: true, trim: true },
6
+ createdBy: { type: String, default: null },
7
+ }, { timestamps: true });
8
+
9
+ module.exports = mongoose.model('AbiFolder', abiFolderSchema);
@@ -0,0 +1,16 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ // Archivo ABI almacenado, identificado por nombre dentro de una carpeta.
4
+ const abiSchema = new mongoose.Schema({
5
+ folder: { type: String, required: true, trim: true, index: true },
6
+ name: { type: String, required: true, trim: true }, // nombre del archivo (con o sin .json)
7
+ contentType: { type: String, default: 'application/json' },
8
+ size: { type: Number, default: 0 },
9
+ abi: { type: mongoose.Schema.Types.Mixed, required: true }, // contenido JSON del ABI
10
+ uploadedBy: { type: String, default: null },
11
+ }, { timestamps: true });
12
+
13
+ // Un mismo nombre de archivo no puede repetirse dentro de la misma carpeta.
14
+ abiSchema.index({ folder: 1, name: 1 }, { unique: true });
15
+
16
+ module.exports = mongoose.model('Abi', abiSchema);
@@ -0,0 +1,32 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const applicationSchema = new mongoose.Schema({
4
+ tenderId: { type: mongoose.Schema.Types.ObjectId, ref: 'Tender', required: true },
5
+ applicantWallet: { type: String, required: true },
6
+ title: { type: String, required: true },
7
+ description: { type: String, required: true },
8
+ documentURL: { type: String, default: null },
9
+ videoURL: { type: String, default: null },
10
+ status: { type: String, enum: ['Pendiente', 'Aprobada', 'Rechazada'], default: 'Pendiente' },
11
+ createdAt: { type: Date, default: Date.now },
12
+ receipt: { type: {} },
13
+ body: { type: Object },
14
+ signCount: { type: Number, default: 0 },
15
+ required: { type: Number, default: 3 },
16
+ steps: [{
17
+ server: String,
18
+ status: { type: String, enum: ['waiting', 'signing', 'signed', 'failed'], default: 'waiting' },
19
+ receipt: Object,
20
+ error: String,
21
+ signedAt: Date,
22
+ claimedAt: Date,
23
+ _id: false,
24
+ }],
25
+ signatures: [{
26
+ wallet: String,
27
+ receipt: Object,
28
+ signedAt: { type: Date, default: Date.now },
29
+ }],
30
+ });
31
+
32
+ module.exports = mongoose.model('Application', applicationSchema);
@@ -0,0 +1,9 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const authorizedWalletSchema = new mongoose.Schema({
4
+ address: { type: String, required: true },
5
+ authorized: { type: Boolean, default: true },
6
+ });
7
+
8
+ const AuthorizedWallet = mongoose.model('AuthorizedWallet', authorizedWalletSchema);
9
+ module.exports = { authorizedWalletSchema, AuthorizedWallet };
@@ -0,0 +1,11 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ // Honorario pagado por una institución a una persona o cargo.
4
+ const deploySchema = new mongoose.Schema({
5
+ contractName: { type: String, default: null },
6
+ args: { type: [], default: null },
7
+ contractAddress: { type: String, required: true, unique: true }, // contrato propio del registro (off-chain)
8
+ institutionContract: { type: String, required: true, index: true },
9
+ }, { timestamps: true });
10
+
11
+ module.exports = { deploySchema };
@@ -0,0 +1,17 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ // Gasto variable de una institución (registro puntual, no recurrente).
4
+ const expenseSchema = new mongoose.Schema({
5
+ wallet: { type: String, default: null },
6
+ userId: { type: String, default: null },
7
+ contractAddress: { type: String, required: true, unique: true }, // contrato propio del registro (off-chain)
8
+ institutionAddress: { type: String, required: true, index: true }, // institución a la que pertenece
9
+ concepto: { type: String, required: true },
10
+ categoria: { type: String, default: 'General' },
11
+ responsable: { type: String, default: 'Tesorería' },
12
+ monto: { type: Number, required: true, min: 0 },
13
+ fecha: { type: String, default: null }, // YYYY-MM-DD
14
+ estado: { type: String, enum: ['Pagado', 'Pendiente', 'En revisión'], default: 'Pendiente' },
15
+ }, { timestamps: true });
16
+
17
+ module.exports = mongoose.model('Expense', expenseSchema);