-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathacpJob.ts
More file actions
810 lines (683 loc) · 22.3 KB
/
acpJob.ts
File metadata and controls
810 lines (683 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
import { Address, formatUnits } from "viem";
import AcpClient from "./acpClient";
import {
AcpJobPhases,
FeeType,
MemoType,
OperationPayload,
} from "./contractClients/baseAcpContractClient";
import AcpMemo from "./acpMemo";
import { DeliverablePayload, AcpMemoStatus, AcpMemoState } from "./interfaces";
import {
getDestinationChainId,
getDestinationEndpointId,
preparePayload,
tryParseJson,
} from "./utils";
import { FareAmount, FareAmountBase } from "./acpFare";
import AcpError from "./acpError";
import { PriceType } from "./acpJobOffering";
import * as util from "util";
class AcpJob {
public name: string | undefined;
public requirement: Record<string, any> | string | undefined;
public priceType: PriceType = PriceType.FIXED;
public priceValue: number = 0;
constructor(
private acpClient: AcpClient,
public id: number,
public clientAddress: Address,
public providerAddress: Address,
public evaluatorAddress: Address,
public price: number,
public priceTokenAddress: Address,
public memos: AcpMemo[],
public phase: AcpJobPhases,
public context: Record<string, any>,
public contractAddress: Address,
private _deliverable: DeliverablePayload | null,
public netPayableAmount?: number
) {
const content = this.memos.find(
(m) => m.nextPhase === AcpJobPhases.NEGOTIATION
)?.content;
if (!content) {
return;
}
const contentObj = tryParseJson<{
name: string;
requirement: Record<string, any> | string;
serviceName: string;
serviceRequirement: Record<string, any>;
priceType: PriceType;
priceValue: number;
}>(content);
if (!contentObj) {
return;
}
if (contentObj.serviceRequirement || contentObj.requirement) {
this.requirement =
contentObj.requirement || contentObj.serviceRequirement;
}
if (contentObj.serviceName || contentObj.name) {
this.name = contentObj.name || contentObj.serviceName;
}
if (contentObj.priceType) {
this.priceType = contentObj.priceType || PriceType.FIXED;
}
if (contentObj.priceValue) {
this.priceValue = contentObj.priceValue || this.price;
}
}
public get acpContractClient() {
return this.acpClient.contractClientByAddress(this.contractAddress);
}
public get config() {
return this.acpContractClient.config;
}
public get baseFare() {
return this.acpContractClient.config.baseFare;
}
public get rejectionReason(): {
rejectedBy: Address,
reason: string | undefined
} | undefined {
const rejectedMemo: AcpMemo | undefined = this.memos.find(
(m) =>
m.status === AcpMemoStatus.REJECTED
);
if (rejectedMemo) {
const rejectedBy: Address = rejectedMemo.senderAddress === this.clientAddress ? this.providerAddress : this.clientAddress;
return {
rejectedBy: rejectedBy,
reason: rejectedMemo.signedReason
};
}
const rejectJobMemo: AcpMemo | undefined = this.memos.find((m) => m.nextPhase === AcpJobPhases.REJECTED);
if (rejectJobMemo) {
return {
rejectedBy: rejectJobMemo.senderAddress,
reason: rejectJobMemo.content,
};
}
return undefined;
}
public get providerAgent() {
return this.acpClient.getAgent(this.providerAddress);
}
public get clientAgent() {
return this.acpClient.getAgent(this.clientAddress);
}
public get evaluatorAgent() {
return this.acpClient.getAgent(this.evaluatorAddress);
}
public get account() {
return this.acpClient.getAccountByJobId(this.id, this.acpContractClient);
}
public get latestMemo(): AcpMemo | undefined {
return this.memos[this.memos.length - 1];
}
public async getDeliverable() {
if (!this._deliverable) {
return null;
}
if (typeof this._deliverable !== "string") {
return this._deliverable;
}
const regex = /api\/memo-contents\/([0-9]+)$/;
const result = this._deliverable?.match(regex);
if (!result) {
return this._deliverable;
}
const deliverable = await this.acpClient.getMemoContent(this._deliverable);
return tryParseJson<DeliverablePayload>(deliverable) || deliverable;
}
async createRequirement(content: string) {
const operations: OperationPayload[] = [];
operations.push(
this.acpContractClient.createMemo(
this.id,
content,
MemoType.MESSAGE,
true,
AcpJobPhases.TRANSACTION
)
);
return await this.acpContractClient.handleOperation(operations);
}
async createPayableRequirement(
content: string,
type:
| MemoType.PAYABLE_REQUEST
| MemoType.PAYABLE_TRANSFER_ESCROW
| MemoType.PAYABLE_TRANSFER,
amount: FareAmountBase,
recipient: Address,
expiredAt: Date = new Date(Date.now() + 1000 * 60 * 5) // 5 minutes
) {
const operations: OperationPayload[] = [];
if (type === MemoType.PAYABLE_TRANSFER_ESCROW) {
operations.push(
this.acpContractClient.approveAllowance(
amount.amount,
amount.fare.contractAddress
)
);
}
const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
const isPercentagePricing: boolean =
this.priceType === PriceType.PERCENTAGE;
if (
amount.fare.chainId &&
amount.fare.chainId !== this.acpContractClient.config.chain.id
) {
operations.push(
this.acpContractClient.createCrossChainPayableMemo(
this.id,
content,
amount.fare.contractAddress,
amount.amount,
recipient,
isPercentagePricing
? BigInt(Math.round(this.priceValue * 10000)) // convert to basis points
: feeAmount.amount,
isPercentagePricing ? FeeType.PERCENTAGE_FEE : FeeType.NO_FEE,
type as MemoType.PAYABLE_REQUEST,
expiredAt,
AcpJobPhases.TRANSACTION,
getDestinationEndpointId(amount.fare.chainId as number)
)
);
} else {
operations.push(
this.acpContractClient.createPayableMemo(
this.id,
content,
amount.amount,
recipient,
isPercentagePricing
? BigInt(Math.round(this.priceValue * 10000)) // convert to basis points
: feeAmount.amount,
isPercentagePricing ? FeeType.PERCENTAGE_FEE : FeeType.NO_FEE,
AcpJobPhases.TRANSACTION,
type,
expiredAt,
amount.fare.contractAddress
)
);
}
return await this.acpContractClient.handleOperation(operations);
}
async payAndAcceptRequirement(reason?: string) {
const memo = this.memos.find(
(m) =>
m.nextPhase === AcpJobPhases.TRANSACTION ||
m.nextPhase === AcpJobPhases.COMPLETED
);
if (!memo) {
throw new AcpError("No notification memo found");
}
if (
memo.type === MemoType.PAYABLE_REQUEST &&
memo.state !== AcpMemoState.PENDING &&
memo.payableDetails?.lzDstEid !== undefined &&
memo.payableDetails?.lzDstEid !== 0
) {
// Payable request memo required to be in pending state
return;
}
const operations: OperationPayload[] = [];
const baseFareAmount = new FareAmount(this.price, this.baseFare);
const transferAmount = memo.payableDetails
? await FareAmountBase.fromContractAddress(
memo.payableDetails.amount,
memo.payableDetails.token,
this.config
)
: new FareAmount(0, this.baseFare);
const totalAmount =
baseFareAmount.fare.contractAddress ===
transferAmount.fare.contractAddress
? baseFareAmount.add(transferAmount)
: baseFareAmount;
operations.push(
this.acpContractClient.approveAllowance(
totalAmount.amount,
this.baseFare.contractAddress
)
);
if (
baseFareAmount.fare.contractAddress !==
transferAmount.fare.contractAddress
) {
operations.push(
this.acpContractClient.approveAllowance(
transferAmount.amount,
transferAmount.fare.contractAddress
)
);
}
operations.push(this.acpContractClient.signMemo(memo.id, true, reason));
operations.push(
this.acpContractClient.createMemo(
this.id,
`Payment made. ${reason ?? ""}`.trim(),
MemoType.MESSAGE,
true,
AcpJobPhases.EVALUATION
)
);
if (memo.payableDetails) {
const destinationChainId = memo.payableDetails.lzDstEid
? getDestinationChainId(memo.payableDetails.lzDstEid)
: this.config.chain.id;
if (destinationChainId !== this.config.chain.id) {
if (memo.type === MemoType.PAYABLE_REQUEST) {
const tokenBalance = await this.acpContractClient.getERC20Balance(
destinationChainId,
memo.payableDetails.token,
this.acpContractClient.agentWalletAddress
);
if (tokenBalance < memo.payableDetails.amount) {
const tokenDecimals = await this.acpContractClient.getERC20Decimals(
destinationChainId,
memo.payableDetails.token
);
const tokenSymbol = await this.acpContractClient.getERC20Symbol(
destinationChainId,
memo.payableDetails.token
);
throw new Error(
`You do not have enough funds to pay for the job which costs ${formatUnits(
memo.payableDetails.amount,
tokenDecimals
)} ${tokenSymbol} on chainId ${destinationChainId}`
);
}
const assetManagerAddress =
await this.acpContractClient.getAssetManager();
const allowance = await this.acpContractClient.getERC20Allowance(
destinationChainId,
memo.payableDetails.token,
this.acpContractClient.agentWalletAddress,
assetManagerAddress
);
const destinationChainOperations: OperationPayload[] = [];
destinationChainOperations.push(
this.acpContractClient.approveAllowance(
memo.payableDetails.amount + allowance,
memo.payableDetails.token,
assetManagerAddress
)
);
await this.acpContractClient.handleOperation(
destinationChainOperations,
destinationChainId
);
}
}
}
if (this.price > 0) {
const x402PaymentDetails =
await this.acpContractClient.getX402PaymentDetails(this.id);
if (x402PaymentDetails.isX402) {
await this.performX402Payment(this.price);
}
}
return await this.acpContractClient.handleOperation(operations);
}
async respond(accept: boolean, reason?: string) {
const memoContent = `${
reason || `Job ${this.id} ${accept ? "accepted" : "rejected"}.`
}`;
if (accept) {
await this.accept(memoContent);
return this.createRequirement(memoContent);
}
return await this.reject(memoContent);
}
async accept(reason?: string) {
const memoContent = `Job ${this.id} accepted. ${reason || ""}`;
const latestMemo = this.latestMemo;
if (latestMemo?.nextPhase !== AcpJobPhases.NEGOTIATION) {
throw new AcpError("No request memo found");
}
return await latestMemo.sign(true, memoContent);
}
async reject(reason?: string) {
const hasPendingRejectionMemo = this.memos.some(
(m) =>
m.nextPhase === AcpJobPhases.REJECTED
);
if (hasPendingRejectionMemo) {
throw new AcpError("There is already a pending rejection memo for this job");
}
const memoContent = `Job ${this.id} rejected. ${reason || ""}`;
const isProviderRequestPhase: boolean = (
this.providerAddress === this.acpClient.walletAddress &&
this.phase === AcpJobPhases.REQUEST
);
const isClientPaymentPhase: boolean = (
this.clientAddress === this.acpClient.walletAddress &&
this.phase === AcpJobPhases.NEGOTIATION
);
if (isProviderRequestPhase) {
const latestMemo = this.latestMemo;
if (latestMemo?.nextPhase !== AcpJobPhases.NEGOTIATION) {
throw new AcpError("No request memo found");
}
return await latestMemo.sign(false, memoContent);
}
if (isClientPaymentPhase) {
const latestMemo = this.latestMemo;
if (latestMemo?.nextPhase !== AcpJobPhases.TRANSACTION) {
throw new AcpError("No payment memo found");
}
return await latestMemo.sign(false, memoContent);
}
const operations: OperationPayload[] = [];
operations.push(
this.acpContractClient.createMemo(
this.id,
memoContent,
MemoType.MESSAGE,
true,
AcpJobPhases.REJECTED
)
);
return await this.acpContractClient.handleOperation(operations);
}
async rejectPayable(
reason: string = "",
amount: FareAmountBase,
expiredAt: Date = new Date(Date.now() + 1000 * 60 * 5) // 5 minutes
) {
const memoContent = `Job ${this.id} rejected. ${reason}`;
const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
const operations: OperationPayload[] = [];
operations.push(
this.acpContractClient.approveAllowance(
amount.amount,
amount.fare.contractAddress
)
);
operations.push(
this.acpContractClient.createPayableMemo(
this.id,
memoContent,
amount.amount,
this.clientAddress,
feeAmount.amount,
FeeType.NO_FEE,
AcpJobPhases.REJECTED,
MemoType.PAYABLE_TRANSFER,
expiredAt,
amount.fare.contractAddress
)
);
return await this.acpContractClient.handleOperation(operations);
}
async deliver(deliverable: DeliverablePayload) {
if (this.phase !== AcpJobPhases.TRANSACTION) {
throw new AcpError("Job is not in transaction phase");
}
const operations: OperationPayload[] = [];
const memoContent = await this.acpClient.createMemoContent(
this.id,
preparePayload(deliverable)
);
operations.push(
this.acpContractClient.createMemo(
this.id,
memoContent?.url,
MemoType.CONTEXT_URL,
true,
AcpJobPhases.COMPLETED
)
);
return await this.acpContractClient.handleOperation(operations);
}
async deliverPayable(
deliverable: DeliverablePayload,
amount: FareAmountBase,
skipFee: boolean = false,
expiredAt: Date = new Date(Date.now() + 1000 * 60 * 5) // 5 minutes
) {
// If payable chain belongs to non ACP native chain, we route to transfer service
if (amount.fare.chainId !== this.acpContractClient.config.chain.id) {
return await this.deliverCrossChainPayable(
this.clientAddress,
preparePayload(deliverable),
amount,
skipFee
);
}
const operations: OperationPayload[] = [];
operations.push(
this.acpContractClient.approveAllowance(
amount.amount,
amount.fare.contractAddress
)
);
const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
const isPercentagePricing: boolean =
this.priceType === PriceType.PERCENTAGE && !skipFee;
const memoContent = await this.acpClient.createMemoContent(
this.id,
preparePayload(deliverable)
);
operations.push(
this.acpContractClient.createPayableMemo(
this.id,
memoContent.url,
amount.amount,
this.clientAddress,
isPercentagePricing
? BigInt(Math.round(this.priceValue * 10000)) // convert to basis points
: feeAmount.amount,
isPercentagePricing ? FeeType.PERCENTAGE_FEE : FeeType.NO_FEE,
AcpJobPhases.COMPLETED,
MemoType.PAYABLE_TRANSFER,
expiredAt,
amount.fare.contractAddress
)
);
return await this.acpContractClient.handleOperation(operations);
}
async evaluate(accept: boolean, reason?: string) {
if (this.latestMemo?.nextPhase !== AcpJobPhases.COMPLETED) {
throw new AcpError("No evaluation memo found");
}
const memo = this.latestMemo;
await memo.sign(accept, reason);
}
async createNotification(content: string) {
const operations: OperationPayload[] = [];
operations.push(
this.acpContractClient.createMemo(
this.id,
content,
MemoType.NOTIFICATION,
true,
AcpJobPhases.COMPLETED
)
);
return await this.acpContractClient.handleOperation(operations);
}
async createPayableNotification(
content: string,
amount: FareAmountBase,
skipFee: boolean = false,
expiredAt: Date = new Date(Date.now() + 1000 * 60 * 5) // 5 minutes
) {
const operations: OperationPayload[] = [];
operations.push(
this.acpContractClient.approveAllowance(
amount.amount,
amount.fare.contractAddress
)
);
const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
const isPercentagePricing: boolean =
this.priceType === PriceType.PERCENTAGE && !skipFee;
operations.push(
this.acpContractClient.createPayableMemo(
this.id,
content,
amount.amount,
this.clientAddress,
isPercentagePricing
? BigInt(Math.round(this.priceValue * 10000)) // convert to basis points
: feeAmount.amount,
isPercentagePricing ? FeeType.PERCENTAGE_FEE : FeeType.NO_FEE,
AcpJobPhases.COMPLETED,
MemoType.PAYABLE_NOTIFICATION,
expiredAt,
amount.fare.contractAddress
)
);
return await this.acpContractClient.handleOperation(operations);
}
private async performX402Payment(budget: number) {
const paymentUrl = "/acp-budget";
const x402PayableREquirements =
await this.acpContractClient.performX402Request(
paymentUrl,
this.acpContractClient.getAcpVersion(),
budget.toString()
);
if (!x402PayableREquirements.isPaymentRequired) {
return;
}
if (!x402PayableREquirements.data.accepts.length) {
throw new AcpError("No X402 payment requirements found");
}
const requirement = x402PayableREquirements.data.accepts[0];
const { encodedPayment, signature, message } =
await this.acpContractClient.generateX402Payment(
{
to: requirement.payTo,
value: Number(requirement.maxAmountRequired),
maxTimeoutSeconds: requirement.maxTimeoutSeconds,
asset: requirement.asset,
},
x402PayableREquirements.data
);
await this.acpContractClient.updateJobX402Nonce(this.id, message.nonce);
const x402Response = await this.acpContractClient.performX402Request(
paymentUrl,
this.acpContractClient.getAcpVersion(),
budget.toString(),
encodedPayment
);
if (x402Response.isPaymentRequired) {
const operations =
await this.acpContractClient.submitTransferWithAuthorization(
message.from,
message.to,
BigInt(message.value),
BigInt(message.validAfter),
BigInt(message.validBefore),
message.nonce,
signature
);
await this.acpContractClient.handleOperation(operations);
}
let waitMs = 2000;
const maxWaitMs = 30000; // max 30 seconds of polling
let iterationCount = 0;
const maxIterations = 10;
while (true) {
const x402PaymentDetails =
await this.acpContractClient.getX402PaymentDetails(this.id);
if (x402PaymentDetails.isBudgetReceived) {
break;
}
iterationCount++;
if (iterationCount >= maxIterations) {
throw new AcpError("X402 payment timed out");
}
await new Promise((resolve) => setTimeout(resolve, waitMs));
waitMs = Math.min(waitMs * 2, maxWaitMs);
}
}
async deliverCrossChainPayable(
recipient: Address,
content: string,
amount: FareAmountBase,
skipFee: boolean = false
) {
if (!amount.fare.chainId) {
throw new AcpError("Chain ID is required for cross chain payable");
}
const chainId = amount.fare.chainId;
const assetManagerAddress = await this.acpContractClient.getAssetManager();
// Check if wallet has enough balance on destination chain
const tokenBalance = await this.acpContractClient.getERC20Balance(
chainId,
amount.fare.contractAddress,
this.acpContractClient.agentWalletAddress
);
if (tokenBalance < amount.amount) {
throw new AcpError("Insufficient token balance for cross chain payable");
}
const currentAllowance = await this.acpContractClient.getERC20Allowance(
chainId,
amount.fare.contractAddress,
this.acpContractClient.agentWalletAddress,
assetManagerAddress
);
// Approve allowance to asset manager on destination chain
const approveAllowanceOperation = this.acpContractClient.approveAllowance(
amount.amount + currentAllowance,
amount.fare.contractAddress,
assetManagerAddress
);
await this.acpContractClient.handleOperation(
[approveAllowanceOperation],
chainId
);
const tokenSymbol = await this.acpContractClient.getERC20Symbol(
chainId,
amount.fare.contractAddress
);
const feeAmount = new FareAmount(0, this.acpContractClient.config.baseFare);
const isPercentagePricing: boolean =
this.priceType === PriceType.PERCENTAGE && !skipFee;
const createMemoOperation =
this.acpContractClient.createCrossChainPayableMemo(
this.id,
content,
amount.fare.contractAddress,
amount.amount,
recipient,
isPercentagePricing
? BigInt(Math.round(this.priceValue * 10000))
: feeAmount.amount,
isPercentagePricing ? FeeType.PERCENTAGE_FEE : FeeType.NO_FEE,
MemoType.PAYABLE_TRANSFER,
new Date(Date.now() + 1000 * 60 * 5),
AcpJobPhases.COMPLETED,
getDestinationEndpointId(chainId)
);
await this.acpContractClient.handleOperation([createMemoOperation]);
}
[util.inspect.custom]() {
return {
id: this.id,
clientAddress: this.clientAddress,
providerAddress: this.providerAddress,
name: this.name,
requirement: this.requirement,
priceType: this.priceType,
priceValue: this.priceValue,
priceTokenAddress: this.priceTokenAddress,
memos: this.memos,
phase: this.phase,
context: this.context,
contractAddress: this.contractAddress,
netPayableAmount: this.netPayableAmount,
};
}
}
export default AcpJob;