@pushchain/core 6.0.27-alpha.3 → 6.0.27-alpha.5

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 (90) hide show
  1. package/AGW.md +35 -6
  2. package/CHANGELOG.md +13 -0
  3. package/MARKETPLACE.md +206 -0
  4. package/package.json +2 -1
  5. package/src/lib/agentic/codec/rules.js +74 -69
  6. package/src/lib/agentic/codec/universal.js +15 -3
  7. package/src/lib/agentic/constants.d.ts +36 -1
  8. package/src/lib/agentic/constants.js +14 -1
  9. package/src/lib/agentic/contracts/reader.d.ts +21 -0
  10. package/src/lib/agentic/contracts/reader.js +3 -0
  11. package/src/lib/agentic/error-messages.d.ts +3 -0
  12. package/src/lib/agentic/error-messages.js +127 -0
  13. package/src/lib/agentic/errors.d.ts +12 -3
  14. package/src/lib/agentic/errors.js +76 -0
  15. package/src/lib/agentic/management/common.js +6 -0
  16. package/src/lib/agentic/management/destination.d.ts +5 -0
  17. package/src/lib/agentic/management/destination.js +32 -0
  18. package/src/lib/agentic/management/prepare.js +80 -55
  19. package/src/lib/agentic/management/svm-public.js +13 -4
  20. package/src/lib/agentic/presets/index.js +8 -9
  21. package/src/lib/agentic/presets/routes.d.ts +1 -1
  22. package/src/lib/agentic/presets/routes.js +6 -7
  23. package/src/lib/agentic/presets/types.d.ts +1 -6
  24. package/src/lib/agentic/public-rule.js +18 -2
  25. package/src/lib/constants/index.d.ts +35 -0
  26. package/src/lib/index.d.ts +4 -0
  27. package/src/lib/index.js +6 -2
  28. package/src/lib/job/job.d.ts +35 -0
  29. package/src/lib/job/job.js +382 -0
  30. package/src/lib/job/types.d.ts +94 -0
  31. package/src/lib/job/types.js +3 -0
  32. package/src/lib/job/watch.d.ts +3 -0
  33. package/src/lib/job/watch.js +169 -0
  34. package/src/lib/job-spec/codec.d.ts +18 -0
  35. package/src/lib/job-spec/codec.js +348 -0
  36. package/src/lib/job-spec/constants.d.ts +32 -0
  37. package/src/lib/job-spec/constants.js +36 -0
  38. package/src/lib/job-spec/helpers.d.ts +19 -0
  39. package/src/lib/job-spec/helpers.js +138 -0
  40. package/src/lib/job-spec/index.d.ts +14 -0
  41. package/src/lib/job-spec/index.js +17 -0
  42. package/src/lib/job-spec/preview.d.ts +8 -0
  43. package/src/lib/job-spec/preview.js +298 -0
  44. package/src/lib/job-spec/read.d.ts +20 -0
  45. package/src/lib/job-spec/read.js +224 -0
  46. package/src/lib/job-spec/schema.d.ts +290 -0
  47. package/src/lib/job-spec/schema.js +70 -0
  48. package/src/lib/job-spec/types.d.ts +139 -0
  49. package/src/lib/job-spec/types.js +3 -0
  50. package/src/lib/market/contracts/AgenticCommerce.d.ts +1026 -0
  51. package/src/lib/market/contracts/AgenticCommerce.js +1317 -0
  52. package/src/lib/market/contracts/RulesBindingHook.d.ts +235 -0
  53. package/src/lib/market/contracts/RulesBindingHook.js +314 -0
  54. package/src/lib/market/contracts/UniversalMarketplace.d.ts +1770 -0
  55. package/src/lib/market/contracts/UniversalMarketplace.js +2295 -0
  56. package/src/lib/market/contracts/UniversalMarketplaceErrors.d.ts +309 -0
  57. package/src/lib/market/contracts/UniversalMarketplaceErrors.js +416 -0
  58. package/src/lib/market/contracts/UniversalMarketplaceRules.d.ts +241 -0
  59. package/src/lib/market/contracts/UniversalMarketplaceRules.js +323 -0
  60. package/src/lib/market/data.d.ts +8 -0
  61. package/src/lib/market/data.js +60 -0
  62. package/src/lib/market/deployment.d.ts +14 -0
  63. package/src/lib/market/deployment.js +23 -0
  64. package/src/lib/market/deposit.d.ts +24 -0
  65. package/src/lib/market/deposit.js +271 -0
  66. package/src/lib/market/errors.d.ts +13 -0
  67. package/src/lib/market/errors.js +81 -0
  68. package/src/lib/market/history.d.ts +6 -0
  69. package/src/lib/market/history.js +83 -0
  70. package/src/lib/market/index.d.ts +4 -0
  71. package/src/lib/market/index.js +12 -0
  72. package/src/lib/market/kernel-wire.d.ts +15 -0
  73. package/src/lib/market/kernel-wire.js +41 -0
  74. package/src/lib/market/market.d.ts +55 -0
  75. package/src/lib/market/market.js +635 -0
  76. package/src/lib/market/rules.d.ts +106 -0
  77. package/src/lib/market/rules.js +293 -0
  78. package/src/lib/market/runtime.d.ts +35 -0
  79. package/src/lib/market/runtime.js +130 -0
  80. package/src/lib/market/types.d.ts +180 -0
  81. package/src/lib/market/types.js +3 -0
  82. package/src/lib/orchestrator/internals/errors.d.ts +9 -2
  83. package/src/lib/orchestrator/internals/errors.js +9 -2
  84. package/src/lib/orchestrator/internals/push-chain-tx.js +17 -3
  85. package/src/lib/push-chain/push-chain.d.ts +44 -1
  86. package/src/lib/push-chain/push-chain.js +23 -3
  87. package/src/lib/read-state/read-params.d.ts +9 -0
  88. package/src/lib/read-state/read-params.js +5 -1
  89. package/src/lib/utils.d.ts +15 -0
  90. package/src/lib/utils.js +4 -0
