@virtuals-protocol/acp-node 0.3.0-beta.12 → 0.3.0-beta.14

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/index.mjs CHANGED
@@ -2,51 +2,41 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
2
2
  var __commonJS = (cb, mod) => function __require() {
3
3
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
4
4
  };
5
- var __async = (__this, __arguments, generator) => {
6
- return new Promise((resolve, reject) => {
7
- var fulfilled = (value) => {
8
- try {
9
- step(generator.next(value));
10
- } catch (e) {
11
- reject(e);
12
- }
13
- };
14
- var rejected = (value) => {
15
- try {
16
- step(generator.throw(value));
17
- } catch (e) {
18
- reject(e);
19
- }
20
- };
21
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
22
- step((generator = generator.apply(__this, __arguments)).next());
23
- });
24
- };
25
5
 
26
6
  // package.json
27
7
  var require_package = __commonJS({
28
8
  "package.json"(exports, module) {
29
9
  module.exports = {
30
10
  name: "@virtuals-protocol/acp-node",
31
- version: "0.3.0-beta.12",
11
+ version: "0.3.0-beta.14",
32
12
  main: "./dist/index.js",
33
13
  module: "./dist/index.mjs",
34
14
  types: "./dist/index.d.ts",
35
15
  scripts: {
36
- test: 'echo "Error: no test specified" && exit 1',
16
+ test: "jest",
17
+ "test:watch": "jest --watch",
18
+ "test:coverage": "jest --coverage",
37
19
  tsup: "tsup src/index.ts --dts --format cjs,esm --out-dir dist"
38
20
  },
39
21
  author: "",
40
22
  license: "ISC",
41
23
  description: "",
42
24
  devDependencies: {
25
+ "@babel/core": "^7.28.5",
26
+ "@babel/preset-env": "^7.28.5",
27
+ "@babel/preset-typescript": "^7.28.5",
28
+ "@types/jest": "^30.0.0",
29
+ "babel-jest": "^30.2.0",
30
+ dotenv: "^17.2.3",
31
+ jest: "^30.2.0",
32
+ "ts-jest": "^29.4.5",
43
33
  typescript: "^5.8.3"
44
34
  },
45
35
  dependencies: {
46
36
  "@aa-sdk/core": "^4.73.0",
47
37
  "@account-kit/infra": "^4.73.0",
48
38
  "@account-kit/smart-contracts": "^4.73.0",
49
- "@virtuals-protocol/acp-node": "^0.3.0-beta.9",
39
+ "@virtuals-protocol/acp-node": "^0.3.0-beta.10",
50
40
  ajv: "^8.17.1",
51
41
  "socket.io-client": "^4.8.1",
52
42
  tsup: "^8.5.0",
@@ -1230,7 +1220,7 @@ var ACP_ABI = [
1230
1220
  var acpAbi_default = ACP_ABI;
1231
1221
 
1232
1222
  // src/acpClient.ts
1233
- import { zeroAddress as zeroAddress2 } from "viem";
1223
+ import { zeroAddress as zeroAddress3 } from "viem";
1234
1224
  import { io } from "socket.io-client";
1235
1225
 
1236
1226
  // src/contractClients/baseAcpContractClient.ts
@@ -1241,7 +1231,8 @@ import {
1241
1231
  http as http2,
1242
1232
  keccak256,
1243
1233
  toEventSignature,
1244
- toHex
1234
+ toHex,
1235
+ zeroAddress
1245
1236
  } from "viem";
1246
1237
 
1247
1238
  // src/configs/acpConfigs.ts
@@ -1280,22 +1271,20 @@ var Fare = class _Fare {
1280
1271
  formatAmount(amount) {
1281
1272
  return parseUnits(amount.toString(), this.decimals);
1282
1273
  }
1283
- static fromContractAddress(_0) {
1284
- return __async(this, arguments, function* (contractAddress, config = baseAcpConfig) {
1285
- if (contractAddress === config.baseFare.contractAddress) {
1286
- return config.baseFare;
1287
- }
1288
- const publicClient = createPublicClient({
1289
- chain: config.chain,
1290
- transport: http(config.rpcEndpoint)
1291
- });
1292
- const decimals = yield publicClient.readContract({
1293
- address: contractAddress,
1294
- abi: erc20Abi,
1295
- functionName: "decimals"
1296
- });
1297
- return new _Fare(contractAddress, decimals);
1274
+ static async fromContractAddress(contractAddress, config = baseAcpConfig) {
1275
+ if (contractAddress === config.baseFare.contractAddress) {
1276
+ return config.baseFare;
1277
+ }
1278
+ const publicClient = createPublicClient({
1279
+ chain: config.chain,
1280
+ transport: http(config.rpcEndpoint)
1298
1281
  });
1282
+ const decimals = await publicClient.readContract({
1283
+ address: contractAddress,
1284
+ abi: erc20Abi,
1285
+ functionName: "decimals"
1286
+ });
1287
+ return new _Fare(contractAddress, decimals);
1299
1288
  }
1300
1289
  };
1301
1290
  var FareAmountBase = class {
@@ -1303,14 +1292,12 @@ var FareAmountBase = class {
1303
1292
  this.amount = amount;
1304
1293
  this.fare = fare;
1305
1294
  }
1306
- static fromContractAddress(_0, _1) {
1307
- return __async(this, arguments, function* (amount, contractAddress, config = baseAcpConfig) {
1308
- const fare = yield Fare.fromContractAddress(contractAddress, config);
1309
- if (typeof amount === "number") {
1310
- return new FareAmount(amount, fare);
1311
- }
1312
- return new FareBigInt(amount, fare);
1313
- });
1295
+ static async fromContractAddress(amount, contractAddress, config = baseAcpConfig) {
1296
+ const fare = await Fare.fromContractAddress(contractAddress, config);
1297
+ if (typeof amount === "number") {
1298
+ return new FareAmount(amount, fare);
1299
+ }
1300
+ return new FareBigInt(amount, fare);
1314
1301
  }
1315
1302
  };
1316
1303
  var FareAmount = class extends FareAmountBase {
@@ -3267,6 +3254,241 @@ var FIAT_TOKEN_V2_ABI = [
3267
3254
  ];
3268
3255
  var fiatTokenV2Abi_default = FIAT_TOKEN_V2_ABI;
3269
3256
 
3257
+ // src/abis/singleSignerValidationModuleAbi.ts
3258
+ var SINGLE_SIGNER_VALIDATION_MODULE_ABI = [
3259
+ { inputs: [], name: "InvalidSignatureType", type: "error" },
3260
+ {
3261
+ inputs: [],
3262
+ name: "NotAuthorized",
3263
+ type: "error"
3264
+ },
3265
+ { inputs: [], name: "NotImplemented", type: "error" },
3266
+ {
3267
+ inputs: [],
3268
+ name: "UnexpectedDataPassed",
3269
+ type: "error"
3270
+ },
3271
+ {
3272
+ anonymous: true,
3273
+ inputs: [
3274
+ {
3275
+ indexed: true,
3276
+ internalType: "address",
3277
+ name: "account",
3278
+ type: "address"
3279
+ },
3280
+ {
3281
+ indexed: true,
3282
+ internalType: "uint32",
3283
+ name: "entityId",
3284
+ type: "uint32"
3285
+ },
3286
+ {
3287
+ indexed: true,
3288
+ internalType: "address",
3289
+ name: "newSigner",
3290
+ type: "address"
3291
+ },
3292
+ {
3293
+ indexed: false,
3294
+ internalType: "address",
3295
+ name: "previousSigner",
3296
+ type: "address"
3297
+ }
3298
+ ],
3299
+ name: "SignerTransferred",
3300
+ type: "event"
3301
+ },
3302
+ {
3303
+ inputs: [],
3304
+ name: "moduleId",
3305
+ outputs: [{ internalType: "string", name: "", type: "string" }],
3306
+ stateMutability: "pure",
3307
+ type: "function"
3308
+ },
3309
+ {
3310
+ inputs: [{ internalType: "bytes", name: "data", type: "bytes" }],
3311
+ name: "onInstall",
3312
+ outputs: [],
3313
+ stateMutability: "nonpayable",
3314
+ type: "function"
3315
+ },
3316
+ {
3317
+ inputs: [{ internalType: "bytes", name: "data", type: "bytes" }],
3318
+ name: "onUninstall",
3319
+ outputs: [],
3320
+ stateMutability: "nonpayable",
3321
+ type: "function"
3322
+ },
3323
+ {
3324
+ inputs: [
3325
+ { internalType: "address", name: "account", type: "address" },
3326
+ {
3327
+ internalType: "bytes32",
3328
+ name: "hash",
3329
+ type: "bytes32"
3330
+ }
3331
+ ],
3332
+ name: "replaySafeHash",
3333
+ outputs: [{ internalType: "bytes32", name: "", type: "bytes32" }],
3334
+ stateMutability: "view",
3335
+ type: "function"
3336
+ },
3337
+ {
3338
+ inputs: [
3339
+ { internalType: "uint32", name: "entityId", type: "uint32" },
3340
+ {
3341
+ internalType: "address",
3342
+ name: "account",
3343
+ type: "address"
3344
+ }
3345
+ ],
3346
+ name: "signers",
3347
+ outputs: [{ internalType: "address", name: "", type: "address" }],
3348
+ stateMutability: "view",
3349
+ type: "function"
3350
+ },
3351
+ {
3352
+ inputs: [{ internalType: "bytes4", name: "interfaceId", type: "bytes4" }],
3353
+ name: "supportsInterface",
3354
+ outputs: [{ internalType: "bool", name: "", type: "bool" }],
3355
+ stateMutability: "view",
3356
+ type: "function"
3357
+ },
3358
+ {
3359
+ inputs: [
3360
+ { internalType: "uint32", name: "entityId", type: "uint32" },
3361
+ {
3362
+ internalType: "address",
3363
+ name: "newSigner",
3364
+ type: "address"
3365
+ }
3366
+ ],
3367
+ name: "transferSigner",
3368
+ outputs: [],
3369
+ stateMutability: "nonpayable",
3370
+ type: "function"
3371
+ },
3372
+ {
3373
+ inputs: [
3374
+ { internalType: "address", name: "account", type: "address" },
3375
+ {
3376
+ internalType: "uint32",
3377
+ name: "entityId",
3378
+ type: "uint32"
3379
+ },
3380
+ { internalType: "address", name: "sender", type: "address" },
3381
+ {
3382
+ internalType: "uint256",
3383
+ name: "",
3384
+ type: "uint256"
3385
+ },
3386
+ { internalType: "bytes", name: "", type: "bytes" },
3387
+ {
3388
+ internalType: "bytes",
3389
+ name: "",
3390
+ type: "bytes"
3391
+ }
3392
+ ],
3393
+ name: "validateRuntime",
3394
+ outputs: [],
3395
+ stateMutability: "view",
3396
+ type: "function"
3397
+ },
3398
+ {
3399
+ inputs: [
3400
+ { internalType: "address", name: "account", type: "address" },
3401
+ {
3402
+ internalType: "uint32",
3403
+ name: "entityId",
3404
+ type: "uint32"
3405
+ },
3406
+ { internalType: "address", name: "", type: "address" },
3407
+ {
3408
+ internalType: "bytes32",
3409
+ name: "digest",
3410
+ type: "bytes32"
3411
+ },
3412
+ { internalType: "bytes", name: "signature", type: "bytes" }
3413
+ ],
3414
+ name: "validateSignature",
3415
+ outputs: [{ internalType: "bytes4", name: "", type: "bytes4" }],
3416
+ stateMutability: "view",
3417
+ type: "function"
3418
+ },
3419
+ {
3420
+ inputs: [
3421
+ {
3422
+ internalType: "uint32",
3423
+ name: "entityId",
3424
+ type: "uint32"
3425
+ },
3426
+ {
3427
+ components: [
3428
+ { internalType: "address", name: "sender", type: "address" },
3429
+ {
3430
+ internalType: "uint256",
3431
+ name: "nonce",
3432
+ type: "uint256"
3433
+ },
3434
+ { internalType: "bytes", name: "initCode", type: "bytes" },
3435
+ {
3436
+ internalType: "bytes",
3437
+ name: "callData",
3438
+ type: "bytes"
3439
+ },
3440
+ {
3441
+ internalType: "bytes32",
3442
+ name: "accountGasLimits",
3443
+ type: "bytes32"
3444
+ },
3445
+ {
3446
+ internalType: "uint256",
3447
+ name: "preVerificationGas",
3448
+ type: "uint256"
3449
+ },
3450
+ { internalType: "bytes32", name: "gasFees", type: "bytes32" },
3451
+ {
3452
+ internalType: "bytes",
3453
+ name: "paymasterAndData",
3454
+ type: "bytes"
3455
+ },
3456
+ { internalType: "bytes", name: "signature", type: "bytes" }
3457
+ ],
3458
+ internalType: "struct PackedUserOperation",
3459
+ name: "userOp",
3460
+ type: "tuple"
3461
+ },
3462
+ { internalType: "bytes32", name: "userOpHash", type: "bytes32" }
3463
+ ],
3464
+ name: "validateUserOp",
3465
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
3466
+ stateMutability: "view",
3467
+ type: "function"
3468
+ }
3469
+ ];
3470
+ var singleSignerValidationModuleAbi_default = SINGLE_SIGNER_VALIDATION_MODULE_ABI;
3471
+
3472
+ // src/constants.ts
3473
+ import { base as base2, baseSepolia as baseSepolia2 } from "viem/chains";
3474
+ var USDC_TOKEN_ADDRESS = {
3475
+ [baseSepolia2.id]: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
3476
+ [base2.id]: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
3477
+ };
3478
+ var X402AuthorizationTypes = [
3479
+ { name: "from", type: "address" },
3480
+ { name: "to", type: "address" },
3481
+ { name: "value", type: "uint256" },
3482
+ { name: "validAfter", type: "uint256" },
3483
+ { name: "validBefore", type: "uint256" },
3484
+ { name: "nonce", type: "bytes32" }
3485
+ ];
3486
+ var HTTP_STATUS_CODES = {
3487
+ OK: 200,
3488
+ PAYMENT_REQUIRED: 402
3489
+ };
3490
+ var SINGLE_SIGNER_VALIDATION_MODULE_ADDRESS = "0x00000000000099DE0BF6fA90dEB851E2A2df7d83";
3491
+
3270
3492
  // src/contractClients/baseAcpContractClient.ts
3271
3493
  var MemoType = /* @__PURE__ */ ((MemoType3) => {
3272
3494
  MemoType3[MemoType3["MESSAGE"] = 0] = "MESSAGE";
@@ -3309,6 +3531,44 @@ var BaseAcpContractClient = class {
3309
3531
  transport: http2(this.config.rpcEndpoint)
3310
3532
  });
3311
3533
  }
3534
+ async validateSessionKeyOnChain(sessionSignerAddress, sessionEntityKeyId) {
3535
+ const onChainSignerAddress = (await this.publicClient.readContract({
3536
+ address: SINGLE_SIGNER_VALIDATION_MODULE_ADDRESS,
3537
+ abi: singleSignerValidationModuleAbi_default,
3538
+ functionName: "signers",
3539
+ args: [sessionEntityKeyId, this.agentWalletAddress]
3540
+ })).toLowerCase();
3541
+ if (onChainSignerAddress === zeroAddress.toLowerCase()) {
3542
+ throw new acpError_default(
3543
+ `ACP Contract Client validation failed:
3544
+ ${JSON.stringify(
3545
+ {
3546
+ reason: "no whitelisted wallet registered on-chain for entity id",
3547
+ entityId: sessionEntityKeyId,
3548
+ agentWalletAddress: this.agentWalletAddress
3549
+ },
3550
+ null,
3551
+ 2
3552
+ )}`
3553
+ );
3554
+ }
3555
+ if (onChainSignerAddress !== sessionSignerAddress.toLowerCase()) {
3556
+ throw new acpError_default(
3557
+ `ACP Contract Client validation failed:
3558
+ ${JSON.stringify(
3559
+ {
3560
+ agentWalletAddress: this.agentWalletAddress,
3561
+ entityId: sessionEntityKeyId,
3562
+ givenWhitelistedWalletAddress: sessionSignerAddress,
3563
+ expectedWhitelistedWalletAddress: onChainSignerAddress,
3564
+ reason: "session signer address mismatch"
3565
+ },
3566
+ null,
3567
+ 2
3568
+ )}`
3569
+ );
3570
+ }
3571
+ }
3312
3572
  get walletAddress() {
3313
3573
  return this.agentWalletAddress;
3314
3574
  }
@@ -3468,43 +3728,39 @@ var BaseAcpContractClient = class {
3468
3728
  throw new acpError_default("Failed to wrap eth", error);
3469
3729
  }
3470
3730
  }
3471
- getX402PaymentDetails(jobId) {
3472
- return __async(this, null, function* () {
3473
- try {
3474
- const result = yield this.publicClient.readContract({
3475
- address: this.contractAddress,
3476
- abi: this.abi,
3477
- functionName: "x402PaymentDetails",
3478
- args: [BigInt(jobId)]
3479
- });
3480
- return {
3481
- isX402: result[0],
3482
- isBudgetReceived: result[1]
3483
- };
3484
- } catch (error) {
3485
- throw new acpError_default("Failed to get X402 payment details", error);
3486
- }
3487
- });
3731
+ async getX402PaymentDetails(jobId) {
3732
+ try {
3733
+ const result = await this.publicClient.readContract({
3734
+ address: this.contractAddress,
3735
+ abi: this.abi,
3736
+ functionName: "x402PaymentDetails",
3737
+ args: [BigInt(jobId)]
3738
+ });
3739
+ return {
3740
+ isX402: result[0],
3741
+ isBudgetReceived: result[1]
3742
+ };
3743
+ } catch (error) {
3744
+ throw new acpError_default("Failed to get X402 payment details", error);
3745
+ }
3488
3746
  }
3489
- submitTransferWithAuthorization(from, to, value, validAfter, validBefore, nonce, signature) {
3490
- return __async(this, null, function* () {
3491
- try {
3492
- const operations = [];
3493
- const data = encodeFunctionData({
3494
- abi: fiatTokenV2Abi_default,
3495
- functionName: "transferWithAuthorization",
3496
- args: [from, to, value, validAfter, validBefore, nonce, signature]
3497
- });
3498
- const payload = {
3499
- data,
3500
- contractAddress: this.config.baseFare.contractAddress
3501
- };
3502
- operations.push(payload);
3503
- return operations;
3504
- } catch (error) {
3505
- throw new acpError_default("Failed to submit TransferWithAuthorization", error);
3506
- }
3507
- });
3747
+ async submitTransferWithAuthorization(from, to, value, validAfter, validBefore, nonce, signature) {
3748
+ try {
3749
+ const operations = [];
3750
+ const data = encodeFunctionData({
3751
+ abi: fiatTokenV2Abi_default,
3752
+ functionName: "transferWithAuthorization",
3753
+ args: [from, to, value, validAfter, validBefore, nonce, signature]
3754
+ });
3755
+ const payload = {
3756
+ data,
3757
+ contractAddress: this.config.baseFare.contractAddress
3758
+ };
3759
+ operations.push(payload);
3760
+ return operations;
3761
+ } catch (error) {
3762
+ throw new acpError_default("Failed to submit TransferWithAuthorization", error);
3763
+ }
3508
3764
  }
3509
3765
  };
3510
3766
  var baseAcpContractClient_default = BaseAcpContractClient;
@@ -3572,29 +3828,8 @@ function safeBase64Encode(data) {
3572
3828
  }
3573
3829
 
3574
3830
  // src/acpJobOffering.ts
3575
- import { zeroAddress } from "viem";
3831
+ import { zeroAddress as zeroAddress2 } from "viem";
3576
3832
  import Ajv from "ajv";
3577
-
3578
- // src/constants.ts
3579
- import { base as base2, baseSepolia as baseSepolia2 } from "viem/chains";
3580
- var USDC_TOKEN_ADDRESS = {
3581
- [baseSepolia2.id]: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
3582
- [base2.id]: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
3583
- };
3584
- var X402AuthorizationTypes = [
3585
- { name: "from", type: "address" },
3586
- { name: "to", type: "address" },
3587
- { name: "value", type: "uint256" },
3588
- { name: "validAfter", type: "uint256" },
3589
- { name: "validBefore", type: "uint256" },
3590
- { name: "nonce", type: "bytes32" }
3591
- ];
3592
- var HTTP_STATUS_CODES = {
3593
- OK: 200,
3594
- PAYMENT_REQUIRED: 402
3595
- };
3596
-
3597
- // src/acpJobOffering.ts
3598
3833
  var AcpJobOffering = class {
3599
3834
  constructor(acpClient, acpContractClient, providerAddress, name, price, priceType = "fixed" /* FIXED */, requirement) {
3600
3835
  this.acpClient = acpClient;
@@ -3606,89 +3841,87 @@ var AcpJobOffering = class {
3606
3841
  this.requirement = requirement;
3607
3842
  this.ajv = new Ajv({ allErrors: true });
3608
3843
  }
3609
- initiateJob(_0, _1) {
3610
- return __async(this, arguments, function* (serviceRequirement, evaluatorAddress, expiredAt = new Date(Date.now() + 1e3 * 60 * 60 * 24)) {
3611
- if (this.requirement && typeof this.requirement === "object") {
3612
- const validator = this.ajv.compile(this.requirement);
3613
- const valid = validator(serviceRequirement);
3614
- if (!valid) {
3615
- throw new acpError_default(this.ajv.errorsText(validator.errors));
3616
- }
3844
+ async initiateJob(serviceRequirement, evaluatorAddress, expiredAt = new Date(Date.now() + 1e3 * 60 * 60 * 24)) {
3845
+ if (this.requirement && typeof this.requirement === "object") {
3846
+ const validator = this.ajv.compile(this.requirement);
3847
+ const valid = validator(serviceRequirement);
3848
+ if (!valid) {
3849
+ throw new acpError_default(this.ajv.errorsText(validator.errors));
3617
3850
  }
3618
- const finalServiceRequirement = {
3619
- name: this.name,
3620
- requirement: serviceRequirement,
3621
- priceValue: this.price,
3622
- priceType: this.priceType
3623
- };
3624
- const fareAmount = new FareAmount(
3625
- this.priceType === "fixed" /* FIXED */ ? this.price : 0,
3626
- this.acpContractClient.config.baseFare
3627
- );
3628
- const account = yield this.acpClient.getByClientAndProvider(
3629
- this.acpContractClient.walletAddress,
3851
+ }
3852
+ const finalServiceRequirement = {
3853
+ name: this.name,
3854
+ requirement: serviceRequirement,
3855
+ priceValue: this.price,
3856
+ priceType: this.priceType
3857
+ };
3858
+ const fareAmount = new FareAmount(
3859
+ this.priceType === "fixed" /* FIXED */ ? this.price : 0,
3860
+ this.acpContractClient.config.baseFare
3861
+ );
3862
+ const account = await this.acpClient.getByClientAndProvider(
3863
+ this.acpContractClient.walletAddress,
3864
+ this.providerAddress,
3865
+ this.acpContractClient
3866
+ );
3867
+ const isV1 = [
3868
+ baseSepoliaAcpConfig.contractAddress,
3869
+ baseSepoliaAcpX402Config.contractAddress,
3870
+ baseAcpConfig.contractAddress,
3871
+ baseAcpX402Config.contractAddress
3872
+ ].includes(this.acpContractClient.config.contractAddress);
3873
+ let createJobPayload;
3874
+ const chainId = this.acpContractClient.config.chain.id;
3875
+ const isUsdcPaymentToken = USDC_TOKEN_ADDRESS[chainId].toLowerCase() === fareAmount.fare.contractAddress.toLowerCase();
3876
+ const isX402Job = this.acpContractClient.config.x402Config && isUsdcPaymentToken;
3877
+ if (isV1 || !account) {
3878
+ createJobPayload = this.acpContractClient.createJob(
3630
3879
  this.providerAddress,
3631
- this.acpContractClient
3632
- );
3633
- const isV1 = [
3634
- baseSepoliaAcpConfig.contractAddress,
3635
- baseSepoliaAcpX402Config.contractAddress,
3636
- baseAcpConfig.contractAddress,
3637
- baseAcpX402Config.contractAddress
3638
- ].includes(this.acpContractClient.config.contractAddress);
3639
- let createJobPayload;
3640
- const chainId = this.acpContractClient.config.chain.id;
3641
- const isUsdcPaymentToken = USDC_TOKEN_ADDRESS[chainId].toLowerCase() === fareAmount.fare.contractAddress.toLowerCase();
3642
- const isX402Job = this.acpContractClient.config.x402Config && isUsdcPaymentToken;
3643
- if (isV1 || !account) {
3644
- createJobPayload = this.acpContractClient.createJob(
3645
- this.providerAddress,
3646
- evaluatorAddress || this.acpContractClient.walletAddress,
3647
- expiredAt,
3648
- fareAmount.fare.contractAddress,
3649
- fareAmount.amount,
3650
- "",
3651
- isX402Job
3652
- );
3653
- } else {
3654
- createJobPayload = this.acpContractClient.createJobWithAccount(
3655
- account.id,
3656
- evaluatorAddress || zeroAddress,
3657
- fareAmount.amount,
3658
- fareAmount.fare.contractAddress,
3659
- expiredAt,
3660
- isX402Job
3661
- );
3662
- }
3663
- const { userOpHash } = yield this.acpContractClient.handleOperation([
3664
- createJobPayload
3665
- ]);
3666
- const jobId = yield this.acpContractClient.getJobId(
3667
- userOpHash,
3668
- this.acpContractClient.walletAddress,
3669
- this.providerAddress
3670
- );
3671
- const payloads = [];
3672
- const setBudgetWithPaymentTokenPayload = this.acpContractClient.setBudgetWithPaymentToken(
3673
- jobId,
3880
+ evaluatorAddress || this.acpContractClient.walletAddress,
3881
+ expiredAt,
3882
+ fareAmount.fare.contractAddress,
3674
3883
  fareAmount.amount,
3675
- fareAmount.fare.contractAddress
3884
+ "",
3885
+ isX402Job
3676
3886
  );
3677
- if (setBudgetWithPaymentTokenPayload) {
3678
- payloads.push(setBudgetWithPaymentTokenPayload);
3679
- }
3680
- payloads.push(
3681
- this.acpContractClient.createMemo(
3682
- jobId,
3683
- JSON.stringify(finalServiceRequirement),
3684
- 0 /* MESSAGE */,
3685
- true,
3686
- 1 /* NEGOTIATION */
3687
- )
3887
+ } else {
3888
+ createJobPayload = this.acpContractClient.createJobWithAccount(
3889
+ account.id,
3890
+ evaluatorAddress || zeroAddress2,
3891
+ fareAmount.amount,
3892
+ fareAmount.fare.contractAddress,
3893
+ expiredAt,
3894
+ isX402Job
3688
3895
  );
3689
- yield this.acpContractClient.handleOperation(payloads);
3690
- return jobId;
3691
- });
3896
+ }
3897
+ const { userOpHash } = await this.acpContractClient.handleOperation([
3898
+ createJobPayload
3899
+ ]);
3900
+ const jobId = await this.acpContractClient.getJobId(
3901
+ userOpHash,
3902
+ this.acpContractClient.walletAddress,
3903
+ this.providerAddress
3904
+ );
3905
+ const payloads = [];
3906
+ const setBudgetWithPaymentTokenPayload = this.acpContractClient.setBudgetWithPaymentToken(
3907
+ jobId,
3908
+ fareAmount.amount,
3909
+ fareAmount.fare.contractAddress
3910
+ );
3911
+ if (setBudgetWithPaymentTokenPayload) {
3912
+ payloads.push(setBudgetWithPaymentTokenPayload);
3913
+ }
3914
+ payloads.push(
3915
+ this.acpContractClient.createMemo(
3916
+ jobId,
3917
+ JSON.stringify(finalServiceRequirement),
3918
+ 0 /* MESSAGE */,
3919
+ true,
3920
+ 1 /* NEGOTIATION */
3921
+ )
3922
+ );
3923
+ await this.acpContractClient.handleOperation(payloads);
3924
+ return jobId;
3692
3925
  }
3693
3926
  };
3694
3927
  var acpJobOffering_default = AcpJobOffering;
@@ -3710,10 +3943,9 @@ var AcpJob = class {
3710
3943
  this.netPayableAmount = netPayableAmount;
3711
3944
  this.priceType = "fixed" /* FIXED */;
3712
3945
  this.priceValue = 0;
3713
- var _a;
3714
- const content = (_a = this.memos.find(
3946
+ const content = this.memos.find(
3715
3947
  (m) => m.nextPhase === 1 /* NEGOTIATION */
3716
- )) == null ? void 0 : _a.content;
3948
+ )?.content;
3717
3949
  if (!content) {
3718
3950
  return;
3719
3951
  }
@@ -3744,18 +3976,16 @@ var AcpJob = class {
3744
3976
  return this.acpContractClient.config.baseFare;
3745
3977
  }
3746
3978
  get deliverable() {
3747
- var _a;
3748
- return (_a = this.memos.find((m) => m.nextPhase === 4 /* COMPLETED */)) == null ? void 0 : _a.content;
3979
+ return this.memos.find((m) => m.nextPhase === 4 /* COMPLETED */)?.content;
3749
3980
  }
3750
3981
  get rejectionReason() {
3751
- var _a;
3752
3982
  const requestMemo = this.memos.find(
3753
3983
  (m) => m.nextPhase === 1 /* NEGOTIATION */ && m.status === "REJECTED" /* REJECTED */
3754
3984
  );
3755
3985
  if (requestMemo) {
3756
3986
  return requestMemo.signedReason;
3757
3987
  }
3758
- return (_a = this.memos.find((m) => m.nextPhase === 5 /* REJECTED */)) == null ? void 0 : _a.content;
3988
+ return this.memos.find((m) => m.nextPhase === 5 /* REJECTED */)?.content;
3759
3989
  }
3760
3990
  get providerAgent() {
3761
3991
  return this.acpClient.getAgent(this.providerAddress);
@@ -3772,337 +4002,311 @@ var AcpJob = class {
3772
4002
  get latestMemo() {
3773
4003
  return this.memos[this.memos.length - 1];
3774
4004
  }
3775
- createRequirement(content) {
3776
- return __async(this, null, function* () {
3777
- const operations = [];
3778
- operations.push(
3779
- this.acpContractClient.createMemo(
3780
- this.id,
3781
- content,
3782
- 0 /* MESSAGE */,
3783
- true,
3784
- 2 /* TRANSACTION */
3785
- )
3786
- );
3787
- return yield this.acpContractClient.handleOperation(operations);
3788
- });
4005
+ async createRequirement(content) {
4006
+ const operations = [];
4007
+ operations.push(
4008
+ this.acpContractClient.createMemo(
4009
+ this.id,
4010
+ content,
4011
+ 0 /* MESSAGE */,
4012
+ true,
4013
+ 2 /* TRANSACTION */
4014
+ )
4015
+ );
4016
+ return await this.acpContractClient.handleOperation(operations);
3789
4017
  }
3790
- createPayableRequirement(_0, _1, _2, _3) {
3791
- return __async(this, arguments, function* (content, type, amount, recipient, expiredAt = new Date(Date.now() + 1e3 * 60 * 5)) {
3792
- const operations = [];
3793
- if (type === 8 /* PAYABLE_TRANSFER_ESCROW */) {
3794
- operations.push(
3795
- this.acpContractClient.approveAllowance(
3796
- amount.amount,
3797
- amount.fare.contractAddress
3798
- )
3799
- );
3800
- }
3801
- const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
4018
+ async createPayableRequirement(content, type, amount, recipient, expiredAt = new Date(Date.now() + 1e3 * 60 * 5)) {
4019
+ const operations = [];
4020
+ if (type === 8 /* PAYABLE_TRANSFER_ESCROW */) {
3802
4021
  operations.push(
3803
- this.acpContractClient.createPayableMemo(
3804
- this.id,
3805
- content,
4022
+ this.acpContractClient.approveAllowance(
3806
4023
  amount.amount,
3807
- recipient,
3808
- this.priceType === "percentage" /* PERCENTAGE */ ? BigInt(Math.round(this.priceValue * 1e4)) : feeAmount.amount,
3809
- this.priceType === "percentage" /* PERCENTAGE */ ? 3 /* PERCENTAGE_FEE */ : 0 /* NO_FEE */,
3810
- 2 /* TRANSACTION */,
3811
- type,
3812
- expiredAt,
3813
4024
  amount.fare.contractAddress
3814
4025
  )
3815
4026
  );
3816
- return yield this.acpContractClient.handleOperation(operations);
3817
- });
4027
+ }
4028
+ const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
4029
+ const isPercentagePricing = this.priceType === "percentage" /* PERCENTAGE */;
4030
+ operations.push(
4031
+ this.acpContractClient.createPayableMemo(
4032
+ this.id,
4033
+ content,
4034
+ amount.amount,
4035
+ recipient,
4036
+ isPercentagePricing ? BigInt(Math.round(this.priceValue * 1e4)) : feeAmount.amount,
4037
+ isPercentagePricing ? 3 /* PERCENTAGE_FEE */ : 0 /* NO_FEE */,
4038
+ 2 /* TRANSACTION */,
4039
+ type,
4040
+ expiredAt,
4041
+ amount.fare.contractAddress
4042
+ )
4043
+ );
4044
+ return await this.acpContractClient.handleOperation(operations);
3818
4045
  }
3819
- payAndAcceptRequirement(reason) {
3820
- return __async(this, null, function* () {
3821
- const memo = this.memos.find(
3822
- (m) => m.nextPhase === 2 /* TRANSACTION */
3823
- );
3824
- if (!memo) {
3825
- throw new acpError_default("No notification memo found");
3826
- }
3827
- const operations = [];
3828
- const baseFareAmount = new FareAmount(this.price, this.baseFare);
3829
- const transferAmount = memo.payableDetails ? yield FareAmountBase.fromContractAddress(
3830
- memo.payableDetails.amount,
3831
- memo.payableDetails.token,
3832
- this.config
3833
- ) : new FareAmount(0, this.baseFare);
3834
- const totalAmount = baseFareAmount.fare.contractAddress === transferAmount.fare.contractAddress ? baseFareAmount.add(transferAmount) : baseFareAmount;
4046
+ async payAndAcceptRequirement(reason) {
4047
+ const memo = this.memos.find(
4048
+ (m) => m.nextPhase === 2 /* TRANSACTION */
4049
+ );
4050
+ if (!memo) {
4051
+ throw new acpError_default("No notification memo found");
4052
+ }
4053
+ const operations = [];
4054
+ const baseFareAmount = new FareAmount(this.price, this.baseFare);
4055
+ const transferAmount = memo.payableDetails ? await FareAmountBase.fromContractAddress(
4056
+ memo.payableDetails.amount,
4057
+ memo.payableDetails.token,
4058
+ this.config
4059
+ ) : new FareAmount(0, this.baseFare);
4060
+ const totalAmount = baseFareAmount.fare.contractAddress === transferAmount.fare.contractAddress ? baseFareAmount.add(transferAmount) : baseFareAmount;
4061
+ operations.push(
4062
+ this.acpContractClient.approveAllowance(
4063
+ totalAmount.amount,
4064
+ this.baseFare.contractAddress
4065
+ )
4066
+ );
4067
+ if (baseFareAmount.fare.contractAddress !== transferAmount.fare.contractAddress) {
3835
4068
  operations.push(
3836
4069
  this.acpContractClient.approveAllowance(
3837
- totalAmount.amount,
3838
- this.baseFare.contractAddress
4070
+ transferAmount.amount,
4071
+ transferAmount.fare.contractAddress
3839
4072
  )
3840
4073
  );
3841
- if (baseFareAmount.fare.contractAddress !== transferAmount.fare.contractAddress) {
3842
- operations.push(
3843
- this.acpContractClient.approveAllowance(
3844
- transferAmount.amount,
3845
- transferAmount.fare.contractAddress
3846
- )
3847
- );
3848
- }
3849
- operations.push(this.acpContractClient.signMemo(memo.id, true, reason));
3850
- operations.push(
3851
- this.acpContractClient.createMemo(
3852
- this.id,
3853
- `Payment made. ${reason != null ? reason : ""}`.trim(),
3854
- 0 /* MESSAGE */,
3855
- true,
3856
- 3 /* EVALUATION */
3857
- )
3858
- );
3859
- const x402PaymentDetails = yield this.acpContractClient.getX402PaymentDetails(this.id);
3860
- if (x402PaymentDetails.isX402) {
3861
- yield this.performX402Payment(this.price);
3862
- }
3863
- return yield this.acpContractClient.handleOperation(operations);
3864
- });
4074
+ }
4075
+ operations.push(this.acpContractClient.signMemo(memo.id, true, reason));
4076
+ operations.push(
4077
+ this.acpContractClient.createMemo(
4078
+ this.id,
4079
+ `Payment made. ${reason ?? ""}`.trim(),
4080
+ 0 /* MESSAGE */,
4081
+ true,
4082
+ 3 /* EVALUATION */
4083
+ )
4084
+ );
4085
+ const x402PaymentDetails = await this.acpContractClient.getX402PaymentDetails(this.id);
4086
+ if (x402PaymentDetails.isX402) {
4087
+ await this.performX402Payment(this.price);
4088
+ }
4089
+ return await this.acpContractClient.handleOperation(operations);
3865
4090
  }
3866
- respond(accept, reason) {
3867
- return __async(this, null, function* () {
3868
- const memoContent = `${reason || `Job ${this.id} ${accept ? "accepted" : "rejected"}.`}`;
3869
- if (accept) {
3870
- yield this.accept(memoContent);
3871
- return this.createRequirement(memoContent);
3872
- }
3873
- return yield this.reject(memoContent);
3874
- });
4091
+ async respond(accept, reason) {
4092
+ const memoContent = `${reason || `Job ${this.id} ${accept ? "accepted" : "rejected"}.`}`;
4093
+ if (accept) {
4094
+ await this.accept(memoContent);
4095
+ return this.createRequirement(memoContent);
4096
+ }
4097
+ return await this.reject(memoContent);
4098
+ }
4099
+ async accept(reason) {
4100
+ const memoContent = `Job ${this.id} accepted. ${reason || ""}`;
4101
+ const latestMemo = this.latestMemo;
4102
+ if (latestMemo?.nextPhase !== 1 /* NEGOTIATION */) {
4103
+ throw new acpError_default("No request memo found");
4104
+ }
4105
+ return await latestMemo.sign(true, memoContent);
3875
4106
  }
3876
- accept(reason) {
3877
- return __async(this, null, function* () {
3878
- const memoContent = `Job ${this.id} accepted. ${reason || ""}`;
4107
+ async reject(reason) {
4108
+ const memoContent = `Job ${this.id} rejected. ${reason || ""}`;
4109
+ if (this.phase === 0 /* REQUEST */) {
3879
4110
  const latestMemo = this.latestMemo;
3880
- if ((latestMemo == null ? void 0 : latestMemo.nextPhase) !== 1 /* NEGOTIATION */) {
4111
+ if (latestMemo?.nextPhase !== 1 /* NEGOTIATION */) {
3881
4112
  throw new acpError_default("No request memo found");
3882
4113
  }
3883
- return yield latestMemo.sign(true, memoContent);
3884
- });
3885
- }
3886
- reject(reason) {
3887
- return __async(this, null, function* () {
3888
- const memoContent = `Job ${this.id} rejected. ${reason || ""}`;
3889
- if (this.phase === 0 /* REQUEST */) {
3890
- const latestMemo = this.latestMemo;
3891
- if ((latestMemo == null ? void 0 : latestMemo.nextPhase) !== 1 /* NEGOTIATION */) {
3892
- throw new acpError_default("No request memo found");
3893
- }
3894
- return yield latestMemo.sign(false, memoContent);
3895
- }
3896
- const operations = [];
3897
- operations.push(
3898
- this.acpContractClient.createMemo(
3899
- this.id,
3900
- memoContent,
3901
- 0 /* MESSAGE */,
3902
- true,
3903
- 5 /* REJECTED */
3904
- )
3905
- );
3906
- return yield this.acpContractClient.handleOperation(operations);
3907
- });
4114
+ return await latestMemo.sign(false, memoContent);
4115
+ }
4116
+ const operations = [];
4117
+ operations.push(
4118
+ this.acpContractClient.createMemo(
4119
+ this.id,
4120
+ memoContent,
4121
+ 0 /* MESSAGE */,
4122
+ true,
4123
+ 5 /* REJECTED */
4124
+ )
4125
+ );
4126
+ return await this.acpContractClient.handleOperation(operations);
3908
4127
  }
3909
- rejectPayable() {
3910
- return __async(this, arguments, function* (reason = "", amount, expiredAt = new Date(Date.now() + 1e3 * 60 * 5)) {
3911
- const memoContent = `Job ${this.id} rejected. ${reason}`;
3912
- const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
3913
- const operations = [];
3914
- operations.push(
3915
- this.acpContractClient.approveAllowance(
3916
- amount.amount,
3917
- amount.fare.contractAddress
3918
- )
3919
- );
3920
- operations.push(
3921
- this.acpContractClient.createPayableMemo(
3922
- this.id,
3923
- memoContent,
3924
- amount.amount,
3925
- this.clientAddress,
3926
- feeAmount.amount,
3927
- 0 /* NO_FEE */,
3928
- 5 /* REJECTED */,
3929
- 7 /* PAYABLE_TRANSFER */,
3930
- expiredAt,
3931
- amount.fare.contractAddress
3932
- )
3933
- );
3934
- return yield this.acpContractClient.handleOperation(operations);
3935
- });
4128
+ async rejectPayable(reason = "", amount, expiredAt = new Date(Date.now() + 1e3 * 60 * 5)) {
4129
+ const memoContent = `Job ${this.id} rejected. ${reason}`;
4130
+ const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
4131
+ const operations = [];
4132
+ operations.push(
4133
+ this.acpContractClient.approveAllowance(
4134
+ amount.amount,
4135
+ amount.fare.contractAddress
4136
+ )
4137
+ );
4138
+ operations.push(
4139
+ this.acpContractClient.createPayableMemo(
4140
+ this.id,
4141
+ memoContent,
4142
+ amount.amount,
4143
+ this.clientAddress,
4144
+ feeAmount.amount,
4145
+ 0 /* NO_FEE */,
4146
+ 5 /* REJECTED */,
4147
+ 7 /* PAYABLE_TRANSFER */,
4148
+ expiredAt,
4149
+ amount.fare.contractAddress
4150
+ )
4151
+ );
4152
+ return await this.acpContractClient.handleOperation(operations);
3936
4153
  }
3937
- deliver(deliverable) {
3938
- return __async(this, null, function* () {
3939
- var _a;
3940
- if (((_a = this.latestMemo) == null ? void 0 : _a.nextPhase) !== 3 /* EVALUATION */) {
3941
- throw new acpError_default("No transaction memo found");
3942
- }
3943
- const operations = [];
3944
- operations.push(
3945
- this.acpContractClient.createMemo(
3946
- this.id,
3947
- preparePayload(deliverable),
3948
- 0 /* MESSAGE */,
3949
- true,
3950
- 4 /* COMPLETED */
3951
- )
3952
- );
3953
- return yield this.acpContractClient.handleOperation(operations);
3954
- });
4154
+ async deliver(deliverable) {
4155
+ if (this.latestMemo?.nextPhase !== 3 /* EVALUATION */) {
4156
+ throw new acpError_default("No transaction memo found");
4157
+ }
4158
+ const operations = [];
4159
+ operations.push(
4160
+ this.acpContractClient.createMemo(
4161
+ this.id,
4162
+ preparePayload(deliverable),
4163
+ 0 /* MESSAGE */,
4164
+ true,
4165
+ 4 /* COMPLETED */
4166
+ )
4167
+ );
4168
+ return await this.acpContractClient.handleOperation(operations);
3955
4169
  }
3956
- deliverPayable(_0, _1) {
3957
- return __async(this, arguments, function* (deliverable, amount, expiredAt = new Date(Date.now() + 1e3 * 60 * 5)) {
3958
- var _a;
3959
- if (((_a = this.latestMemo) == null ? void 0 : _a.nextPhase) !== 3 /* EVALUATION */) {
3960
- throw new acpError_default("No transaction memo found");
3961
- }
3962
- const operations = [];
3963
- operations.push(
3964
- this.acpContractClient.approveAllowance(
3965
- amount.amount,
3966
- amount.fare.contractAddress
3967
- )
3968
- );
3969
- const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
3970
- operations.push(
3971
- this.acpContractClient.createPayableMemo(
3972
- this.id,
3973
- preparePayload(deliverable),
3974
- amount.amount,
3975
- this.clientAddress,
3976
- feeAmount.amount,
3977
- 0 /* NO_FEE */,
3978
- 4 /* COMPLETED */,
3979
- 7 /* PAYABLE_TRANSFER */,
3980
- expiredAt,
3981
- amount.fare.contractAddress
3982
- )
3983
- );
3984
- return yield this.acpContractClient.handleOperation(operations);
3985
- });
4170
+ async deliverPayable(deliverable, amount, skipFee = false, expiredAt = new Date(Date.now() + 1e3 * 60 * 5)) {
4171
+ if (this.latestMemo?.nextPhase !== 3 /* EVALUATION */) {
4172
+ throw new acpError_default("No transaction memo found");
4173
+ }
4174
+ const operations = [];
4175
+ operations.push(
4176
+ this.acpContractClient.approveAllowance(
4177
+ amount.amount,
4178
+ amount.fare.contractAddress
4179
+ )
4180
+ );
4181
+ const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
4182
+ const isPercentagePricing = this.priceType === "percentage" /* PERCENTAGE */ && !skipFee;
4183
+ operations.push(
4184
+ this.acpContractClient.createPayableMemo(
4185
+ this.id,
4186
+ preparePayload(deliverable),
4187
+ amount.amount,
4188
+ this.clientAddress,
4189
+ isPercentagePricing ? BigInt(Math.round(this.priceValue * 1e4)) : feeAmount.amount,
4190
+ isPercentagePricing ? 3 /* PERCENTAGE_FEE */ : 0 /* NO_FEE */,
4191
+ 4 /* COMPLETED */,
4192
+ 7 /* PAYABLE_TRANSFER */,
4193
+ expiredAt,
4194
+ amount.fare.contractAddress
4195
+ )
4196
+ );
4197
+ return await this.acpContractClient.handleOperation(operations);
3986
4198
  }
3987
- evaluate(accept, reason) {
3988
- return __async(this, null, function* () {
3989
- var _a;
3990
- if (((_a = this.latestMemo) == null ? void 0 : _a.nextPhase) !== 4 /* COMPLETED */) {
3991
- throw new acpError_default("No evaluation memo found");
3992
- }
3993
- const memo = this.latestMemo;
3994
- yield memo.sign(accept, reason);
3995
- });
4199
+ async evaluate(accept, reason) {
4200
+ if (this.latestMemo?.nextPhase !== 4 /* COMPLETED */) {
4201
+ throw new acpError_default("No evaluation memo found");
4202
+ }
4203
+ const memo = this.latestMemo;
4204
+ await memo.sign(accept, reason);
3996
4205
  }
3997
- createNotification(content) {
3998
- return __async(this, null, function* () {
3999
- const operations = [];
4000
- operations.push(
4001
- this.acpContractClient.createMemo(
4002
- this.id,
4003
- content,
4004
- 9 /* NOTIFICATION */,
4005
- true,
4006
- 4 /* COMPLETED */
4007
- )
4008
- );
4009
- return yield this.acpContractClient.handleOperation(operations);
4010
- });
4206
+ async createNotification(content) {
4207
+ const operations = [];
4208
+ operations.push(
4209
+ this.acpContractClient.createMemo(
4210
+ this.id,
4211
+ content,
4212
+ 9 /* NOTIFICATION */,
4213
+ true,
4214
+ 4 /* COMPLETED */
4215
+ )
4216
+ );
4217
+ return await this.acpContractClient.handleOperation(operations);
4011
4218
  }
4012
- createPayableNotification(_0, _1) {
4013
- return __async(this, arguments, function* (content, amount, expiredAt = new Date(Date.now() + 1e3 * 60 * 5)) {
4014
- const operations = [];
4015
- operations.push(
4016
- this.acpContractClient.approveAllowance(
4017
- amount.amount,
4018
- amount.fare.contractAddress
4019
- )
4020
- );
4021
- const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
4022
- operations.push(
4023
- this.acpContractClient.createPayableMemo(
4024
- this.id,
4025
- content,
4026
- amount.amount,
4027
- this.clientAddress,
4028
- feeAmount.amount,
4029
- 0 /* NO_FEE */,
4030
- 4 /* COMPLETED */,
4031
- 10 /* PAYABLE_NOTIFICATION */,
4032
- expiredAt,
4033
- amount.fare.contractAddress
4034
- )
4035
- );
4036
- return yield this.acpContractClient.handleOperation(operations);
4037
- });
4219
+ async createPayableNotification(content, amount, skipFee = false, expiredAt = new Date(Date.now() + 1e3 * 60 * 5)) {
4220
+ const operations = [];
4221
+ operations.push(
4222
+ this.acpContractClient.approveAllowance(
4223
+ amount.amount,
4224
+ amount.fare.contractAddress
4225
+ )
4226
+ );
4227
+ const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
4228
+ const isPercentagePricing = this.priceType === "percentage" /* PERCENTAGE */ && !skipFee;
4229
+ operations.push(
4230
+ this.acpContractClient.createPayableMemo(
4231
+ this.id,
4232
+ content,
4233
+ amount.amount,
4234
+ this.clientAddress,
4235
+ isPercentagePricing ? BigInt(Math.round(this.priceValue * 1e4)) : feeAmount.amount,
4236
+ isPercentagePricing ? 3 /* PERCENTAGE_FEE */ : 0 /* NO_FEE */,
4237
+ 4 /* COMPLETED */,
4238
+ 10 /* PAYABLE_NOTIFICATION */,
4239
+ expiredAt,
4240
+ amount.fare.contractAddress
4241
+ )
4242
+ );
4243
+ return await this.acpContractClient.handleOperation(operations);
4038
4244
  }
4039
- performX402Payment(budget) {
4040
- return __async(this, null, function* () {
4041
- const paymentUrl = "/acp-budget";
4042
- const x402PayableREquirements = yield this.acpContractClient.performX402Request(
4043
- paymentUrl,
4044
- this.acpContractClient.getAcpVersion(),
4045
- budget.toString()
4046
- );
4047
- if (!x402PayableREquirements.isPaymentRequired) {
4048
- return;
4049
- }
4050
- if (!x402PayableREquirements.data.accepts.length) {
4051
- throw new acpError_default("No X402 payment requirements found");
4052
- }
4053
- const requirement = x402PayableREquirements.data.accepts[0];
4054
- const { encodedPayment, signature, message } = yield this.acpContractClient.generateX402Payment(
4055
- {
4056
- to: requirement.payTo,
4057
- value: Number(requirement.maxAmountRequired),
4058
- maxTimeoutSeconds: requirement.maxTimeoutSeconds,
4059
- asset: requirement.asset
4060
- },
4061
- x402PayableREquirements.data
4062
- );
4063
- yield this.acpContractClient.updateJobX402Nonce(this.id, message.nonce);
4064
- const x402Response = yield this.acpContractClient.performX402Request(
4065
- paymentUrl,
4066
- this.acpContractClient.getAcpVersion(),
4067
- budget.toString(),
4068
- encodedPayment
4245
+ async performX402Payment(budget) {
4246
+ const paymentUrl = "/acp-budget";
4247
+ const x402PayableREquirements = await this.acpContractClient.performX402Request(
4248
+ paymentUrl,
4249
+ this.acpContractClient.getAcpVersion(),
4250
+ budget.toString()
4251
+ );
4252
+ if (!x402PayableREquirements.isPaymentRequired) {
4253
+ return;
4254
+ }
4255
+ if (!x402PayableREquirements.data.accepts.length) {
4256
+ throw new acpError_default("No X402 payment requirements found");
4257
+ }
4258
+ const requirement = x402PayableREquirements.data.accepts[0];
4259
+ const { encodedPayment, signature, message } = await this.acpContractClient.generateX402Payment(
4260
+ {
4261
+ to: requirement.payTo,
4262
+ value: Number(requirement.maxAmountRequired),
4263
+ maxTimeoutSeconds: requirement.maxTimeoutSeconds,
4264
+ asset: requirement.asset
4265
+ },
4266
+ x402PayableREquirements.data
4267
+ );
4268
+ await this.acpContractClient.updateJobX402Nonce(this.id, message.nonce);
4269
+ const x402Response = await this.acpContractClient.performX402Request(
4270
+ paymentUrl,
4271
+ this.acpContractClient.getAcpVersion(),
4272
+ budget.toString(),
4273
+ encodedPayment
4274
+ );
4275
+ if (x402Response.isPaymentRequired) {
4276
+ const operations = await this.acpContractClient.submitTransferWithAuthorization(
4277
+ message.from,
4278
+ message.to,
4279
+ BigInt(message.value),
4280
+ BigInt(message.validAfter),
4281
+ BigInt(message.validBefore),
4282
+ message.nonce,
4283
+ signature
4069
4284
  );
4070
- if (x402Response.isPaymentRequired) {
4071
- const operations = yield this.acpContractClient.submitTransferWithAuthorization(
4072
- message.from,
4073
- message.to,
4074
- BigInt(message.value),
4075
- BigInt(message.validAfter),
4076
- BigInt(message.validBefore),
4077
- message.nonce,
4078
- signature
4079
- );
4080
- yield this.acpContractClient.handleOperation(operations);
4285
+ await this.acpContractClient.handleOperation(operations);
4286
+ }
4287
+ let waitMs = 2e3;
4288
+ const maxWaitMs = 3e4;
4289
+ let iterationCount = 0;
4290
+ const maxIterations = 10;
4291
+ while (true) {
4292
+ const x402PaymentDetails = await this.acpContractClient.getX402PaymentDetails(this.id);
4293
+ if (x402PaymentDetails.isBudgetReceived) {
4294
+ break;
4081
4295
  }
4082
- let waitMs = 2e3;
4083
- const maxWaitMs = 3e4;
4084
- let iterationCount = 0;
4085
- const maxIterations = 10;
4086
- while (true) {
4087
- const x402PaymentDetails = yield this.acpContractClient.getX402PaymentDetails(this.id);
4088
- if (x402PaymentDetails.isBudgetReceived) {
4089
- break;
4090
- }
4091
- iterationCount++;
4092
- if (iterationCount >= maxIterations) {
4093
- throw new acpError_default("X402 payment timed out");
4094
- }
4095
- yield new Promise((resolve) => setTimeout(resolve, waitMs));
4096
- waitMs = Math.min(waitMs * 2, maxWaitMs);
4296
+ iterationCount++;
4297
+ if (iterationCount >= maxIterations) {
4298
+ throw new acpError_default("X402 payment timed out");
4097
4299
  }
4098
- });
4300
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
4301
+ waitMs = Math.min(waitMs * 2, maxWaitMs);
4302
+ }
4099
4303
  }
4100
4304
  };
4101
4305
  var acpJob_default = AcpJob;
4102
4306
 
4103
4307
  // src/acpMemo.ts
4104
4308
  var AcpMemo = class {
4105
- constructor(contractClient, id, type, content, nextPhase, status, senderAddress, signedReason, expiry, payableDetails) {
4309
+ constructor(contractClient, id, type, content, nextPhase, status, senderAddress, signedReason, expiry, payableDetails, txHash, signedTxHash) {
4106
4310
  this.contractClient = contractClient;
4107
4311
  this.id = id;
4108
4312
  this.type = type;
@@ -4113,6 +4317,8 @@ var AcpMemo = class {
4113
4317
  this.signedReason = signedReason;
4114
4318
  this.expiry = expiry;
4115
4319
  this.payableDetails = payableDetails;
4320
+ this.txHash = txHash;
4321
+ this.signedTxHash = signedTxHash;
4116
4322
  if (this.payableDetails) {
4117
4323
  this.payableDetails.amount = BigInt(this.payableDetails.amount);
4118
4324
  this.payableDetails.feeAmount = BigInt(this.payableDetails.feeAmount);
@@ -4120,28 +4326,23 @@ var AcpMemo = class {
4120
4326
  this.structuredContent = tryParseJson(this.content) || void 0;
4121
4327
  }
4122
4328
  get payloadType() {
4123
- var _a;
4124
- return (_a = this.structuredContent) == null ? void 0 : _a.type;
4329
+ return this.structuredContent?.type;
4125
4330
  }
4126
4331
  getStructuredContent() {
4127
4332
  return this.structuredContent;
4128
4333
  }
4129
- create(jobId, isSecured = true) {
4130
- return __async(this, null, function* () {
4131
- return yield this.contractClient.createMemo(
4132
- jobId,
4133
- this.content,
4134
- this.type,
4135
- isSecured,
4136
- this.nextPhase
4137
- );
4138
- });
4334
+ async create(jobId, isSecured = true) {
4335
+ return await this.contractClient.createMemo(
4336
+ jobId,
4337
+ this.content,
4338
+ this.type,
4339
+ isSecured,
4340
+ this.nextPhase
4341
+ );
4139
4342
  }
4140
- sign(approved, reason) {
4141
- return __async(this, null, function* () {
4142
- const payload = this.contractClient.signMemo(this.id, approved, reason);
4143
- return yield this.contractClient.handleOperation([payload]);
4144
- });
4343
+ async sign(approved, reason) {
4344
+ const payload = this.contractClient.signMemo(this.id, approved, reason);
4345
+ return await this.contractClient.handleOperation([payload]);
4145
4346
  }
4146
4347
  };
4147
4348
  var acpMemo_default = AcpMemo;
@@ -4155,14 +4356,12 @@ var AcpAccount = class {
4155
4356
  this.providerAddress = providerAddress;
4156
4357
  this.metadata = metadata;
4157
4358
  }
4158
- updateMetadata(metadata) {
4159
- return __async(this, null, function* () {
4160
- const hash = yield this.contractClient.updateAccountMetadata(
4161
- this.id,
4162
- JSON.stringify(metadata)
4163
- );
4164
- return hash;
4165
- });
4359
+ async updateMetadata(metadata) {
4360
+ const hash = await this.contractClient.updateAccountMetadata(
4361
+ this.id,
4362
+ JSON.stringify(metadata)
4363
+ );
4364
+ return hash;
4166
4365
  }
4167
4366
  };
4168
4367
 
@@ -4203,10 +4402,8 @@ var AcpClient = class {
4203
4402
  get acpUrl() {
4204
4403
  return this.acpContractClient.config.acpUrl;
4205
4404
  }
4206
- defaultOnEvaluate(job) {
4207
- return __async(this, null, function* () {
4208
- yield job.evaluate(true, "Evaluated by default");
4209
- });
4405
+ async defaultOnEvaluate(job) {
4406
+ await job.evaluate(true, "Evaluated by default");
4210
4407
  }
4211
4408
  get walletAddress() {
4212
4409
  if (Array.isArray(this.acpContractClient)) {
@@ -4214,267 +4411,39 @@ var AcpClient = class {
4214
4411
  }
4215
4412
  return this.acpContractClient.walletAddress;
4216
4413
  }
4217
- init() {
4218
- return __async(this, null, function* () {
4219
- const socket = io(this.acpUrl, {
4220
- auth: {
4221
- walletAddress: this.walletAddress
4222
- },
4223
- extraHeaders: {
4224
- "x-sdk-version": version,
4225
- "x-sdk-language": "node",
4226
- "x-contract-address": this.contractClients[0].contractAddress
4227
- // always prioritize the first client
4228
- },
4229
- transports: ["websocket"]
4230
- });
4231
- socket.on("roomJoined" /* ROOM_JOINED */, (_, callback) => {
4232
- console.log("Joined ACP Room");
4233
- callback(true);
4234
- });
4235
- socket.on(
4236
- "onEvaluate" /* ON_EVALUATE */,
4237
- (data, callback) => __async(this, null, function* () {
4238
- callback(true);
4239
- if (this.onEvaluate) {
4240
- const job = new acpJob_default(
4241
- this,
4242
- data.id,
4243
- data.clientAddress,
4244
- data.providerAddress,
4245
- data.evaluatorAddress,
4246
- data.price,
4247
- data.priceTokenAddress,
4248
- data.memos.map((memo) => {
4249
- return new acpMemo_default(
4250
- this.contractClientByAddress(data.contractAddress),
4251
- memo.id,
4252
- memo.memoType,
4253
- memo.content,
4254
- memo.nextPhase,
4255
- memo.status,
4256
- memo.senderAddress,
4257
- memo.signedReason,
4258
- memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4259
- memo.payableDetails
4260
- );
4261
- }),
4262
- data.phase,
4263
- data.context,
4264
- data.contractAddress,
4265
- data.netPayableAmount
4266
- );
4267
- this.onEvaluate(job);
4268
- }
4269
- })
4270
- );
4271
- socket.on(
4272
- "onNewTask" /* ON_NEW_TASK */,
4273
- (data, callback) => __async(this, null, function* () {
4274
- callback(true);
4275
- if (this.onNewTask) {
4276
- const job = new acpJob_default(
4277
- this,
4278
- data.id,
4279
- data.clientAddress,
4280
- data.providerAddress,
4281
- data.evaluatorAddress,
4282
- data.price,
4283
- data.priceTokenAddress,
4284
- data.memos.map((memo) => {
4285
- return new acpMemo_default(
4286
- this.contractClientByAddress(data.contractAddress),
4287
- memo.id,
4288
- memo.memoType,
4289
- memo.content,
4290
- memo.nextPhase,
4291
- memo.status,
4292
- memo.senderAddress,
4293
- memo.signedReason,
4294
- memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4295
- memo.payableDetails
4296
- );
4297
- }),
4298
- data.phase,
4299
- data.context,
4300
- data.contractAddress,
4301
- data.netPayableAmount
4302
- );
4303
- this.onNewTask(
4304
- job,
4305
- job.memos.find((m) => m.id == data.memoToSign)
4306
- );
4307
- }
4308
- })
4309
- );
4310
- const cleanup = () => __async(this, null, function* () {
4311
- if (socket) {
4312
- socket.disconnect();
4313
- }
4314
- process.exit(0);
4315
- });
4316
- process.on("SIGINT", cleanup);
4317
- process.on("SIGTERM", cleanup);
4318
- });
4319
- }
4320
- browseAgents(keyword, options) {
4321
- return __async(this, null, function* () {
4322
- let { cluster, sort_by, top_k, graduationStatus, onlineStatus } = options;
4323
- top_k = top_k != null ? top_k : 5;
4324
- let url = `${this.acpUrl}/api/agents/v3/search?search=${keyword}`;
4325
- if (sort_by && sort_by.length > 0) {
4326
- url += `&sortBy=${sort_by.map((s) => s).join(",")}`;
4327
- }
4328
- if (top_k) {
4329
- url += `&top_k=${top_k}`;
4330
- }
4331
- if (this.walletAddress) {
4332
- url += `&walletAddressesToExclude=${this.walletAddress}`;
4333
- }
4334
- if (cluster) {
4335
- url += `&cluster=${cluster}`;
4336
- }
4337
- if (graduationStatus) {
4338
- url += `&graduationStatus=${graduationStatus}`;
4339
- }
4340
- if (onlineStatus) {
4341
- url += `&onlineStatus=${onlineStatus}`;
4342
- }
4343
- const response = yield fetch(url);
4344
- const data = yield response.json();
4345
- const availableContractClientAddresses = this.contractClients.map(
4346
- (client) => client.contractAddress.toLowerCase()
4347
- );
4348
- return data.data.filter(
4349
- (agent) => agent.walletAddress.toLowerCase() !== this.walletAddress.toLowerCase()
4350
- ).filter(
4351
- (agent) => availableContractClientAddresses.includes(
4352
- agent.contractAddress.toLowerCase()
4353
- )
4354
- ).map((agent) => {
4355
- const acpContractClient = this.contractClients.find(
4356
- (client) => client.contractAddress.toLowerCase() === agent.contractAddress.toLowerCase()
4357
- );
4358
- if (!acpContractClient) {
4359
- throw new acpError_default("ACP contract client not found");
4360
- }
4361
- return {
4362
- id: agent.id,
4363
- name: agent.name,
4364
- description: agent.description,
4365
- jobOfferings: agent.jobs.map((jobs) => {
4366
- return new acpJobOffering_default(
4367
- this,
4368
- acpContractClient,
4369
- agent.walletAddress,
4370
- jobs.name,
4371
- jobs.priceV2.value,
4372
- jobs.priceV2.type,
4373
- jobs.requirement
4374
- );
4375
- }),
4376
- contractAddress: agent.contractAddress,
4377
- twitterHandle: agent.twitterHandle,
4378
- walletAddress: agent.walletAddress,
4379
- metrics: agent.metrics,
4380
- resource: agent.resources
4381
- };
4382
- });
4414
+ async init() {
4415
+ const socket = io(this.acpUrl, {
4416
+ auth: {
4417
+ walletAddress: this.walletAddress
4418
+ },
4419
+ extraHeaders: {
4420
+ "x-sdk-version": version,
4421
+ "x-sdk-language": "node",
4422
+ "x-contract-address": this.contractClients[0].contractAddress
4423
+ // always prioritize the first client
4424
+ },
4425
+ transports: ["websocket"]
4383
4426
  });
4384
- }
4385
- initiateJob(_0, _1, _2, _3) {
4386
- return __async(this, arguments, function* (providerAddress, serviceRequirement, fareAmount, evaluatorAddress, expiredAt = new Date(Date.now() + 1e3 * 60 * 60 * 24)) {
4387
- if (providerAddress === this.walletAddress) {
4388
- throw new acpError_default(
4389
- "Provider address cannot be the same as the client address"
4390
- );
4391
- }
4392
- const account = yield this.getByClientAndProvider(
4393
- this.walletAddress,
4394
- providerAddress,
4395
- this.acpContractClient
4396
- );
4397
- const isV1 = [
4398
- baseSepoliaAcpConfig.contractAddress,
4399
- baseSepoliaAcpX402Config.contractAddress,
4400
- baseAcpConfig.contractAddress,
4401
- baseAcpX402Config.contractAddress
4402
- ].includes(this.acpContractClient.config.contractAddress);
4403
- const defaultEvaluatorAddress = isV1 && !evaluatorAddress ? this.walletAddress : zeroAddress2;
4404
- const chainId = this.acpContractClient.config.chain.id;
4405
- const isUsdcPaymentToken = USDC_TOKEN_ADDRESS[chainId].toLowerCase() === fareAmount.fare.contractAddress.toLowerCase();
4406
- const isX402Job = this.acpContractClient.config.x402Config && isUsdcPaymentToken;
4407
- const createJobPayload = isV1 || !account ? this.acpContractClient.createJob(
4408
- providerAddress,
4409
- evaluatorAddress || defaultEvaluatorAddress,
4410
- expiredAt,
4411
- fareAmount.fare.contractAddress,
4412
- fareAmount.amount,
4413
- "",
4414
- isX402Job
4415
- ) : this.acpContractClient.createJobWithAccount(
4416
- account.id,
4417
- evaluatorAddress || defaultEvaluatorAddress,
4418
- fareAmount.amount,
4419
- fareAmount.fare.contractAddress,
4420
- expiredAt,
4421
- isX402Job
4422
- );
4423
- const { userOpHash } = yield this.acpContractClient.handleOperation([
4424
- createJobPayload
4425
- ]);
4426
- const jobId = yield this.acpContractClient.getJobId(
4427
- userOpHash,
4428
- this.walletAddress,
4429
- providerAddress
4430
- );
4431
- const payloads = [];
4432
- const setBudgetWithPaymentTokenPayload = this.acpContractClient.setBudgetWithPaymentToken(
4433
- jobId,
4434
- fareAmount.amount,
4435
- fareAmount.fare.contractAddress
4436
- );
4437
- if (setBudgetWithPaymentTokenPayload) {
4438
- payloads.push(setBudgetWithPaymentTokenPayload);
4439
- }
4440
- payloads.push(
4441
- this.acpContractClient.createMemo(
4442
- jobId,
4443
- preparePayload(serviceRequirement),
4444
- 0 /* MESSAGE */,
4445
- true,
4446
- 1 /* NEGOTIATION */
4447
- )
4448
- );
4449
- yield this.acpContractClient.handleOperation(payloads);
4450
- return jobId;
4427
+ socket.on("roomJoined" /* ROOM_JOINED */, (_, callback) => {
4428
+ console.log("Joined ACP Room");
4429
+ callback(true);
4451
4430
  });
4452
- }
4453
- getActiveJobs(page = 1, pageSize = 10) {
4454
- return __async(this, null, function* () {
4455
- let url = `${this.acpUrl}/api/jobs/active?pagination[page]=${page}&pagination[pageSize]=${pageSize}`;
4456
- try {
4457
- const response = yield fetch(url, {
4458
- headers: {
4459
- "wallet-address": this.walletAddress
4460
- }
4461
- });
4462
- const data = yield response.json();
4463
- if (data.error) {
4464
- throw new acpError_default(data.error.message);
4465
- }
4466
- return data.data.map((job) => {
4467
- return new acpJob_default(
4431
+ socket.on(
4432
+ "onEvaluate" /* ON_EVALUATE */,
4433
+ async (data, callback) => {
4434
+ callback(true);
4435
+ if (this.onEvaluate) {
4436
+ const job = new acpJob_default(
4468
4437
  this,
4469
- job.id,
4470
- job.clientAddress,
4471
- job.providerAddress,
4472
- job.evaluatorAddress,
4473
- job.price,
4474
- job.priceTokenAddress,
4475
- job.memos.map((memo) => {
4438
+ data.id,
4439
+ data.clientAddress,
4440
+ data.providerAddress,
4441
+ data.evaluatorAddress,
4442
+ data.price,
4443
+ data.priceTokenAddress,
4444
+ data.memos.map((memo) => {
4476
4445
  return new acpMemo_default(
4477
- this.contractClientByAddress(job.contractAddress),
4446
+ this.contractClientByAddress(data.contractAddress),
4478
4447
  memo.id,
4479
4448
  memo.memoType,
4480
4449
  memo.content,
@@ -4483,45 +4452,36 @@ var AcpClient = class {
4483
4452
  memo.senderAddress,
4484
4453
  memo.signedReason,
4485
4454
  memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4486
- memo.payableDetails
4455
+ memo.payableDetails,
4456
+ memo.txHash,
4457
+ memo.signedTxHash
4487
4458
  );
4488
4459
  }),
4489
- job.phase,
4490
- job.context,
4491
- job.contractAddress,
4492
- job.netPayableAmount
4460
+ data.phase,
4461
+ data.context,
4462
+ data.contractAddress,
4463
+ data.netPayableAmount
4493
4464
  );
4494
- });
4495
- } catch (error) {
4496
- throw new acpError_default("Failed to get active jobs", error);
4497
- }
4498
- });
4499
- }
4500
- getPendingMemoJobs(page = 1, pageSize = 10) {
4501
- return __async(this, null, function* () {
4502
- let url = `${this.acpUrl}/api/jobs/pending-memos?pagination[page]=${page}&pagination[pageSize]=${pageSize}`;
4503
- try {
4504
- const response = yield fetch(url, {
4505
- headers: {
4506
- "wallet-address": this.acpContractClient.walletAddress
4507
- }
4508
- });
4509
- const data = yield response.json();
4510
- if (data.error) {
4511
- throw new acpError_default(data.error.message);
4465
+ this.onEvaluate(job);
4512
4466
  }
4513
- return data.data.map((job) => {
4514
- return new acpJob_default(
4467
+ }
4468
+ );
4469
+ socket.on(
4470
+ "onNewTask" /* ON_NEW_TASK */,
4471
+ async (data, callback) => {
4472
+ callback(true);
4473
+ if (this.onNewTask) {
4474
+ const job = new acpJob_default(
4515
4475
  this,
4516
- job.id,
4517
- job.clientAddress,
4518
- job.providerAddress,
4519
- job.evaluatorAddress,
4520
- job.price,
4521
- job.priceTokenAddress,
4522
- job.memos.map((memo) => {
4476
+ data.id,
4477
+ data.clientAddress,
4478
+ data.providerAddress,
4479
+ data.evaluatorAddress,
4480
+ data.price,
4481
+ data.priceTokenAddress,
4482
+ data.memos.map((memo) => {
4523
4483
  return new acpMemo_default(
4524
- this.contractClientByAddress(job.contractAddress),
4484
+ this.contractClientByAddress(data.contractAddress),
4525
4485
  memo.id,
4526
4486
  memo.memoType,
4527
4487
  memo.content,
@@ -4530,131 +4490,268 @@ var AcpClient = class {
4530
4490
  memo.senderAddress,
4531
4491
  memo.signedReason,
4532
4492
  memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4533
- typeof memo.payableDetails === "string" ? tryParseJson(memo.payableDetails) || void 0 : memo.payableDetails
4493
+ memo.payableDetails,
4494
+ memo.txHash,
4495
+ memo.signedTxHash
4534
4496
  );
4535
4497
  }),
4536
- job.phase,
4537
- job.context,
4538
- job.contractAddress,
4539
- job.netPayableAmount
4498
+ data.phase,
4499
+ data.context,
4500
+ data.contractAddress,
4501
+ data.netPayableAmount
4540
4502
  );
4541
- });
4542
- } catch (error) {
4543
- throw new acpError_default("Failed to get pending memo jobs", error);
4503
+ this.onNewTask(
4504
+ job,
4505
+ job.memos.find((m) => m.id == data.memoToSign)
4506
+ );
4507
+ }
4544
4508
  }
4545
- });
4509
+ );
4510
+ const cleanup = async () => {
4511
+ if (socket) {
4512
+ socket.disconnect();
4513
+ }
4514
+ process.exit(0);
4515
+ };
4516
+ process.on("SIGINT", cleanup);
4517
+ process.on("SIGTERM", cleanup);
4546
4518
  }
4547
- getCompletedJobs(page = 1, pageSize = 10) {
4548
- return __async(this, null, function* () {
4549
- let url = `${this.acpUrl}/api/jobs/completed?pagination[page]=${page}&pagination[pageSize]=${pageSize}`;
4550
- try {
4551
- const response = yield fetch(url, {
4552
- headers: {
4553
- "wallet-address": this.acpContractClient.walletAddress
4554
- }
4555
- });
4556
- const data = yield response.json();
4557
- if (data.error) {
4558
- throw new acpError_default(data.error.message);
4559
- }
4560
- return data.data.map((job) => {
4561
- return new acpJob_default(
4519
+ async browseAgents(keyword, options) {
4520
+ let { cluster, sort_by, top_k, graduationStatus, onlineStatus } = options;
4521
+ top_k = top_k ?? 5;
4522
+ let url = `${this.acpUrl}/api/agents/v4/search?search=${keyword}`;
4523
+ if (sort_by && sort_by.length > 0) {
4524
+ url += `&sortBy=${sort_by.map((s) => s).join(",")}`;
4525
+ }
4526
+ if (top_k) {
4527
+ url += `&top_k=${top_k}`;
4528
+ }
4529
+ if (this.walletAddress) {
4530
+ url += `&walletAddressesToExclude=${this.walletAddress}`;
4531
+ }
4532
+ if (cluster) {
4533
+ url += `&cluster=${cluster}`;
4534
+ }
4535
+ if (graduationStatus) {
4536
+ url += `&graduationStatus=${graduationStatus}`;
4537
+ }
4538
+ if (onlineStatus) {
4539
+ url += `&onlineStatus=${onlineStatus}`;
4540
+ }
4541
+ const response = await fetch(url);
4542
+ const data = await response.json();
4543
+ const availableContractClientAddresses = this.contractClients.map(
4544
+ (client) => client.contractAddress.toLowerCase()
4545
+ );
4546
+ return data.data.filter(
4547
+ (agent) => agent.walletAddress.toLowerCase() !== this.walletAddress.toLowerCase()
4548
+ ).filter(
4549
+ (agent) => availableContractClientAddresses.includes(
4550
+ agent.contractAddress.toLowerCase()
4551
+ )
4552
+ ).map((agent) => {
4553
+ const acpContractClient = this.contractClients.find(
4554
+ (client) => client.contractAddress.toLowerCase() === agent.contractAddress.toLowerCase()
4555
+ );
4556
+ if (!acpContractClient) {
4557
+ throw new acpError_default("ACP contract client not found");
4558
+ }
4559
+ return {
4560
+ id: agent.id,
4561
+ name: agent.name,
4562
+ description: agent.description,
4563
+ jobOfferings: agent.jobs.map((jobs) => {
4564
+ return new acpJobOffering_default(
4562
4565
  this,
4563
- job.id,
4564
- job.clientAddress,
4565
- job.providerAddress,
4566
- job.evaluatorAddress,
4567
- job.price,
4568
- job.priceTokenAddress,
4569
- job.memos.map((memo) => {
4570
- return new acpMemo_default(
4571
- this.contractClientByAddress(job.contractAddress),
4572
- memo.id,
4573
- memo.memoType,
4574
- memo.content,
4575
- memo.nextPhase,
4576
- memo.status,
4577
- memo.senderAddress,
4578
- memo.signedReason,
4579
- memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4580
- memo.payableDetails
4581
- );
4582
- }),
4583
- job.phase,
4584
- job.context,
4585
- job.contractAddress,
4586
- job.netPayableAmount
4566
+ acpContractClient,
4567
+ agent.walletAddress,
4568
+ jobs.name,
4569
+ jobs.priceV2.value,
4570
+ jobs.priceV2.type,
4571
+ jobs.requirement
4587
4572
  );
4588
- });
4589
- } catch (error) {
4590
- throw new acpError_default("Failed to get completed jobs", error);
4591
- }
4573
+ }),
4574
+ contractAddress: agent.contractAddress,
4575
+ twitterHandle: agent.twitterHandle,
4576
+ walletAddress: agent.walletAddress,
4577
+ metrics: agent.metrics,
4578
+ resource: agent.resources
4579
+ };
4592
4580
  });
4593
4581
  }
4594
- getCancelledJobs(page = 1, pageSize = 10) {
4595
- return __async(this, null, function* () {
4596
- let url = `${this.acpUrl}/api/jobs/cancelled?pagination[page]=${page}&pagination[pageSize]=${pageSize}`;
4597
- try {
4598
- const response = yield fetch(url, {
4599
- headers: {
4600
- "wallet-address": this.walletAddress
4601
- }
4602
- });
4603
- const data = yield response.json();
4604
- if (data.error) {
4605
- throw new acpError_default(data.error.message);
4582
+ async initiateJob(providerAddress, serviceRequirement, fareAmount, evaluatorAddress, expiredAt = new Date(Date.now() + 1e3 * 60 * 60 * 24)) {
4583
+ if (providerAddress === this.walletAddress) {
4584
+ throw new acpError_default(
4585
+ "Provider address cannot be the same as the client address"
4586
+ );
4587
+ }
4588
+ const account = await this.getByClientAndProvider(
4589
+ this.walletAddress,
4590
+ providerAddress,
4591
+ this.acpContractClient
4592
+ );
4593
+ const isV1 = [
4594
+ baseSepoliaAcpConfig.contractAddress,
4595
+ baseSepoliaAcpX402Config.contractAddress,
4596
+ baseAcpConfig.contractAddress,
4597
+ baseAcpX402Config.contractAddress
4598
+ ].includes(this.acpContractClient.config.contractAddress);
4599
+ const defaultEvaluatorAddress = isV1 && !evaluatorAddress ? this.walletAddress : zeroAddress3;
4600
+ const chainId = this.acpContractClient.config.chain.id;
4601
+ const isUsdcPaymentToken = USDC_TOKEN_ADDRESS[chainId].toLowerCase() === fareAmount.fare.contractAddress.toLowerCase();
4602
+ const isX402Job = this.acpContractClient.config.x402Config && isUsdcPaymentToken;
4603
+ const createJobPayload = isV1 || !account ? this.acpContractClient.createJob(
4604
+ providerAddress,
4605
+ evaluatorAddress || defaultEvaluatorAddress,
4606
+ expiredAt,
4607
+ fareAmount.fare.contractAddress,
4608
+ fareAmount.amount,
4609
+ "",
4610
+ isX402Job
4611
+ ) : this.acpContractClient.createJobWithAccount(
4612
+ account.id,
4613
+ evaluatorAddress || defaultEvaluatorAddress,
4614
+ fareAmount.amount,
4615
+ fareAmount.fare.contractAddress,
4616
+ expiredAt,
4617
+ isX402Job
4618
+ );
4619
+ const { userOpHash } = await this.acpContractClient.handleOperation([
4620
+ createJobPayload
4621
+ ]);
4622
+ const jobId = await this.acpContractClient.getJobId(
4623
+ userOpHash,
4624
+ this.walletAddress,
4625
+ providerAddress
4626
+ );
4627
+ const payloads = [];
4628
+ const setBudgetWithPaymentTokenPayload = this.acpContractClient.setBudgetWithPaymentToken(
4629
+ jobId,
4630
+ fareAmount.amount,
4631
+ fareAmount.fare.contractAddress
4632
+ );
4633
+ if (setBudgetWithPaymentTokenPayload) {
4634
+ payloads.push(setBudgetWithPaymentTokenPayload);
4635
+ }
4636
+ payloads.push(
4637
+ this.acpContractClient.createMemo(
4638
+ jobId,
4639
+ preparePayload(serviceRequirement),
4640
+ 0 /* MESSAGE */,
4641
+ true,
4642
+ 1 /* NEGOTIATION */
4643
+ )
4644
+ );
4645
+ await this.acpContractClient.handleOperation(payloads);
4646
+ return jobId;
4647
+ }
4648
+ async getActiveJobs(page = 1, pageSize = 10) {
4649
+ let url = `${this.acpUrl}/api/jobs/active?pagination[page]=${page}&pagination[pageSize]=${pageSize}`;
4650
+ try {
4651
+ const response = await fetch(url, {
4652
+ headers: {
4653
+ "wallet-address": this.walletAddress
4606
4654
  }
4607
- return data.data.map((job) => {
4608
- return new acpJob_default(
4609
- this,
4610
- job.id,
4611
- job.clientAddress,
4612
- job.providerAddress,
4613
- job.evaluatorAddress,
4614
- job.price,
4615
- job.priceTokenAddress,
4616
- job.memos.map((memo) => {
4617
- return new acpMemo_default(
4618
- this.contractClientByAddress(job.contractAddress),
4619
- memo.id,
4620
- memo.memoType,
4621
- memo.content,
4622
- memo.nextPhase,
4623
- memo.status,
4624
- memo.senderAddress,
4625
- memo.signedReason,
4626
- memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4627
- memo.payableDetails
4628
- );
4629
- }),
4630
- job.phase,
4631
- job.context,
4632
- job.contractAddress,
4633
- job.netPayableAmount
4634
- );
4635
- });
4636
- } catch (error) {
4637
- throw new acpError_default("Failed to get cancelled jobs", error);
4655
+ });
4656
+ const data = await response.json();
4657
+ if (data.error) {
4658
+ throw new acpError_default(data.error.message);
4638
4659
  }
4639
- });
4660
+ return data.data.map((job) => {
4661
+ return new acpJob_default(
4662
+ this,
4663
+ job.id,
4664
+ job.clientAddress,
4665
+ job.providerAddress,
4666
+ job.evaluatorAddress,
4667
+ job.price,
4668
+ job.priceTokenAddress,
4669
+ job.memos.map((memo) => {
4670
+ return new acpMemo_default(
4671
+ this.contractClientByAddress(job.contractAddress),
4672
+ memo.id,
4673
+ memo.memoType,
4674
+ memo.content,
4675
+ memo.nextPhase,
4676
+ memo.status,
4677
+ memo.senderAddress,
4678
+ memo.signedReason,
4679
+ memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4680
+ memo.payableDetails,
4681
+ memo.txHash,
4682
+ memo.signedTxHash
4683
+ );
4684
+ }),
4685
+ job.phase,
4686
+ job.context,
4687
+ job.contractAddress,
4688
+ job.netPayableAmount
4689
+ );
4690
+ });
4691
+ } catch (error) {
4692
+ throw new acpError_default("Failed to get active jobs", error);
4693
+ }
4694
+ }
4695
+ async getPendingMemoJobs(page = 1, pageSize = 10) {
4696
+ let url = `${this.acpUrl}/api/jobs/pending-memos?pagination[page]=${page}&pagination[pageSize]=${pageSize}`;
4697
+ try {
4698
+ const response = await fetch(url, {
4699
+ headers: {
4700
+ "wallet-address": this.acpContractClient.walletAddress
4701
+ }
4702
+ });
4703
+ const data = await response.json();
4704
+ if (data.error) {
4705
+ throw new acpError_default(data.error.message);
4706
+ }
4707
+ return data.data.map((job) => {
4708
+ return new acpJob_default(
4709
+ this,
4710
+ job.id,
4711
+ job.clientAddress,
4712
+ job.providerAddress,
4713
+ job.evaluatorAddress,
4714
+ job.price,
4715
+ job.priceTokenAddress,
4716
+ job.memos.map((memo) => {
4717
+ return new acpMemo_default(
4718
+ this.contractClientByAddress(job.contractAddress),
4719
+ memo.id,
4720
+ memo.memoType,
4721
+ memo.content,
4722
+ memo.nextPhase,
4723
+ memo.status,
4724
+ memo.senderAddress,
4725
+ memo.signedReason,
4726
+ memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4727
+ typeof memo.payableDetails === "string" ? tryParseJson(memo.payableDetails) || void 0 : memo.payableDetails,
4728
+ memo.txHash,
4729
+ memo.signedTxHash
4730
+ );
4731
+ }),
4732
+ job.phase,
4733
+ job.context,
4734
+ job.contractAddress,
4735
+ job.netPayableAmount
4736
+ );
4737
+ });
4738
+ } catch (error) {
4739
+ throw new acpError_default("Failed to get pending memo jobs", error);
4740
+ }
4640
4741
  }
4641
- getJobById(jobId) {
4642
- return __async(this, null, function* () {
4643
- let url = `${this.acpUrl}/api/jobs/${jobId}`;
4644
- try {
4645
- const response = yield fetch(url, {
4646
- headers: {
4647
- "wallet-address": this.acpContractClient.walletAddress
4648
- }
4649
- });
4650
- const data = yield response.json();
4651
- if (data.error) {
4652
- throw new acpError_default(data.error.message);
4653
- }
4654
- const job = data.data;
4655
- if (!job) {
4656
- return;
4742
+ async getCompletedJobs(page = 1, pageSize = 10) {
4743
+ let url = `${this.acpUrl}/api/jobs/completed?pagination[page]=${page}&pagination[pageSize]=${pageSize}`;
4744
+ try {
4745
+ const response = await fetch(url, {
4746
+ headers: {
4747
+ "wallet-address": this.acpContractClient.walletAddress
4657
4748
  }
4749
+ });
4750
+ const data = await response.json();
4751
+ if (data.error) {
4752
+ throw new acpError_default(data.error.message);
4753
+ }
4754
+ return data.data.map((job) => {
4658
4755
  return new acpJob_default(
4659
4756
  this,
4660
4757
  job.id,
@@ -4674,7 +4771,9 @@ var AcpClient = class {
4674
4771
  memo.senderAddress,
4675
4772
  memo.signedReason,
4676
4773
  memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4677
- memo.payableDetails
4774
+ memo.payableDetails,
4775
+ memo.txHash,
4776
+ memo.signedTxHash
4678
4777
  );
4679
4778
  }),
4680
4779
  job.phase,
@@ -4682,98 +4781,188 @@ var AcpClient = class {
4682
4781
  job.contractAddress,
4683
4782
  job.netPayableAmount
4684
4783
  );
4685
- } catch (error) {
4686
- throw new acpError_default("Failed to get job by id", error);
4687
- }
4688
- });
4784
+ });
4785
+ } catch (error) {
4786
+ throw new acpError_default("Failed to get completed jobs", error);
4787
+ }
4689
4788
  }
4690
- getMemoById(jobId, memoId) {
4691
- return __async(this, null, function* () {
4692
- let url = `${this.acpUrl}/api/jobs/${jobId}/memos/${memoId}`;
4693
- try {
4694
- const response = yield fetch(url, {
4695
- headers: {
4696
- "wallet-address": this.walletAddress
4697
- }
4698
- });
4699
- const data = yield response.json();
4700
- if (data.error) {
4701
- throw new acpError_default(data.error.message);
4702
- }
4703
- const memo = data.data;
4704
- if (!memo) {
4705
- return;
4789
+ async getCancelledJobs(page = 1, pageSize = 10) {
4790
+ let url = `${this.acpUrl}/api/jobs/cancelled?pagination[page]=${page}&pagination[pageSize]=${pageSize}`;
4791
+ try {
4792
+ const response = await fetch(url, {
4793
+ headers: {
4794
+ "wallet-address": this.walletAddress
4706
4795
  }
4707
- return new acpMemo_default(
4708
- this.contractClientByAddress(memo.contractAddress),
4709
- memo.id,
4710
- memo.memoType,
4711
- memo.content,
4712
- memo.nextPhase,
4713
- memo.status,
4714
- memo.senderAddress,
4715
- memo.signedReason,
4716
- memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4717
- memo.payableDetails
4718
- );
4719
- } catch (error) {
4720
- throw new acpError_default("Failed to get memo by id", error);
4796
+ });
4797
+ const data = await response.json();
4798
+ if (data.error) {
4799
+ throw new acpError_default(data.error.message);
4721
4800
  }
4722
- });
4801
+ return data.data.map((job) => {
4802
+ return new acpJob_default(
4803
+ this,
4804
+ job.id,
4805
+ job.clientAddress,
4806
+ job.providerAddress,
4807
+ job.evaluatorAddress,
4808
+ job.price,
4809
+ job.priceTokenAddress,
4810
+ job.memos.map((memo) => {
4811
+ return new acpMemo_default(
4812
+ this.contractClientByAddress(job.contractAddress),
4813
+ memo.id,
4814
+ memo.memoType,
4815
+ memo.content,
4816
+ memo.nextPhase,
4817
+ memo.status,
4818
+ memo.senderAddress,
4819
+ memo.signedReason,
4820
+ memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4821
+ memo.payableDetails,
4822
+ memo.txHash,
4823
+ memo.signedTxHash
4824
+ );
4825
+ }),
4826
+ job.phase,
4827
+ job.context,
4828
+ job.contractAddress,
4829
+ job.netPayableAmount
4830
+ );
4831
+ });
4832
+ } catch (error) {
4833
+ throw new acpError_default("Failed to get cancelled jobs", error);
4834
+ }
4723
4835
  }
4724
- getAgent(walletAddress) {
4725
- return __async(this, null, function* () {
4726
- const url = `${this.acpUrl}/api/agents?filters[walletAddress]=${walletAddress}`;
4727
- const response = yield fetch(url);
4728
- const data = yield response.json();
4729
- const agents = data.data || [];
4730
- if (agents.length === 0) {
4836
+ async getJobById(jobId) {
4837
+ let url = `${this.acpUrl}/api/jobs/${jobId}`;
4838
+ try {
4839
+ const response = await fetch(url, {
4840
+ headers: {
4841
+ "wallet-address": this.acpContractClient.walletAddress
4842
+ }
4843
+ });
4844
+ const data = await response.json();
4845
+ if (data.error) {
4846
+ throw new acpError_default(data.error.message);
4847
+ }
4848
+ const job = data.data;
4849
+ if (!job) {
4731
4850
  return;
4732
4851
  }
4733
- return agents[0];
4734
- });
4852
+ return new acpJob_default(
4853
+ this,
4854
+ job.id,
4855
+ job.clientAddress,
4856
+ job.providerAddress,
4857
+ job.evaluatorAddress,
4858
+ job.price,
4859
+ job.priceTokenAddress,
4860
+ job.memos.map((memo) => {
4861
+ return new acpMemo_default(
4862
+ this.contractClientByAddress(job.contractAddress),
4863
+ memo.id,
4864
+ memo.memoType,
4865
+ memo.content,
4866
+ memo.nextPhase,
4867
+ memo.status,
4868
+ memo.senderAddress,
4869
+ memo.signedReason,
4870
+ memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4871
+ memo.payableDetails,
4872
+ memo.txHash,
4873
+ memo.signedTxHash
4874
+ );
4875
+ }),
4876
+ job.phase,
4877
+ job.context,
4878
+ job.contractAddress,
4879
+ job.netPayableAmount
4880
+ );
4881
+ } catch (error) {
4882
+ throw new acpError_default("Failed to get job by id", error);
4883
+ }
4735
4884
  }
4736
- getAccountByJobId(jobId, acpContractClient) {
4737
- return __async(this, null, function* () {
4738
- try {
4739
- const url = `${this.acpUrl}/api/accounts/job/${jobId}`;
4740
- const response = yield fetch(url);
4741
- const data = yield response.json();
4742
- if (!data.data) {
4743
- return null;
4885
+ async getMemoById(jobId, memoId) {
4886
+ let url = `${this.acpUrl}/api/jobs/${jobId}/memos/${memoId}`;
4887
+ try {
4888
+ const response = await fetch(url, {
4889
+ headers: {
4890
+ "wallet-address": this.walletAddress
4744
4891
  }
4745
- return new AcpAccount(
4746
- acpContractClient || this.contractClients[0],
4747
- data.data.id,
4748
- data.data.clientAddress,
4749
- data.data.providerAddress,
4750
- data.data.metadata
4751
- );
4752
- } catch (error) {
4753
- throw new acpError_default("Failed to get account by job id", error);
4892
+ });
4893
+ const data = await response.json();
4894
+ if (data.error) {
4895
+ throw new acpError_default(data.error.message);
4754
4896
  }
4755
- });
4897
+ const memo = data.data;
4898
+ if (!memo) {
4899
+ return;
4900
+ }
4901
+ return new acpMemo_default(
4902
+ this.contractClientByAddress(memo.contractAddress),
4903
+ memo.id,
4904
+ memo.memoType,
4905
+ memo.content,
4906
+ memo.nextPhase,
4907
+ memo.status,
4908
+ memo.senderAddress,
4909
+ memo.signedReason,
4910
+ memo.expiry ? new Date(parseInt(memo.expiry) * 1e3) : void 0,
4911
+ memo.payableDetails,
4912
+ memo.txHash,
4913
+ memo.signedTxHash
4914
+ );
4915
+ } catch (error) {
4916
+ throw new acpError_default("Failed to get memo by id", error);
4917
+ }
4756
4918
  }
4757
- getByClientAndProvider(clientAddress, providerAddress, acpContractClient) {
4758
- return __async(this, null, function* () {
4759
- try {
4760
- const url = `${this.acpUrl}/api/accounts/client/${clientAddress}/provider/${providerAddress}`;
4761
- const response = yield fetch(url);
4762
- const data = yield response.json();
4763
- if (!data.data) {
4764
- return null;
4765
- }
4766
- return new AcpAccount(
4767
- acpContractClient || this.contractClients[0],
4768
- data.data.id,
4769
- data.data.clientAddress,
4770
- data.data.providerAddress,
4771
- data.data.metadata
4772
- );
4773
- } catch (error) {
4774
- throw new acpError_default("Failed to get account by client and provider", error);
4919
+ async getAgent(walletAddress) {
4920
+ const url = `${this.acpUrl}/api/agents?filters[walletAddress]=${walletAddress}`;
4921
+ const response = await fetch(url);
4922
+ const data = await response.json();
4923
+ const agents = data.data || [];
4924
+ if (agents.length === 0) {
4925
+ return;
4926
+ }
4927
+ return agents[0];
4928
+ }
4929
+ async getAccountByJobId(jobId, acpContractClient) {
4930
+ try {
4931
+ const url = `${this.acpUrl}/api/accounts/job/${jobId}`;
4932
+ const response = await fetch(url);
4933
+ const data = await response.json();
4934
+ if (!data.data) {
4935
+ return null;
4775
4936
  }
4776
- });
4937
+ return new AcpAccount(
4938
+ acpContractClient || this.contractClients[0],
4939
+ data.data.id,
4940
+ data.data.clientAddress,
4941
+ data.data.providerAddress,
4942
+ data.data.metadata
4943
+ );
4944
+ } catch (error) {
4945
+ throw new acpError_default("Failed to get account by job id", error);
4946
+ }
4947
+ }
4948
+ async getByClientAndProvider(clientAddress, providerAddress, acpContractClient) {
4949
+ try {
4950
+ const url = `${this.acpUrl}/api/accounts/client/${clientAddress}/provider/${providerAddress}`;
4951
+ const response = await fetch(url);
4952
+ const data = await response.json();
4953
+ if (!data.data) {
4954
+ return null;
4955
+ }
4956
+ return new AcpAccount(
4957
+ acpContractClient || this.contractClients[0],
4958
+ data.data.id,
4959
+ data.data.clientAddress,
4960
+ data.data.providerAddress,
4961
+ data.data.metadata
4962
+ );
4963
+ } catch (error) {
4964
+ throw new acpError_default("Failed to get account by client and provider", error);
4965
+ }
4777
4966
  }
4778
4967
  };
4779
4968
  var acpClient_default = AcpClient;
@@ -4800,136 +4989,127 @@ var AcpX402 = class {
4800
4989
  this.sessionKeyClient = sessionKeyClient;
4801
4990
  this.publicClient = publicClient;
4802
4991
  }
4803
- signUpdateJobNonceMessage(jobId, nonce) {
4804
- return __async(this, null, function* () {
4805
- const message = `${jobId}-${nonce}`;
4806
- const signature = yield this.sessionKeyClient.account.getSigner().signMessage(message);
4807
- return signature;
4808
- });
4992
+ async signUpdateJobNonceMessage(jobId, nonce) {
4993
+ const message = `${jobId}-${nonce}`;
4994
+ const signature = await this.sessionKeyClient.account.getSigner().signMessage(message);
4995
+ return signature;
4809
4996
  }
4810
- updateJobNonce(jobId, nonce) {
4811
- return __async(this, null, function* () {
4812
- try {
4813
- const apiUrl = `${this.config.acpUrl}/api/jobs/${jobId}/x402-nonce`;
4814
- const signature = yield this.signUpdateJobNonceMessage(jobId, nonce);
4815
- const response = yield fetch(apiUrl, {
4816
- method: "POST",
4817
- headers: {
4818
- "x-signature": signature,
4819
- "x-nonce": nonce,
4820
- "Content-Type": "application/json"
4821
- },
4822
- body: JSON.stringify({
4823
- data: {
4824
- nonce
4825
- }
4826
- })
4827
- });
4828
- if (!response.ok) {
4829
- throw new acpError_default(
4830
- "Failed to update job X402 nonce",
4831
- response.statusText
4832
- );
4833
- }
4834
- const acpJob = yield response.json();
4835
- return acpJob;
4836
- } catch (error) {
4837
- throw new acpError_default("Failed to update job X402 nonce", error);
4997
+ async updateJobNonce(jobId, nonce) {
4998
+ try {
4999
+ const apiUrl = `${this.config.acpUrl}/api/jobs/${jobId}/x402-nonce`;
5000
+ const signature = await this.signUpdateJobNonceMessage(jobId, nonce);
5001
+ const response = await fetch(apiUrl, {
5002
+ method: "POST",
5003
+ headers: {
5004
+ "x-signature": signature,
5005
+ "x-nonce": nonce,
5006
+ "Content-Type": "application/json"
5007
+ },
5008
+ body: JSON.stringify({
5009
+ data: {
5010
+ nonce
5011
+ }
5012
+ })
5013
+ });
5014
+ if (!response.ok) {
5015
+ throw new acpError_default(
5016
+ "Failed to update job X402 nonce",
5017
+ response.statusText
5018
+ );
4838
5019
  }
4839
- });
5020
+ const acpJob = await response.json();
5021
+ return acpJob;
5022
+ } catch (error) {
5023
+ throw new acpError_default("Failed to update job X402 nonce", error);
5024
+ }
4840
5025
  }
4841
- generatePayment(payableRequest, requirements) {
4842
- return __async(this, null, function* () {
4843
- try {
4844
- const USDC_CONTRACT = this.config.baseFare.contractAddress;
4845
- const timeNow = Math.floor(Date.now() / 1e3);
4846
- const validAfter = timeNow.toString();
4847
- const validBefore = (timeNow + requirements.accepts[0].maxTimeoutSeconds).toString();
4848
- const [tokenName, tokenVersion] = yield this.publicClient.multicall({
4849
- contracts: [
4850
- {
4851
- address: USDC_CONTRACT,
4852
- abi: erc20Abi3,
4853
- functionName: "name"
4854
- },
4855
- {
4856
- address: USDC_CONTRACT,
4857
- abi: fiatTokenV2Abi_default,
4858
- functionName: "version"
4859
- }
4860
- ]
4861
- });
4862
- const nonce = `0x${randomBytes(32).toString("hex")}`;
4863
- const message = {
4864
- from: this.sessionKeyClient.account.address,
4865
- to: payableRequest.to,
4866
- value: payableRequest.value.toString(),
4867
- validAfter: validAfter.toString(),
4868
- validBefore: validBefore.toString(),
4869
- nonce
4870
- };
4871
- const typedData = {
4872
- types: {
4873
- TransferWithAuthorization: X402AuthorizationTypes
4874
- },
4875
- domain: {
4876
- name: tokenName.result,
4877
- version: tokenVersion.result,
4878
- chainId: this.config.chain.id,
4879
- verifyingContract: USDC_CONTRACT
5026
+ async generatePayment(payableRequest, requirements) {
5027
+ try {
5028
+ const USDC_CONTRACT = this.config.baseFare.contractAddress;
5029
+ const timeNow = Math.floor(Date.now() / 1e3);
5030
+ const validAfter = timeNow.toString();
5031
+ const validBefore = (timeNow + requirements.accepts[0].maxTimeoutSeconds).toString();
5032
+ const [tokenName, tokenVersion] = await this.publicClient.multicall({
5033
+ contracts: [
5034
+ {
5035
+ address: USDC_CONTRACT,
5036
+ abi: erc20Abi3,
5037
+ functionName: "name"
4880
5038
  },
4881
- primaryType: "TransferWithAuthorization",
4882
- message
4883
- };
4884
- const signature = yield this.sessionKeyClient.signTypedData({
4885
- typedData
4886
- });
4887
- const payload = {
4888
- x402Version: requirements.x402Version,
4889
- scheme: requirements.accepts[0].scheme,
4890
- network: requirements.accepts[0].network,
4891
- payload: {
4892
- signature,
4893
- authorization: message
5039
+ {
5040
+ address: USDC_CONTRACT,
5041
+ abi: fiatTokenV2Abi_default,
5042
+ functionName: "version"
4894
5043
  }
4895
- };
4896
- const encodedPayment = safeBase64Encode(JSON.stringify(payload));
4897
- return {
4898
- encodedPayment,
5044
+ ]
5045
+ });
5046
+ const nonce = `0x${randomBytes(32).toString("hex")}`;
5047
+ const message = {
5048
+ from: this.sessionKeyClient.account.address,
5049
+ to: payableRequest.to,
5050
+ value: payableRequest.value.toString(),
5051
+ validAfter: validAfter.toString(),
5052
+ validBefore: validBefore.toString(),
5053
+ nonce
5054
+ };
5055
+ const typedData = {
5056
+ types: {
5057
+ TransferWithAuthorization: X402AuthorizationTypes
5058
+ },
5059
+ domain: {
5060
+ name: tokenName.result,
5061
+ version: tokenVersion.result,
5062
+ chainId: this.config.chain.id,
5063
+ verifyingContract: USDC_CONTRACT
5064
+ },
5065
+ primaryType: "TransferWithAuthorization",
5066
+ message
5067
+ };
5068
+ const signature = await this.sessionKeyClient.signTypedData({
5069
+ typedData
5070
+ });
5071
+ const payload = {
5072
+ x402Version: requirements.x402Version,
5073
+ scheme: requirements.accepts[0].scheme,
5074
+ network: requirements.accepts[0].network,
5075
+ payload: {
4899
5076
  signature,
4900
- message
4901
- };
4902
- } catch (error) {
4903
- throw new acpError_default("Failed to generate X402 payment", error);
4904
- }
4905
- });
4906
- }
4907
- performRequest(url, version2, budget, signature) {
4908
- return __async(this, null, function* () {
4909
- var _a;
4910
- const baseUrl = (_a = this.config.x402Config) == null ? void 0 : _a.url;
4911
- if (!baseUrl) throw new acpError_default("X402 URL not configured");
4912
- try {
4913
- const headers = {};
4914
- if (signature) headers["x-payment"] = signature;
4915
- if (budget) headers["x-budget"] = budget.toString();
4916
- headers["x-acp-version"] = version2;
4917
- const res = yield fetch(`${baseUrl}${url}`, { method: "GET", headers });
4918
- const data = yield res.json();
4919
- if (!res.ok && res.status !== HTTP_STATUS_CODES.PAYMENT_REQUIRED) {
4920
- throw new acpError_default(
4921
- "Invalid response status code for X402 request",
4922
- data
4923
- );
5077
+ authorization: message
4924
5078
  }
4925
- return {
4926
- isPaymentRequired: res.status === HTTP_STATUS_CODES.PAYMENT_REQUIRED,
5079
+ };
5080
+ const encodedPayment = safeBase64Encode(JSON.stringify(payload));
5081
+ return {
5082
+ encodedPayment,
5083
+ signature,
5084
+ message
5085
+ };
5086
+ } catch (error) {
5087
+ throw new acpError_default("Failed to generate X402 payment", error);
5088
+ }
5089
+ }
5090
+ async performRequest(url, version2, budget, signature) {
5091
+ const baseUrl = this.config.x402Config?.url;
5092
+ if (!baseUrl) throw new acpError_default("X402 URL not configured");
5093
+ try {
5094
+ const headers = {};
5095
+ if (signature) headers["x-payment"] = signature;
5096
+ if (budget) headers["x-budget"] = budget.toString();
5097
+ headers["x-acp-version"] = version2;
5098
+ const res = await fetch(`${baseUrl}${url}`, { method: "GET", headers });
5099
+ const data = await res.json();
5100
+ if (!res.ok && res.status !== HTTP_STATUS_CODES.PAYMENT_REQUIRED) {
5101
+ throw new acpError_default(
5102
+ "Invalid response status code for X402 request",
4927
5103
  data
4928
- };
4929
- } catch (error) {
4930
- throw new acpError_default("Failed to perform X402 request", error);
5104
+ );
4931
5105
  }
4932
- });
5106
+ return {
5107
+ isPaymentRequired: res.status === HTTP_STATUS_CODES.PAYMENT_REQUIRED,
5108
+ data
5109
+ };
5110
+ } catch (error) {
5111
+ throw new acpError_default("Failed to perform X402 request", error);
5112
+ }
4933
5113
  }
4934
5114
  };
4935
5115
 
@@ -4941,37 +5121,46 @@ var AcpContractClient = class _AcpContractClient extends baseAcpContractClient_d
4941
5121
  this.MAX_FEE_PER_GAS = 2e7;
4942
5122
  this.MAX_PRIORITY_FEE_PER_GAS = 21e6;
4943
5123
  }
4944
- static build(_0, _1, _2) {
4945
- return __async(this, arguments, function* (walletPrivateKey, sessionEntityKeyId, agentWalletAddress, config = baseAcpConfig) {
4946
- const acpContractClient = new _AcpContractClient(
4947
- agentWalletAddress,
4948
- config
4949
- );
4950
- yield acpContractClient.init(walletPrivateKey, sessionEntityKeyId);
4951
- return acpContractClient;
4952
- });
5124
+ static async build(walletPrivateKey, sessionEntityKeyId, agentWalletAddress, config = baseAcpConfig) {
5125
+ const acpContractClient = new _AcpContractClient(
5126
+ agentWalletAddress,
5127
+ config
5128
+ );
5129
+ await acpContractClient.init(walletPrivateKey, sessionEntityKeyId);
5130
+ return acpContractClient;
4953
5131
  }
4954
- init(privateKey, sessionEntityKeyId) {
4955
- return __async(this, null, function* () {
4956
- const sessionKeySigner = LocalAccountSigner.privateKeyToAccountSigner(privateKey);
4957
- this._sessionKeyClient = yield createModularAccountV2Client({
4958
- chain: this.chain,
4959
- transport: alchemy({
4960
- rpcUrl: this.config.alchemyRpcUrl
4961
- }),
4962
- signer: sessionKeySigner,
4963
- policyId: "186aaa4a-5f57-4156-83fb-e456365a8820",
4964
- accountAddress: this.agentWalletAddress,
4965
- signerEntity: {
4966
- entityId: sessionEntityKeyId,
4967
- isGlobalValidation: true
4968
- }
4969
- });
4970
- this._acpX402 = new AcpX402(
4971
- this.config,
4972
- this.sessionKeyClient,
4973
- this.publicClient
5132
+ async init(privateKey, sessionEntityKeyId) {
5133
+ const sessionKeySigner = LocalAccountSigner.privateKeyToAccountSigner(privateKey);
5134
+ this._sessionKeyClient = await createModularAccountV2Client({
5135
+ chain: this.chain,
5136
+ transport: alchemy({
5137
+ rpcUrl: this.config.alchemyRpcUrl
5138
+ }),
5139
+ signer: sessionKeySigner,
5140
+ policyId: "186aaa4a-5f57-4156-83fb-e456365a8820",
5141
+ accountAddress: this.agentWalletAddress,
5142
+ signerEntity: {
5143
+ entityId: sessionEntityKeyId,
5144
+ isGlobalValidation: true
5145
+ }
5146
+ });
5147
+ this._acpX402 = new AcpX402(
5148
+ this.config,
5149
+ this.sessionKeyClient,
5150
+ this.publicClient
5151
+ );
5152
+ const account = this.sessionKeyClient.account;
5153
+ const sessionSignerAddress = await account.getSigner().getAddress();
5154
+ if (!await account.isAccountDeployed()) {
5155
+ throw new acpError_default(
5156
+ `ACP Contract Client validation failed: agent account ${this.agentWalletAddress} is not deployed on-chain`
4974
5157
  );
5158
+ }
5159
+ await this.validateSessionKeyOnChain(sessionSignerAddress, sessionEntityKeyId);
5160
+ console.log("Connected to ACP:", {
5161
+ agentWalletAddress: this.agentWalletAddress,
5162
+ whitelistedWalletAddress: sessionSignerAddress,
5163
+ entityId: sessionEntityKeyId
4975
5164
  });
4976
5165
  }
4977
5166
  getRandomNonce(bits = 152) {
@@ -4995,74 +5184,68 @@ var AcpContractClient = class _AcpContractClient extends baseAcpContractClient_d
4995
5184
  }
4996
5185
  return this._acpX402;
4997
5186
  }
4998
- calculateGasFees() {
4999
- return __async(this, null, function* () {
5000
- const finalMaxFeePerGas = BigInt(this.MAX_FEE_PER_GAS) + BigInt(this.MAX_PRIORITY_FEE_PER_GAS) * BigInt(Math.max(0, this.PRIORITY_FEE_MULTIPLIER - 1));
5001
- return finalMaxFeePerGas;
5002
- });
5187
+ async calculateGasFees() {
5188
+ const finalMaxFeePerGas = BigInt(this.MAX_FEE_PER_GAS) + BigInt(this.MAX_PRIORITY_FEE_PER_GAS) * BigInt(Math.max(0, this.PRIORITY_FEE_MULTIPLIER - 1));
5189
+ return finalMaxFeePerGas;
5003
5190
  }
5004
- handleOperation(operations) {
5005
- return __async(this, null, function* () {
5006
- const payload = {
5007
- uo: operations.map((op) => ({
5008
- target: op.contractAddress,
5009
- data: op.data,
5010
- value: op.value
5011
- })),
5012
- overrides: {
5013
- nonceKey: this.getRandomNonce()
5191
+ async handleOperation(operations) {
5192
+ const payload = {
5193
+ uo: operations.map((op) => ({
5194
+ target: op.contractAddress,
5195
+ data: op.data,
5196
+ value: op.value
5197
+ })),
5198
+ overrides: {
5199
+ nonceKey: this.getRandomNonce()
5200
+ }
5201
+ };
5202
+ let retries = this.config.maxRetries;
5203
+ let finalError;
5204
+ while (retries > 0) {
5205
+ try {
5206
+ if (this.config.maxRetries > retries) {
5207
+ const gasFees = await this.calculateGasFees();
5208
+ payload["overrides"] = {
5209
+ maxFeePerGas: `0x${gasFees.toString(16)}`
5210
+ };
5014
5211
  }
5015
- };
5016
- let retries = this.config.maxRetries;
5017
- let finalError;
5018
- while (retries > 0) {
5019
- try {
5020
- if (this.config.maxRetries > retries) {
5021
- const gasFees = yield this.calculateGasFees();
5022
- payload["overrides"] = {
5023
- maxFeePerGas: `0x${gasFees.toString(16)}`
5024
- };
5025
- }
5026
- const { hash } = yield this.sessionKeyClient.sendUserOperation(payload);
5027
- const txnHash = yield this.sessionKeyClient.waitForUserOperationTransaction({
5028
- hash
5029
- });
5030
- return { userOpHash: hash, txnHash };
5031
- } catch (error) {
5032
- retries -= 1;
5033
- if (retries === 0) {
5034
- finalError = error;
5035
- break;
5036
- }
5037
- yield new Promise((resolve) => setTimeout(resolve, 2e3 * retries));
5212
+ const { hash } = await this.sessionKeyClient.sendUserOperation(payload);
5213
+ const txnHash = await this.sessionKeyClient.waitForUserOperationTransaction({
5214
+ hash
5215
+ });
5216
+ return { userOpHash: hash, txnHash };
5217
+ } catch (error) {
5218
+ retries -= 1;
5219
+ if (retries === 0) {
5220
+ finalError = error;
5221
+ break;
5038
5222
  }
5223
+ await new Promise((resolve) => setTimeout(resolve, 2e3 * retries));
5039
5224
  }
5040
- throw new acpError_default(`Failed to send user operation`, finalError);
5041
- });
5225
+ }
5226
+ throw new acpError_default(`Failed to send user operation`, finalError);
5042
5227
  }
5043
- getJobId(createJobUserOpHash, clientAddress, providerAddress) {
5044
- return __async(this, null, function* () {
5045
- const result = yield this.sessionKeyClient.getUserOperationReceipt(createJobUserOpHash);
5046
- if (!result) {
5047
- throw new acpError_default("Failed to get user operation receipt");
5048
- }
5049
- const contractLogs = result.logs.filter((log) => {
5050
- return log.address.toLowerCase() === this.contractAddress.toLowerCase();
5051
- }).map(
5052
- (log) => decodeEventLog({
5053
- abi: this.abi,
5054
- data: log.data,
5055
- topics: log.topics
5056
- })
5057
- );
5058
- const createdJobEvent = contractLogs.find(
5059
- (log) => log.eventName === "JobCreated" && log.args.client.toLowerCase() === clientAddress.toLowerCase() && log.args.provider.toLowerCase() === providerAddress.toLowerCase()
5060
- );
5061
- if (!createdJobEvent) {
5062
- throw new acpError_default("Failed to find created job event");
5063
- }
5064
- return Number(createdJobEvent.args.jobId);
5065
- });
5228
+ async getJobId(createJobUserOpHash, clientAddress, providerAddress) {
5229
+ const result = await this.sessionKeyClient.getUserOperationReceipt(createJobUserOpHash);
5230
+ if (!result) {
5231
+ throw new acpError_default("Failed to get user operation receipt");
5232
+ }
5233
+ const contractLogs = result.logs.filter((log) => {
5234
+ return log.address.toLowerCase() === this.contractAddress.toLowerCase();
5235
+ }).map(
5236
+ (log) => decodeEventLog({
5237
+ abi: this.abi,
5238
+ data: log.data,
5239
+ topics: log.topics
5240
+ })
5241
+ );
5242
+ const createdJobEvent = contractLogs.find(
5243
+ (log) => log.eventName === "JobCreated" && log.args.client.toLowerCase() === clientAddress.toLowerCase() && log.args.provider.toLowerCase() === providerAddress.toLowerCase()
5244
+ );
5245
+ if (!createdJobEvent) {
5246
+ throw new acpError_default("Failed to find created job event");
5247
+ }
5248
+ return Number(createdJobEvent.args.jobId);
5066
5249
  }
5067
5250
  createJob(providerAddress, evaluatorAddress, expireAt, paymentTokenAddress, budgetBaseUnit, metadata, isX402Job) {
5068
5251
  try {
@@ -5133,20 +5316,14 @@ var AcpContractClient = class _AcpContractClient extends baseAcpContractClient_d
5133
5316
  updateAccountMetadata(accountId, metadata) {
5134
5317
  throw new acpError_default("Not Supported");
5135
5318
  }
5136
- updateJobX402Nonce(jobId, nonce) {
5137
- return __async(this, null, function* () {
5138
- return yield this.acpX402.updateJobNonce(jobId, nonce);
5139
- });
5319
+ async updateJobX402Nonce(jobId, nonce) {
5320
+ return await this.acpX402.updateJobNonce(jobId, nonce);
5140
5321
  }
5141
- generateX402Payment(payableRequest, requirements) {
5142
- return __async(this, null, function* () {
5143
- return yield this.acpX402.generatePayment(payableRequest, requirements);
5144
- });
5322
+ async generateX402Payment(payableRequest, requirements) {
5323
+ return await this.acpX402.generatePayment(payableRequest, requirements);
5145
5324
  }
5146
- performX402Request(url, version2, budget, signature) {
5147
- return __async(this, null, function* () {
5148
- return yield this.acpX402.performRequest(url, version2, budget, signature);
5149
- });
5325
+ async performX402Request(url, version2, budget, signature) {
5326
+ return await this.acpX402.performRequest(url, version2, budget, signature);
5150
5327
  }
5151
5328
  getAcpVersion() {
5152
5329
  return "1";
@@ -5874,68 +6051,77 @@ var AcpContractClientV2 = class _AcpContractClientV2 extends baseAcpContractClie
5874
6051
  this.MAX_FEE_PER_GAS = 2e7;
5875
6052
  this.MAX_PRIORITY_FEE_PER_GAS = 21e6;
5876
6053
  }
5877
- static build(_0, _1, _2) {
5878
- return __async(this, arguments, function* (walletPrivateKey, sessionEntityKeyId, agentWalletAddress, config = baseAcpConfigV2) {
5879
- const publicClient = createPublicClient4({
5880
- chain: config.chain,
5881
- transport: http3(config.rpcEndpoint)
5882
- });
5883
- const [jobManagerAddress, memoManagerAddress, accountManagerAddress] = yield publicClient.multicall({
5884
- contracts: [
5885
- {
5886
- address: config.contractAddress,
5887
- abi: config.abi,
5888
- functionName: "jobManager"
5889
- },
5890
- {
5891
- address: config.contractAddress,
5892
- abi: config.abi,
5893
- functionName: "memoManager"
5894
- },
5895
- {
5896
- address: config.contractAddress,
5897
- abi: config.abi,
5898
- functionName: "accountManager"
5899
- }
5900
- ]
5901
- });
5902
- if (!jobManagerAddress || !memoManagerAddress || !accountManagerAddress) {
5903
- throw new acpError_default(
5904
- "Failed to get job manager, memo manager, or account manager address"
5905
- );
5906
- }
5907
- const acpContractClient = new _AcpContractClientV2(
5908
- jobManagerAddress.result,
5909
- memoManagerAddress.result,
5910
- accountManagerAddress.result,
5911
- agentWalletAddress,
5912
- config
5913
- );
5914
- yield acpContractClient.init(walletPrivateKey, sessionEntityKeyId);
5915
- return acpContractClient;
6054
+ static async build(walletPrivateKey, sessionEntityKeyId, agentWalletAddress, config = baseAcpConfigV2) {
6055
+ const publicClient = createPublicClient4({
6056
+ chain: config.chain,
6057
+ transport: http3(config.rpcEndpoint)
5916
6058
  });
5917
- }
5918
- init(privateKey, sessionEntityKeyId) {
5919
- return __async(this, null, function* () {
5920
- const sessionKeySigner = LocalAccountSigner2.privateKeyToAccountSigner(privateKey);
5921
- this._sessionKeyClient = yield createModularAccountV2Client2({
5922
- chain: this.chain,
5923
- transport: alchemy2({
5924
- rpcUrl: this.config.alchemyRpcUrl
5925
- }),
5926
- signer: sessionKeySigner,
5927
- policyId: "186aaa4a-5f57-4156-83fb-e456365a8820",
5928
- accountAddress: this.agentWalletAddress,
5929
- signerEntity: {
5930
- entityId: sessionEntityKeyId,
5931
- isGlobalValidation: true
6059
+ const [jobManagerAddress, memoManagerAddress, accountManagerAddress] = await publicClient.multicall({
6060
+ contracts: [
6061
+ {
6062
+ address: config.contractAddress,
6063
+ abi: config.abi,
6064
+ functionName: "jobManager"
6065
+ },
6066
+ {
6067
+ address: config.contractAddress,
6068
+ abi: config.abi,
6069
+ functionName: "memoManager"
6070
+ },
6071
+ {
6072
+ address: config.contractAddress,
6073
+ abi: config.abi,
6074
+ functionName: "accountManager"
5932
6075
  }
5933
- });
5934
- this._acpX402 = new AcpX402(
5935
- this.config,
5936
- this.sessionKeyClient,
5937
- this.publicClient
6076
+ ]
6077
+ });
6078
+ if (!jobManagerAddress || !memoManagerAddress || !accountManagerAddress) {
6079
+ throw new acpError_default(
6080
+ "Failed to get job manager, memo manager, or account manager address"
6081
+ );
6082
+ }
6083
+ const acpContractClient = new _AcpContractClientV2(
6084
+ jobManagerAddress.result,
6085
+ memoManagerAddress.result,
6086
+ accountManagerAddress.result,
6087
+ agentWalletAddress,
6088
+ config
6089
+ );
6090
+ await acpContractClient.init(walletPrivateKey, sessionEntityKeyId);
6091
+ return acpContractClient;
6092
+ }
6093
+ async init(privateKey, sessionEntityKeyId) {
6094
+ const sessionKeySigner = LocalAccountSigner2.privateKeyToAccountSigner(privateKey);
6095
+ this._sessionKeyClient = await createModularAccountV2Client2({
6096
+ chain: this.chain,
6097
+ transport: alchemy2({
6098
+ rpcUrl: this.config.alchemyRpcUrl
6099
+ }),
6100
+ signer: sessionKeySigner,
6101
+ policyId: "186aaa4a-5f57-4156-83fb-e456365a8820",
6102
+ accountAddress: this.agentWalletAddress,
6103
+ signerEntity: {
6104
+ entityId: sessionEntityKeyId,
6105
+ isGlobalValidation: true
6106
+ }
6107
+ });
6108
+ this._acpX402 = new AcpX402(
6109
+ this.config,
6110
+ this.sessionKeyClient,
6111
+ this.publicClient
6112
+ );
6113
+ const account = this.sessionKeyClient.account;
6114
+ const sessionSignerAddress = await account.getSigner().getAddress();
6115
+ if (!await account.isAccountDeployed()) {
6116
+ throw new acpError_default(
6117
+ `ACP Contract Client validation failed: agent account ${this.agentWalletAddress} is not deployed on-chain`
5938
6118
  );
6119
+ }
6120
+ await this.validateSessionKeyOnChain(sessionSignerAddress, sessionEntityKeyId);
6121
+ console.log("Connected to ACP:", {
6122
+ agentWalletAddress: this.agentWalletAddress,
6123
+ whitelistedWalletAddress: sessionSignerAddress,
6124
+ entityId: sessionEntityKeyId
5939
6125
  });
5940
6126
  }
5941
6127
  getRandomNonce(bits = 152) {
@@ -5959,116 +6145,102 @@ var AcpContractClientV2 = class _AcpContractClientV2 extends baseAcpContractClie
5959
6145
  }
5960
6146
  return this._acpX402;
5961
6147
  }
5962
- calculateGasFees() {
5963
- return __async(this, null, function* () {
5964
- const finalMaxFeePerGas = BigInt(this.MAX_FEE_PER_GAS) + BigInt(this.MAX_PRIORITY_FEE_PER_GAS) * BigInt(Math.max(0, this.PRIORITY_FEE_MULTIPLIER - 1));
5965
- return finalMaxFeePerGas;
5966
- });
6148
+ async calculateGasFees() {
6149
+ const finalMaxFeePerGas = BigInt(this.MAX_FEE_PER_GAS) + BigInt(this.MAX_PRIORITY_FEE_PER_GAS) * BigInt(Math.max(0, this.PRIORITY_FEE_MULTIPLIER - 1));
6150
+ return finalMaxFeePerGas;
5967
6151
  }
5968
- handleOperation(operations) {
5969
- return __async(this, null, function* () {
5970
- const payload = {
5971
- uo: operations.map((operation) => ({
5972
- target: operation.contractAddress,
5973
- data: operation.data,
5974
- value: operation.value
5975
- })),
5976
- overrides: {
5977
- nonceKey: this.getRandomNonce()
6152
+ async handleOperation(operations) {
6153
+ const payload = {
6154
+ uo: operations.map((operation) => ({
6155
+ target: operation.contractAddress,
6156
+ data: operation.data,
6157
+ value: operation.value
6158
+ })),
6159
+ overrides: {
6160
+ nonceKey: this.getRandomNonce()
6161
+ }
6162
+ };
6163
+ let retries = this.config.maxRetries;
6164
+ let finalError;
6165
+ while (retries > 0) {
6166
+ try {
6167
+ if (this.config.maxRetries > retries) {
6168
+ const gasFees = await this.calculateGasFees();
6169
+ payload["overrides"] = {
6170
+ maxFeePerGas: `0x${gasFees.toString(16)}`
6171
+ };
5978
6172
  }
5979
- };
5980
- let retries = this.config.maxRetries;
5981
- let finalError;
5982
- while (retries > 0) {
5983
- try {
5984
- if (this.config.maxRetries > retries) {
5985
- const gasFees = yield this.calculateGasFees();
5986
- payload["overrides"] = {
5987
- maxFeePerGas: `0x${gasFees.toString(16)}`
5988
- };
6173
+ const { hash } = await this.sessionKeyClient.sendUserOperation(payload);
6174
+ const txnHash = await this.sessionKeyClient.waitForUserOperationTransaction({
6175
+ hash,
6176
+ tag: "pending",
6177
+ retries: {
6178
+ intervalMs: 200,
6179
+ multiplier: 1.1,
6180
+ maxRetries: 10
5989
6181
  }
5990
- const { hash } = yield this.sessionKeyClient.sendUserOperation(payload);
5991
- const txnHash = yield this.sessionKeyClient.waitForUserOperationTransaction({
5992
- hash,
5993
- tag: "pending",
5994
- retries: {
5995
- intervalMs: 200,
5996
- multiplier: 1.1,
5997
- maxRetries: 10
5998
- }
5999
- });
6000
- return { userOpHash: hash, txnHash };
6001
- } catch (error) {
6002
- retries -= 1;
6003
- if (retries === 0) {
6004
- finalError = error;
6005
- break;
6006
- }
6007
- yield new Promise((resolve) => setTimeout(resolve, 2e3 * retries));
6182
+ });
6183
+ return { userOpHash: hash, txnHash };
6184
+ } catch (error) {
6185
+ retries -= 1;
6186
+ if (retries === 0) {
6187
+ finalError = error;
6188
+ break;
6008
6189
  }
6190
+ await new Promise((resolve) => setTimeout(resolve, 2e3 * retries));
6009
6191
  }
6010
- throw new acpError_default(`Failed to send user operation`, finalError);
6011
- });
6192
+ }
6193
+ throw new acpError_default(`Failed to send user operation`, finalError);
6012
6194
  }
6013
- getJobId(createJobUserOpHash, clientAddress, providerAddress) {
6014
- return __async(this, null, function* () {
6015
- const result = yield this.sessionKeyClient.getUserOperationReceipt(
6016
- createJobUserOpHash,
6017
- "pending"
6018
- );
6019
- if (!result) {
6020
- throw new acpError_default("Failed to get user operation receipt");
6021
- }
6022
- const contractLogs = result.logs.filter((log) => {
6023
- return log.address.toLowerCase() === this.jobManagerAddress.toLowerCase();
6024
- }).map(
6025
- (log) => decodeEventLog2({
6026
- abi: jobManagerAbi_default,
6027
- data: log.data,
6028
- topics: log.topics
6029
- })
6030
- );
6031
- const createdJobEvent = contractLogs.find(
6032
- (log) => log.eventName === "JobCreated" && log.args.client.toLowerCase() === clientAddress.toLowerCase() && log.args.provider.toLowerCase() === providerAddress.toLowerCase()
6033
- );
6034
- if (!createdJobEvent) {
6035
- throw new acpError_default("Failed to find created job event");
6036
- }
6037
- return Number(createdJobEvent.args.jobId);
6038
- });
6195
+ async getJobId(createJobUserOpHash, clientAddress, providerAddress) {
6196
+ const result = await this.sessionKeyClient.getUserOperationReceipt(
6197
+ createJobUserOpHash,
6198
+ "pending"
6199
+ );
6200
+ if (!result) {
6201
+ throw new acpError_default("Failed to get user operation receipt");
6202
+ }
6203
+ const contractLogs = result.logs.filter((log) => {
6204
+ return log.address.toLowerCase() === this.jobManagerAddress.toLowerCase();
6205
+ }).map(
6206
+ (log) => decodeEventLog2({
6207
+ abi: jobManagerAbi_default,
6208
+ data: log.data,
6209
+ topics: log.topics
6210
+ })
6211
+ );
6212
+ const createdJobEvent = contractLogs.find(
6213
+ (log) => log.eventName === "JobCreated" && log.args.client.toLowerCase() === clientAddress.toLowerCase() && log.args.provider.toLowerCase() === providerAddress.toLowerCase()
6214
+ );
6215
+ if (!createdJobEvent) {
6216
+ throw new acpError_default("Failed to find created job event");
6217
+ }
6218
+ return Number(createdJobEvent.args.jobId);
6039
6219
  }
6040
- updateJobX402Nonce(jobId, nonce) {
6041
- return __async(this, null, function* () {
6042
- return yield this.acpX402.updateJobNonce(jobId, nonce);
6043
- });
6220
+ async updateJobX402Nonce(jobId, nonce) {
6221
+ return await this.acpX402.updateJobNonce(jobId, nonce);
6044
6222
  }
6045
- generateX402Payment(payableRequest, requirements) {
6046
- return __async(this, null, function* () {
6047
- return yield this.acpX402.generatePayment(payableRequest, requirements);
6048
- });
6223
+ async generateX402Payment(payableRequest, requirements) {
6224
+ return await this.acpX402.generatePayment(payableRequest, requirements);
6049
6225
  }
6050
- performX402Request(url, version2, budget, signature) {
6051
- return __async(this, null, function* () {
6052
- return yield this.acpX402.performRequest(url, version2, budget, signature);
6053
- });
6226
+ async performX402Request(url, version2, budget, signature) {
6227
+ return await this.acpX402.performRequest(url, version2, budget, signature);
6054
6228
  }
6055
- getX402PaymentDetails(jobId) {
6056
- return __async(this, null, function* () {
6057
- try {
6058
- const result = yield this.publicClient.readContract({
6059
- address: this.jobManagerAddress,
6060
- abi: jobManagerAbi_default,
6061
- functionName: "x402PaymentDetails",
6062
- args: [BigInt(jobId)]
6063
- });
6064
- return {
6065
- isX402: result[0],
6066
- isBudgetReceived: result[1]
6067
- };
6068
- } catch (error) {
6069
- throw new acpError_default("Failed to get X402 payment details", error);
6070
- }
6071
- });
6229
+ async getX402PaymentDetails(jobId) {
6230
+ try {
6231
+ const result = await this.publicClient.readContract({
6232
+ address: this.jobManagerAddress,
6233
+ abi: jobManagerAbi_default,
6234
+ functionName: "x402PaymentDetails",
6235
+ args: [BigInt(jobId)]
6236
+ });
6237
+ return {
6238
+ isX402: result[0],
6239
+ isBudgetReceived: result[1]
6240
+ };
6241
+ } catch (error) {
6242
+ throw new acpError_default("Failed to get X402 payment details", error);
6243
+ }
6072
6244
  }
6073
6245
  getAcpVersion() {
6074
6246
  return "2";