@@ -0,0 +1,106 @@
1
+ import { type Address, type Hex } from 'viem';
2
+ import type { MoveableToken } from '../constants/tokens';
3
+ import { PUSH_NETWORK } from '../constants/enums';
4
+ import { type AssetCapWire, type AllowedCallWire, type UniversalTermsWire } from '../agentic/codec/universal-terms';
5
+ import type { ArgumentPath, WalletMarker } from '../agentic/agentic.types';
6
+ import type { PrincipalMarker } from '../job-spec/types';
7
+ export type MarketAssetToken = MoveableToken | string | {
8
+ prc20: Address;
9
+ };
10
+ export type MarketPin = {
11
+ arg: ArgumentPath;
12
+ expected: Hex | Address | bigint | boolean | WalletMarker | PrincipalMarker;
13
+ max?: never;
14
+ } | {
15
+ arg: ArgumentPath;
16
+ max: bigint | PrincipalMarker;
17
+ expected?: never;
18
+ };
19
+ export interface AgentCardRules {
20
+ assets: {
21
+ token: MarketAssetToken;
22
+ maxPerCall: bigint | PrincipalMarker;
23
+ maxTotal?: bigint | PrincipalMarker;
24
+ }[];
25
+ principalAsset: number;
26
+ maxGasPerCall: bigint;
27
+ allowedCalls: {
28
+ target: Address;
29
+ selector: string;
30
+ pins?: MarketPin[];
31
+ maxValue?: bigint;
32
+ }[];
33
+ }
34
+ export interface CardRulesWire {
35
+ assets: readonly AssetCapWire[];
36
+ principalAsset: number;
37
+ maxGasPerCall: bigint;
38
+ allowedCalls: readonly AllowedCallWire[];
39
+ }
40
+ export declare const MARKER_WALLET: `0x${string}`;
41
+ export declare const MARKER_PRINCIPAL: `0x${string}`;
42
+ export declare const CARD_RULES_PARAM: {
43
+ readonly type: "tuple";
44
+ readonly components: readonly [{
45
+ readonly name: "assets";
46
+ readonly type: "tuple[]";
47
+ readonly components: readonly [{
48
+ readonly name: "token";
49
+ readonly type: "address";
50
+ }, {
51
+ readonly name: "maxPerCall";
52
+ readonly type: "uint256";
53
+ }, {
54
+ readonly name: "maxTotal";
55
+ readonly type: "uint256";
56
+ }];
57
+ }, {
58
+ readonly name: "principalAsset";
59
+ readonly type: "uint8";
60
+ }, {
61
+ readonly name: "maxGasPerCall";
62
+ readonly type: "uint256";
63
+ }, {
64
+ readonly name: "allowedCalls";
65
+ readonly type: "tuple[]";
66
+ readonly components: readonly [{
67
+ readonly name: "target";
68
+ readonly type: "address";
69
+ }, {
70
+ readonly name: "selector";
71
+ readonly type: "bytes4";
72
+ }, {
73
+ readonly name: "beneficiaryOffset";
74
+ readonly type: "uint16";
75
+ }, {
76
+ readonly name: "hasBeneficiary";
77
+ readonly type: "bool";
78
+ }, {
79
+ readonly name: "maxValue";
80
+ readonly type: "uint256";
81
+ }, {
82
+ readonly name: "pins";
83
+ readonly type: "tuple[]";
84
+ readonly components: readonly [{
85
+ readonly name: "offset";
86
+ readonly type: "uint16";
87
+ }, {
88
+ readonly name: "op";
89
+ readonly type: "uint8";
90
+ }, {
91
+ readonly name: "value";
92
+ readonly type: "bytes32";
93
+ }];
94
+ }];
95
+ }];
96
+ };
97
+ export declare function validateAgentCardRules(rules: AgentCardRules): void;
98
+ export declare function encodeAgentCardRules(rules: AgentCardRules, options: {
99
+ chain: string;
100
+ network?: PUSH_NETWORK;
101
+ }): Hex;
102
+ export declare function decodeCardRulesWire(bytes: Hex): CardRulesWire;
103
+ export declare function decodeAgentCardRules(bytes: Hex, _options?: {
104
+ chain?: string;
105
+ }): AgentCardRules;
106
+ export declare function fillCardRules(r: CardRulesWire, principal: bigint, wallet: Address, expiredAt: number): UniversalTermsWire;
@@ -0,0 +1,293 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CARD_RULES_PARAM = exports.MARKER_PRINCIPAL = exports.MARKER_WALLET = void 0;
4
+ exports.validateAgentCardRules = validateAgentCardRules;
5
+ exports.encodeAgentCardRules = encodeAgentCardRules;
6
+ exports.decodeCardRulesWire = decodeCardRulesWire;
7
+ exports.decodeAgentCardRules = decodeAgentCardRules;
8
+ exports.fillCardRules = fillCardRules;
9
+ const viem_1 = require("viem");
10
+ const enums_1 = require("../constants/enums");
11
+ const prc20_address_1 = require("../universal/prc20-address");
12
+ const abi_layout_1 = require("../agentic/codec/abi-layout");
13
+ const selectors_1 = require("../agentic/codec/selectors");
14
+ const pins_1 = require("../agentic/codec/pins");
15
+ const universal_terms_1 = require("../agentic/codec/universal-terms");
16
+ const constants_1 = require("../job-spec/constants");
17
+ const errors_1 = require("./errors");
18
+ exports.MARKER_WALLET = (0, viem_1.keccak256)((0, viem_1.stringToHex)('push.marketplace.marker.WALLET'));
19
+ exports.MARKER_PRINCIPAL = (0, viem_1.keccak256)((0, viem_1.stringToHex)('push.marketplace.marker.PRINCIPAL'));
20
+ const PRINCIPAL_WORD = BigInt(exports.MARKER_PRINCIPAL);
21
+ const decodedRules = new WeakMap();
22
+ const fingerprint = (r) => JSON.stringify(r, (_, v) => (typeof v === 'bigint' ? v.toString() : v));
23
+ const fields = universal_terms_1.UNIVERSAL_TERMS_PARAM.components;
24
+ exports.CARD_RULES_PARAM = {
25
+ type: 'tuple',
26
+ components: [
27
+ fields[2],
28
+ { name: 'principalAsset', type: 'uint8' },
29
+ fields[3],
30
+ fields[4],
31
+ ],
32
+ };
33
+ const bad = (message) => {
34
+ throw new errors_1.MarketError('INVALID_AGENT_CARD_RULES', message);
35
+ };
36
+ function cap(n) {
37
+ const v = n === constants_1.PRINCIPAL ? PRINCIPAL_WORD : n ?? BigInt(0);
38
+ if (typeof v !== 'bigint' || v < BigInt(0) || v >= BigInt(1) << BigInt(256))
39
+ bad('Spending caps must fit uint256.');
40
+ return v;
41
+ }
42
+ function toWire(input, options) {
43
+ if (!input ||
44
+ !Array.isArray(input.assets) ||
45
+ !Array.isArray(input.allowedCalls))
46
+ bad('Card rules need assets and allowedCalls arrays.');
47
+ const saved = decodedRules.get(input);
48
+ if (saved?.fingerprint === fingerprint(input))
49
+ return saved.wire;
50
+ if ('approvals' in input)
51
+ bad('V2 approvals belong in allowedCalls with spender and amount pins; remove the retired approvals array.');
52
+ if (input.assets.some((a) => typeof a.token === 'object' &&
53
+ 'prc20' in a.token &&
54
+ /^0x0{40}$/i.test(a.token.prc20)))
55
+ bad('An explicit PRC20 reference cannot be zero.');
56
+ const assets = input.assets.map((a) => ({
57
+ token: typeof a.token === 'object' && 'prc20' in a.token
58
+ ? (0, viem_1.getAddress)(a.token.prc20)
59
+ : (() => {
60
+ if (options?.structural)
61
+ return (0, viem_1.getAddress)(typeof a.token === 'string' ? a.token : a.token.address);
62
+ if (!options?.chain)
63
+ return bad('Encoding destination tokens needs the card chain, or an explicit { prc20 } reference.');
64
+ try {
65
+ return (0, prc20_address_1.getPRC20Address)({
66
+ chain: options.chain,
67
+ address: typeof a.token === 'string' ? a.token : a.token.address,
68
+ }, { network: options.network ?? enums_1.PUSH_NETWORK.TESTNET_DONUT }).address;
69
+ }
70
+ catch (cause) {
71
+ throw new errors_1.MarketError('TOKEN_ROUTE_UNAVAILABLE', 'This card token has no verified Push route for the selected chain.', { chain: options.chain, token: a.token }, cause);
72
+ }
73
+ })(),
74
+ maxPerCall: cap(a.maxPerCall),
75
+ maxTotal: cap(a.maxTotal),
76
+ }));
77
+ const allowedCalls = input.allowedCalls.map((call) => {
78
+ const parsed = (0, selectors_1.parseSelector)(call.selector);
79
+ if (parsed.valueOnly)
80
+ bad('Marketplace cards support EVM function calls, not Push value-only rules.');
81
+ const pins = (call.pins ?? []).map((p) => {
82
+ const location = parsed.inputs
83
+ ? (0, abi_layout_1.argumentLocation)(parsed.inputs, p.arg, 'Card pin')
84
+ : {
85
+ offset: typeof p.arg === 'number' && Number.isInteger(p.arg) && p.arg >= 0
86
+ ? 4 + p.arg * 32
87
+ : bad('Raw selector pins need a nonnegative integer word index.'),
88
+ param: { type: 'uint256' },
89
+ };
90
+ const max = 'max' in p && p.max !== undefined;
91
+ const value = 'max' in p && p.max !== undefined ? p.max : p.expected;
92
+ if (value === undefined)
93
+ return bad('A card pin needs expected or max.');
94
+ if (value === 'agentic:wallet' && max)
95
+ bad('WALLET is supported only in equality pins.');
96
+ const encoded = value === 'agentic:wallet'
97
+ ? exports.MARKER_WALLET
98
+ : value === constants_1.PRINCIPAL
99
+ ? exports.MARKER_PRINCIPAL
100
+ : max
101
+ ? (0, viem_1.toHex)(cap(value), { size: 32 })
102
+ : (0, abi_layout_1.encodeArgWord)(location.param, value, 'Card pin');
103
+ return {
104
+ offset: location.offset,
105
+ op: max ? 1 : 0,
106
+ value: encoded,
107
+ };
108
+ });
109
+ return {
110
+ target: (0, viem_1.getAddress)(call.target),
111
+ selector: parsed.selector,
112
+ beneficiaryOffset: 0,
113
+ hasBeneficiary: false,
114
+ maxValue: cap(call.maxValue),
115
+ pins,
116
+ };
117
+ });
118
+ const wire = {
119
+ assets,
120
+ principalAsset: input.principalAsset,
121
+ maxGasPerCall: cap(input.maxGasPerCall),
122
+ allowedCalls,
123
+ };
124
+ validateWire(wire, !!options?.structural);
125
+ return wire;
126
+ }
127
+ function validateWire(r, structural = false) {
128
+ if (!Array.isArray(r.assets) || r.assets.length < 1 || r.assets.length > 8)
129
+ bad('Cards need 1..8 assets.');
130
+ if (!Number.isInteger(r.principalAsset) ||
131
+ r.principalAsset < 0 ||
132
+ r.principalAsset >= r.assets.length)
133
+ bad('principalAsset is outside the asset list.');
134
+ const tokens = new Set();
135
+ r.assets.forEach((a, i) => {
136
+ if (!(0, viem_1.isAddress)(a.token) ||
137
+ (!structural && /^0x0{40}$/i.test(a.token)) ||
138
+ tokens.has(a.token.toLowerCase()))
139
+ bad('Assets need distinct nonzero PRC20 addresses.');
140
+ tokens.add(a.token.toLowerCase());
141
+ cap(a.maxPerCall);
142
+ cap(a.maxTotal);
143
+ if (i === r.principalAsset) {
144
+ if (a.maxTotal !== PRINCIPAL_WORD || a.maxPerCall === BigInt(0))
145
+ bad('The principal total must be PRINCIPAL and its per-call cap must be positive or PRINCIPAL.');
146
+ }
147
+ else if (a.maxPerCall === PRINCIPAL_WORD || a.maxTotal === PRINCIPAL_WORD)
148
+ bad('PRINCIPAL asset-cap markers belong only on the principal asset.');
149
+ });
150
+ cap(r.maxGasPerCall);
151
+ if (!Array.isArray(r.allowedCalls) ||
152
+ r.allowedCalls.length < 1 ||
153
+ r.allowedCalls.length > 32)
154
+ bad('Cards need 1..32 allowed calls.');
155
+ if (r.allowedCalls.reduce((n, c) => n + c.pins.length, 0) > 32)
156
+ bad('A card rule supports at most 32 conditions.');
157
+ const entries = new Set();
158
+ const pairs = new Map();
159
+ for (const c of r.allowedCalls) {
160
+ if (!(0, viem_1.isAddress)(c.target) ||
161
+ /^0x0{40}$/i.test(c.target) ||
162
+ !/^0x[\da-f]{8}$/i.test(c.selector))
163
+ bad('An allowed app or selector is invalid.');
164
+ cap(c.maxValue);
165
+ try {
166
+ (0, pins_1.validatePins)(c.pins);
167
+ }
168
+ catch (cause) {
169
+ throw new errors_1.MarketError('INVALID_AGENT_CARD_RULES', 'An allowed call has invalid argument conditions.', undefined, cause);
170
+ }
171
+ if (c.hasBeneficiary &&
172
+ (c.beneficiaryOffset < 4 || (c.beneficiaryOffset - 4) % 32 !== 0))
173
+ bad('Invalid recipient offset.');
174
+ for (const p of c.pins)
175
+ if (p.value === exports.MARKER_WALLET && p.op !== 0)
176
+ bad('WALLET pins must use equality.');
177
+ const encoded = (0, viem_1.encodeAbiParameters)([{ ...fields[4], type: 'tuple' }], [c]);
178
+ if (entries.has(encoded))
179
+ bad('Duplicate allowed call.');
180
+ entries.add(encoded);
181
+ const key = `${c.target.toLowerCase()}:${c.selector.toLowerCase()}`;
182
+ if (pairs.has(key) && (!pairs.get(key) || !c.pins.length))
183
+ bad('An unpinned alternative would bypass the pinned call.');
184
+ pairs.set(key, c.pins.length > 0);
185
+ const pin = (offset, op) => c.pins.find((p) => p.offset === offset && p.op === op);
186
+ const recipient = (offset) => (c.hasBeneficiary && c.beneficiaryOffset === offset) ||
187
+ pin(offset, 0)?.value === exports.MARKER_WALLET;
188
+ if (c.selector === '0x39509351')
189
+ bad('increaseAllowance is not supported in cards.');
190
+ if (c.selector === '0x095ea7b3') {
191
+ const spender = pin(4, 0)?.value;
192
+ if (!spender ||
193
+ BigInt(spender) === BigInt(0) ||
194
+ BigInt(spender) >> BigInt(160) !== BigInt(0))
195
+ bad('approve needs an EQ pin to a nonzero literal spender.');
196
+ if (!pin(36, 1))
197
+ bad('approve needs a MAX amount pin.');
198
+ }
199
+ if (c.selector === '0xa9059cbb' && !recipient(4))
200
+ bad('transfer must pin its recipient to WALLET.');
201
+ if (c.selector === '0x23b872dd' && !recipient(36))
202
+ bad('transferFrom must pin its recipient to WALLET.');
203
+ }
204
+ }
205
+ function validateAgentCardRules(rules) {
206
+ toWire(rules, { structural: true });
207
+ }
208
+ function encodeAgentCardRules(rules, options) {
209
+ return (0, viem_1.encodeAbiParameters)([exports.CARD_RULES_PARAM], [toWire(rules, options)]);
210
+ }
211
+ function decodeCardRulesWire(bytes) {
212
+ try {
213
+ const wire = (0, viem_1.decodeAbiParameters)([exports.CARD_RULES_PARAM], bytes)[0];
214
+ validateWire(wire);
215
+ if ((0, viem_1.encodeAbiParameters)([exports.CARD_RULES_PARAM], [wire]).toLowerCase() !==
216
+ bytes.toLowerCase())
217
+ bad('Noncanonical card rules.');
218
+ return wire;
219
+ }
220
+ catch (cause) {
221
+ if (cause instanceof errors_1.MarketError)
222
+ throw cause;
223
+ throw new errors_1.MarketError('INVALID_AGENT_CARD_RULES', 'Unsupported or malformed v2 card-rule encoding.', undefined, cause);
224
+ }
225
+ }
226
+ function decodeAgentCardRules(bytes, _options) {
227
+ void _options;
228
+ const r = decodeCardRulesWire(bytes);
229
+ // Explicit PRC20 references make unknown/custom registry tokens lossless and unambiguous.
230
+ const result = {
231
+ ...r,
232
+ assets: r.assets.map((a) => ({
233
+ token: { prc20: a.token },
234
+ maxPerCall: a.maxPerCall === PRINCIPAL_WORD ? constants_1.PRINCIPAL : a.maxPerCall,
235
+ maxTotal: a.maxTotal === PRINCIPAL_WORD ? constants_1.PRINCIPAL : a.maxTotal,
236
+ })),
237
+ allowedCalls: r.allowedCalls.map((c) => ({
238
+ target: c.target,
239
+ selector: c.selector,
240
+ maxValue: c.maxValue,
241
+ pins: [
242
+ ...c.pins.map((p) => {
243
+ const value = p.value === exports.MARKER_WALLET
244
+ ? 'agentic:wallet'
245
+ : p.value === exports.MARKER_PRINCIPAL
246
+ ? constants_1.PRINCIPAL
247
+ : p.value;
248
+ return p.op === 1
249
+ ? {
250
+ arg: (p.offset - 4) / 32,
251
+ max: value === constants_1.PRINCIPAL ? constants_1.PRINCIPAL : BigInt(p.value),
252
+ }
253
+ : { arg: (p.offset - 4) / 32, expected: value };
254
+ }),
255
+ ...(c.hasBeneficiary
256
+ ? [
257
+ {
258
+ arg: (c.beneficiaryOffset - 4) / 32,
259
+ expected: 'agentic:wallet',
260
+ },
261
+ ]
262
+ : []),
263
+ ],
264
+ })),
265
+ };
266
+ decodedRules.set(result, { fingerprint: fingerprint(result), wire: r });
267
+ return result;
268
+ }
269
+ function fillCardRules(r, principal, wallet, expiredAt) {
270
+ const walletWord = (0, viem_1.toHex)(BigInt(wallet), { size: 32 });
271
+ return {
272
+ validUntil: expiredAt,
273
+ expectedCEA: wallet,
274
+ assets: r.assets.map((a, i) => ({
275
+ ...a,
276
+ maxPerCall: a.maxPerCall === PRINCIPAL_WORD ? principal : a.maxPerCall,
277
+ maxTotal: i === r.principalAsset ? principal : a.maxTotal,
278
+ })),
279
+ maxGasPerCall: r.maxGasPerCall,
280
+ allowedCalls: r.allowedCalls.map((c) => ({
281
+ ...c,
282
+ pins: c.pins.map((p) => ({
283
+ ...p,
284
+ value: p.value === exports.MARKER_WALLET
285
+ ? walletWord
286
+ : p.value === exports.MARKER_PRINCIPAL
287
+ ? (0, viem_1.toHex)(principal, { size: 32 })
288
+ : p.value,
289
+ })),
290
+ })),
291
+ };
292
+ }
293
+ //# sourceMappingURL=rules.js.map
@@ -0,0 +1,35 @@
1
+ import { type Abi, type Address, type TypedData, type TypedDataDomain } from 'viem';
2
+ import type { AgenticRuntime } from '../agentic/runtime';
3
+ import type { Call } from '../agentic/contracts/v6';
4
+ import type { ExecuteParams, TransactionExecutionOptions, UniversalExecuteParams, UniversalTxResponse } from '../orchestrator/orchestrator.types';
5
+ import type { ProgressEvent } from '../progress-hook/progress-hook.types';
6
+ import { type MarketDeployment } from './deployment';
7
+ export type StackProgressHook = (event: ProgressEvent) => void;
8
+ export interface StackRuntime {
9
+ agw: AgenticRuntime;
10
+ account(): Address;
11
+ wallet(): Address | undefined;
12
+ send(params: ExecuteParams | UniversalExecuteParams, options?: TransactionExecutionOptions): Promise<UniversalTxResponse>;
13
+ signTypedData(data: {
14
+ domain: TypedDataDomain;
15
+ types: TypedData;
16
+ primaryType: string;
17
+ message: Record<string, unknown>;
18
+ }): Promise<string>;
19
+ canSignTypedData?(): boolean;
20
+ /** Internal fixture override; never a public initialization option. */
21
+ deployment?: MarketDeployment;
22
+ /** Receipt-confirmed creation blocks accelerate bounded event recovery. */
23
+ jobBlocks?: Map<bigint, bigint>;
24
+ }
25
+ export declare function deployment(rt: StackRuntime): MarketDeployment;
26
+ export interface MarketSnapshot {
27
+ blockNumber: bigint;
28
+ timestamp: number;
29
+ read<T>(address: Address, abi: Abi, name: string, args?: readonly unknown[]): Promise<T>;
30
+ }
31
+ export declare function snapshot(rt: StackRuntime, atBlock?: bigint): Promise<MarketSnapshot>;
32
+ export declare function progress(rt: StackRuntime, hook: StackProgressHook | undefined, id: string, message: string, response?: object): void;
33
+ export declare function write(rt: StackRuntime, call: Call, hook: StackProgressHook | undefined, family: 'MARKET' | 'JOB', signer?: boolean): Promise<UniversalTxResponse>;
34
+ export declare function ownerBatch(rt: StackRuntime, wallet: Address, calls: Call[], hook?: StackProgressHook): Promise<UniversalTxResponse>;
35
+ export declare function eventArgs(rt: StackRuntime, tx: UniversalTxResponse, address: Address, abi: Abi, name: string): Promise<Record<string, unknown>>;
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deployment = deployment;
4
+ exports.snapshot = snapshot;
5
+ exports.progress = progress;
6
+ exports.write = write;
7
+ exports.ownerBatch = ownerBatch;
8
+ exports.eventArgs = eventArgs;
9
+ const viem_1 = require("viem");
10
+ const common_1 = require("../agentic/management/common");
11
+ const deployments_1 = require("../agentic/deployments");
12
+ const errors_1 = require("./errors");
13
+ const deployment_1 = require("./deployment");
14
+ function deployment(rt) {
15
+ return rt.deployment ?? (0, deployment_1.marketplaceDeployment)(rt.agw.network);
16
+ }
17
+ async function snapshot(rt, atBlock) {
18
+ const blockNumber = atBlock ?? (await rt.agw.reader.getBlockNumber());
19
+ const timestamp = rt.agw.reader.getBlock
20
+ ? Number((await rt.agw.reader.getBlock({ blockNumber })).timestamp)
21
+ : rt.agw.nowSeconds();
22
+ return {
23
+ blockNumber,
24
+ timestamp,
25
+ read: async (address, abi, name, args = []) => {
26
+ try {
27
+ return (await rt.agw.reader.readContract({
28
+ address,
29
+ abi,
30
+ functionName: name,
31
+ args,
32
+ blockNumber,
33
+ }));
34
+ }
35
+ catch (cause) {
36
+ throw new errors_1.MarketError('READ_FAILED', `Could not load ${name} at block ${blockNumber}.`, { address, functionName: name, blockNumber }, cause);
37
+ }
38
+ },
39
+ };
40
+ }
41
+ function progress(rt, hook, id, message, response = {}) {
42
+ rt.agw.emit({
43
+ id,
44
+ title: message,
45
+ message,
46
+ level: id.endsWith('199-02') ? 'ERROR' : 'INFO',
47
+ response,
48
+ timestamp: new Date().toISOString(),
49
+ }, hook);
50
+ }
51
+ async function write(rt, call, hook, family, signer = false) {
52
+ if (rt.agw.isReadOnly)
53
+ throw new errors_1.MarketError('READ_ONLY', 'Connect a signing wallet to continue.');
54
+ progress(rt, hook, `${family}-TX-103`, 'Submitting transaction');
55
+ try {
56
+ const tx = await (signer
57
+ ? rt.agw.execute({ to: call.target, value: call.value, data: call.data }, { progressHook: hook })
58
+ : rt.send({ to: call.target, value: call.value, data: call.data }, { progressHook: hook }));
59
+ const originalWait = tx.wait.bind(tx);
60
+ let terminalReported = false;
61
+ const wait = async (...args) => {
62
+ try {
63
+ const receipt = await originalWait(...args);
64
+ if (!terminalReported) {
65
+ terminalReported = true;
66
+ progress(rt, hook, `${family}-TX-199-${receipt.status === 1 ? '01' : '02'}`, receipt.status === 1
67
+ ? 'Transaction confirmed'
68
+ : 'Transaction reverted', { txHash: tx.hash });
69
+ }
70
+ return receipt;
71
+ }
72
+ catch (error) {
73
+ progress(rt, hook, `${family}-TX-199-02`, 'Transaction confirmation unavailable', { txHash: tx.hash });
74
+ throw error;
75
+ }
76
+ };
77
+ return { ...tx, wait };
78
+ }
79
+ catch (error) {
80
+ const wrapped = (0, errors_1.stackError)(error);
81
+ progress(rt, hook, `${family}-TX-199-02`, 'Transaction failed', {
82
+ error: wrapped,
83
+ });
84
+ throw wrapped;
85
+ }
86
+ }
87
+ async function ownerBatch(rt, wallet, calls, hook) {
88
+ const gen = (0, deployments_1.currentGeneration)(rt.agw.network);
89
+ const s = await snapshot(rt);
90
+ const owner = (0, viem_1.getAddress)(await s.read(wallet, gen.contracts.abis.wallet, 'owner'));
91
+ if (owner !== (0, viem_1.getAddress)(rt.agw.signerPushAccount()))
92
+ throw new errors_1.MarketError('NOT_CLIENT', 'Connect the owner of the job wallet.');
93
+ return write(rt, {
94
+ target: wallet,
95
+ value: BigInt(0),
96
+ data: gen.contracts.encodeExecute(calls),
97
+ }, hook, 'JOB', true);
98
+ }
99
+ async function eventArgs(rt, tx, address, abi, name) {
100
+ const result = await (0, common_1.confirmedLogs)(rt.agw, tx);
101
+ const found = [];
102
+ for (const log of result.logs) {
103
+ if (log.address.toLowerCase() !== address.toLowerCase())
104
+ continue;
105
+ try {
106
+ const e = (0, viem_1.decodeEventLog)({
107
+ abi,
108
+ eventName: name,
109
+ data: log.data,
110
+ topics: log.topics,
111
+ strict: true,
112
+ });
113
+ if (e.eventName === name) {
114
+ found.push(e.args);
115
+ const args = e.args;
116
+ if ((name === 'JobCreated' || name === 'JobOpened') &&
117
+ typeof args['jobId'] === 'bigint' &&
118
+ log.blockNumber !== null)
119
+ rt.jobBlocks?.set(args['jobId'], log.blockNumber);
120
+ }
121
+ }
122
+ catch {
123
+ /* Other contract events are expected in a receipt. */
124
+ }
125
+ }
126
+ if (found.length !== 1)
127
+ throw new errors_1.MarketError('RECEIPT_MISMATCH', `The submitted transaction did not produce one ${name} event.`, { txHash: tx.hash });
128
+ return found[0];
129
+ }
130
+ //# sourceMappingURL=runtime.js.map