sdk-triggerx 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/.eslintrc.json +16 -0
  2. package/README.md +249 -0
  3. package/dist/api/jobs.d.ts +15 -0
  4. package/dist/api/jobs.js +138 -0
  5. package/dist/api/tasks.d.ts +4 -0
  6. package/dist/api/tasks.js +13 -0
  7. package/dist/client.d.ts +7 -0
  8. package/dist/client.js +27 -0
  9. package/dist/config.d.ts +6 -0
  10. package/dist/config.js +15 -0
  11. package/dist/contracts/JobRegistry.d.ts +12 -0
  12. package/dist/contracts/JobRegistry.js +26 -0
  13. package/dist/contracts/TriggerXContract.d.ts +6 -0
  14. package/dist/contracts/TriggerXContract.js +14 -0
  15. package/dist/contracts/abi/JobRegistry.json +1554 -0
  16. package/dist/contracts/index.d.ts +1 -0
  17. package/dist/contracts/index.js +17 -0
  18. package/dist/index.d.ts +8 -0
  19. package/dist/index.js +26 -0
  20. package/dist/src/api/checkTgBalance.d.ts +2 -0
  21. package/dist/src/api/checkTgBalance.js +35 -0
  22. package/dist/src/api/deleteJob.d.ts +2 -0
  23. package/dist/src/api/deleteJob.js +20 -0
  24. package/dist/src/api/getJobDataById.d.ts +3 -0
  25. package/dist/src/api/getJobDataById.js +21 -0
  26. package/dist/src/api/getUserData.d.ts +3 -0
  27. package/dist/src/api/getUserData.js +21 -0
  28. package/dist/src/api/getjob.d.ts +8 -0
  29. package/dist/src/api/getjob.js +23 -0
  30. package/dist/src/api/jobs.d.ts +18 -0
  31. package/dist/src/api/jobs.js +270 -0
  32. package/dist/src/api/tasks.d.ts +4 -0
  33. package/dist/src/api/tasks.js +13 -0
  34. package/dist/src/api/topupTg.d.ts +2 -0
  35. package/dist/src/api/topupTg.js +19 -0
  36. package/dist/src/api/withdrawTg.d.ts +8 -0
  37. package/dist/src/api/withdrawTg.js +27 -0
  38. package/dist/src/client.d.ts +10 -0
  39. package/dist/src/client.js +37 -0
  40. package/dist/src/config.d.ts +6 -0
  41. package/dist/src/config.js +15 -0
  42. package/dist/src/contracts/JobRegistry.d.ts +12 -0
  43. package/dist/src/contracts/JobRegistry.js +24 -0
  44. package/dist/src/contracts/TriggerXContract.d.ts +6 -0
  45. package/dist/src/contracts/TriggerXContract.js +14 -0
  46. package/dist/src/contracts/abi/GasRegistry.json +607 -0
  47. package/dist/src/contracts/abi/JobRegistry.json +1554 -0
  48. package/dist/src/contracts/index.d.ts +1 -0
  49. package/dist/src/contracts/index.js +17 -0
  50. package/dist/src/index.d.ts +7 -0
  51. package/dist/src/index.js +25 -0
  52. package/dist/src/types.d.ts +246 -0
  53. package/dist/src/types.js +15 -0
  54. package/dist/src/utils/errors.d.ts +4 -0
  55. package/dist/src/utils/errors.js +17 -0
  56. package/dist/test/createJobExample.d.ts +1 -0
  57. package/dist/test/createJobExample.js +77 -0
  58. package/dist/test/deleteJob.test.d.ts +1 -0
  59. package/dist/test/deleteJob.test.js +22 -0
  60. package/dist/test/example.test.d.ts +1 -0
  61. package/dist/test/example.test.js +11 -0
  62. package/dist/test/getJobDataById.test.d.ts +1 -0
  63. package/dist/test/getJobDataById.test.js +23 -0
  64. package/dist/test/getUserData.test.d.ts +1 -0
  65. package/dist/test/getUserData.test.js +22 -0
  66. package/dist/test/getjob.test.d.ts +1 -0
  67. package/dist/test/getjob.test.js +21 -0
  68. package/dist/test/testTgFunctions.d.ts +1 -0
  69. package/dist/test/testTgFunctions.js +56 -0
  70. package/dist/types.d.ts +134 -0
  71. package/dist/types.js +15 -0
  72. package/dist/utils/errors.d.ts +4 -0
  73. package/dist/utils/errors.js +17 -0
  74. package/jest.config.js +7 -0
  75. package/package.json +32 -0
  76. package/scripts/deploy.ts +9 -0
  77. package/src/api/checkTgBalance.ts +27 -0
  78. package/src/api/deleteJob.ts +22 -0
  79. package/src/api/getJobDataById.ts +24 -0
  80. package/src/api/getUserData.ts +24 -0
  81. package/src/api/getjob.ts +26 -0
  82. package/src/api/jobs.ts +303 -0
  83. package/src/api/topupTg.ts +17 -0
  84. package/src/api/withdrawTg.ts +25 -0
  85. package/src/client.ts +38 -0
  86. package/src/config.ts +16 -0
  87. package/src/contracts/JobRegistry.ts +45 -0
  88. package/src/contracts/TriggerXContract.ts +14 -0
  89. package/src/contracts/abi/.gitkeep +1 -0
  90. package/src/contracts/abi/GasRegistry.json +607 -0
  91. package/src/contracts/abi/JobRegistry.json +1554 -0
  92. package/src/contracts/index.ts +1 -0
  93. package/src/index.ts +7 -0
  94. package/src/types.ts +262 -0
  95. package/src/utils/errors.ts +13 -0
  96. package/test/createJobExample.ts +84 -0
  97. package/test/deleteJob.test.ts +25 -0
  98. package/test/example.test.d.ts +1 -0
  99. package/test/example.test.js +11 -0
  100. package/test/example.test.ts +10 -0
  101. package/test/getJobDataById.test.ts +27 -0
  102. package/test/getUserData.test.ts +25 -0
  103. package/test/getjob.test.ts +23 -0
  104. package/test/testTgFunctions.ts +56 -0
  105. package/tsconfig.json +16 -0
@@ -0,0 +1 @@
1
+ export * from './TriggerXContract';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./TriggerXContract"), exports);
@@ -0,0 +1,8 @@
1
+ export * from './client';
2
+ export * from './config';
3
+ export * from './types';
4
+ export * from './api/tasks';
5
+ export * from './api/jobs';
6
+ export { createJobOnChain } from './contracts/JobRegistry';
7
+ export * from './contracts';
8
+ export * from './utils/errors';
package/dist/index.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.createJobOnChain = void 0;
18
+ __exportStar(require("./client"), exports);
19
+ __exportStar(require("./config"), exports);
20
+ __exportStar(require("./types"), exports);
21
+ __exportStar(require("./api/tasks"), exports);
22
+ __exportStar(require("./api/jobs"), exports);
23
+ var JobRegistry_1 = require("./contracts/JobRegistry");
24
+ Object.defineProperty(exports, "createJobOnChain", { enumerable: true, get: function () { return JobRegistry_1.createJobOnChain; } });
25
+ __exportStar(require("./contracts"), exports);
26
+ __exportStar(require("./utils/errors"), exports);
@@ -0,0 +1,2 @@
1
+ import { ethers } from 'ethers';
2
+ export declare const checkTgBalance: (signer: ethers.Signer) => Promise<string>;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.checkTgBalance = void 0;
7
+ const ethers_1 = require("ethers");
8
+ const GasRegistry_json_1 = __importDefault(require("../contracts/abi/GasRegistry.json"));
9
+ const checkTgBalance = async (signer) => {
10
+ const gasRegistryContractAddress = process.env.GAS_REGISTRY_CONTRACT_ADDRESS || '0x85ea3eB894105bD7e7e2A8D34cf66C8E8163CD2a';
11
+ if (!gasRegistryContractAddress) {
12
+ throw new Error('GAS_REGISTRY_CONTRACT_ADDRESS is not set in the environment variables');
13
+ }
14
+ const contract = new ethers_1.ethers.Contract(gasRegistryContractAddress, GasRegistry_json_1.default, signer);
15
+ const address = await signer.getAddress();
16
+ const balance = await contract.balances(address);
17
+ // balance is likely an array or object with ethSpent and TGbalance, both in wei
18
+ // We'll convert TGbalance from wei to ETH
19
+ // If balance is an array: [ethSpent, TGbalance]
20
+ // If balance is an object: { ethSpent, TGbalance }
21
+ let tgBalanceWei;
22
+ if (Array.isArray(balance)) {
23
+ tgBalanceWei = balance[1];
24
+ }
25
+ else if (balance && balance.TGbalance !== undefined) {
26
+ tgBalanceWei = balance.TGbalance;
27
+ }
28
+ else {
29
+ throw new Error('Unexpected balance format');
30
+ }
31
+ const tgBalanceEth = ethers_1.ethers.formatEther(tgBalanceWei);
32
+ console.log('tgBalanceEth', tgBalanceEth);
33
+ return tgBalanceEth;
34
+ };
35
+ exports.checkTgBalance = checkTgBalance;
@@ -0,0 +1,2 @@
1
+ import { TriggerXClient } from '../client';
2
+ export declare const deleteJob: (client: TriggerXClient, jobId: string) => Promise<void>;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ // sdk-triggerx/src/api/deleteJob.ts
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.deleteJob = void 0;
5
+ const deleteJob = async (client, jobId) => {
6
+ const apiKey = client.getApiKey(); // Assuming you have a method to get the API key
7
+ try {
8
+ await client.put(`api/jobs/delete/${jobId}`, {}, {
9
+ headers: {
10
+ 'Content-Type': 'application/json',
11
+ 'X-API-KEY': apiKey,
12
+ },
13
+ });
14
+ }
15
+ catch (error) {
16
+ console.error('Error deleting job:', error);
17
+ throw error; // Rethrow the error for handling in the calling function
18
+ }
19
+ };
20
+ exports.deleteJob = deleteJob;
@@ -0,0 +1,3 @@
1
+ import { TriggerXClient } from '../client';
2
+ import { JobDataAPI } from '../types';
3
+ export declare const getJobDataById: (client: TriggerXClient, jobId: string) => Promise<JobDataAPI>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ // sdk-triggerx/src/api/getJobDataById.ts
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.getJobDataById = void 0;
5
+ const getJobDataById = async (client, jobId) => {
6
+ const apiKey = client.getApiKey(); // Assuming you have a method to get the API key
7
+ try {
8
+ const response = await client.get(`/api/jobs/${jobId}`, {
9
+ headers: {
10
+ 'Content-Type': 'application/json',
11
+ 'X-API-KEY': apiKey,
12
+ },
13
+ });
14
+ return response; // Assuming the response data matches the JobDataAPI interface
15
+ }
16
+ catch (error) {
17
+ console.error('Error fetching job data by ID:', error);
18
+ throw error; // Rethrow the error for handling in the calling function
19
+ }
20
+ };
21
+ exports.getJobDataById = getJobDataById;
@@ -0,0 +1,3 @@
1
+ import { TriggerXClient } from '../client';
2
+ import { UserData } from '../types';
3
+ export declare const getUserData: (client: TriggerXClient, address: string) => Promise<UserData>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ // sdk-triggerx/src/api/getUserData.ts
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.getUserData = void 0;
5
+ const getUserData = async (client, address) => {
6
+ const apiKey = client.getApiKey(); // Assuming you have a method to get the API key
7
+ try {
8
+ const response = await client.get(`api/users/${address}`, {
9
+ headers: {
10
+ 'Content-Type': 'application/json',
11
+ 'X-API-KEY': apiKey,
12
+ },
13
+ });
14
+ return response; // Assuming the response data matches the UserData interface
15
+ }
16
+ catch (error) {
17
+ console.error('Error fetching user data:', error);
18
+ throw error; // Rethrow the error for handling in the calling function
19
+ }
20
+ };
21
+ exports.getUserData = getUserData;
@@ -0,0 +1,8 @@
1
+ import { TriggerXClient } from '../client';
2
+ import { JobResponseUser } from '../types';
3
+ /**
4
+ * Fetch job data for a given API key by calling the backend endpoint.
5
+ * @param client TriggerXClient instance
6
+ * @returns JobResponse containing job data or error
7
+ */
8
+ export declare function getJobData(client: TriggerXClient): Promise<JobResponseUser>;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getJobData = getJobData;
4
+ /**
5
+ * Fetch job data for a given API key by calling the backend endpoint.
6
+ * @param client TriggerXClient instance
7
+ * @returns JobResponse containing job data or error
8
+ */
9
+ async function getJobData(client) {
10
+ try {
11
+ const apiKey = client.getApiKey(); // Assuming you have a method to get the API key
12
+ const data = await client.get('/api/jobs/by-apikey', {
13
+ headers: {
14
+ 'Content-Type': 'application/json',
15
+ 'X-API-KEY': apiKey,
16
+ },
17
+ });
18
+ return { success: true, jobs: data.jobs };
19
+ }
20
+ catch (error) {
21
+ return { success: false, error: error.message, };
22
+ }
23
+ }
@@ -0,0 +1,18 @@
1
+ import { TriggerXClient } from '../client';
2
+ import { TimeBasedJobInput, EventBasedJobInput, ConditionBasedJobInput, CreateJobData, JobResponse } from '../types';
3
+ import { Signer } from 'ethers';
4
+ export declare function toCreateJobDataFromTime(input: TimeBasedJobInput): CreateJobData;
5
+ export declare function toCreateJobDataFromEvent(input: EventBasedJobInput): CreateJobData;
6
+ export declare function toCreateJobDataFromCondition(input: ConditionBasedJobInput): CreateJobData;
7
+ export interface CreateJobParams {
8
+ jobInput: TimeBasedJobInput | EventBasedJobInput | ConditionBasedJobInput;
9
+ signer: Signer;
10
+ encodedData?: string;
11
+ }
12
+ /**
13
+ * Create a job on the blockchain.
14
+ * @param client TriggerXClient instance
15
+ * @param params Parameters for creating the job
16
+ * @returns JobResponse containing the result of the job creation
17
+ */
18
+ export declare function createJob(client: TriggerXClient, params: CreateJobParams): Promise<JobResponse>;
@@ -0,0 +1,270 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.toCreateJobDataFromTime = toCreateJobDataFromTime;
7
+ exports.toCreateJobDataFromEvent = toCreateJobDataFromEvent;
8
+ exports.toCreateJobDataFromCondition = toCreateJobDataFromCondition;
9
+ exports.createJob = createJob;
10
+ const JobRegistry_1 = require("../contracts/JobRegistry");
11
+ const ethers_1 = require("ethers");
12
+ const JobRegistry_json_1 = __importDefault(require("../contracts/abi/JobRegistry.json"));
13
+ const topupTg_1 = require("./topupTg");
14
+ const checkTgBalance_1 = require("./checkTgBalance");
15
+ const JOB_ID = '300949528249665590178224313442040528409305273634097553067152835846309150732';
16
+ const DYNAMIC_ARGS_URL = 'https://teal-random-koala-993.mypinata.cloud/ipfs/bafkreif426p7t7takzhw3g6we2h6wsvf27p5jxj3gaiynqf22p3jvhx4la';
17
+ const JOB_REGISTRY_ADDRESS = '0xdB66c11221234C6B19cCBd29868310c31494C21C'; // Set your fixed contract address here
18
+ function toCreateJobDataFromTime(input) {
19
+ return {
20
+ job_id: JOB_ID,
21
+ user_address: input.userAddress,
22
+ ether_balance: input.etherBalance,
23
+ token_balance: input.tokenBalance,
24
+ job_title: input.jobTitle,
25
+ task_definition_id: input.dynamicArgumentsScriptUrl ? 2 : 1,
26
+ custom: true,
27
+ time_frame: input.timeFrame,
28
+ recurring: input.recurring ?? false,
29
+ job_cost_prediction: input.jobCostPrediction,
30
+ timezone: input.timezone,
31
+ created_chain_id: input.createdChainId,
32
+ schedule_type: input.scheduleType,
33
+ time_interval: input.timeInterval,
34
+ cron_expression: input.cronExpression,
35
+ specific_schedule: input.specificSchedule,
36
+ target_chain_id: input.targetChainId,
37
+ target_contract_address: input.targetContractAddress,
38
+ target_function: input.targetFunction,
39
+ abi: input.abi,
40
+ arg_type: input.dynamicArgumentsScriptUrl ? 2 : 1,
41
+ arguments: input.arguments,
42
+ dynamic_arguments_script_url: input.dynamicArgumentsScriptUrl,
43
+ is_imua: input.isImua ?? true,
44
+ };
45
+ }
46
+ function toCreateJobDataFromEvent(input) {
47
+ return {
48
+ job_id: JOB_ID,
49
+ user_address: input.userAddress,
50
+ ether_balance: input.etherBalance,
51
+ token_balance: input.tokenBalance,
52
+ job_title: input.jobTitle,
53
+ task_definition_id: input.dynamicArgumentsScriptUrl ? 4 : 3,
54
+ custom: true,
55
+ time_frame: input.timeFrame,
56
+ recurring: input.recurring ?? false,
57
+ job_cost_prediction: input.jobCostPrediction,
58
+ timezone: input.timezone,
59
+ created_chain_id: input.createdChainId,
60
+ trigger_chain_id: input.triggerChainId,
61
+ trigger_contract_address: input.triggerContractAddress,
62
+ trigger_event: input.triggerEvent,
63
+ target_chain_id: input.targetChainId,
64
+ target_contract_address: input.targetContractAddress,
65
+ target_function: input.targetFunction,
66
+ abi: input.abi,
67
+ arg_type: input.dynamicArgumentsScriptUrl ? 2 : 1,
68
+ arguments: input.arguments,
69
+ dynamic_arguments_script_url: input.dynamicArgumentsScriptUrl,
70
+ is_imua: input.isImua ?? true,
71
+ };
72
+ }
73
+ function toCreateJobDataFromCondition(input) {
74
+ return {
75
+ job_id: JOB_ID,
76
+ user_address: input.userAddress,
77
+ ether_balance: input.etherBalance,
78
+ token_balance: input.tokenBalance,
79
+ job_title: input.jobTitle,
80
+ task_definition_id: input.dynamicArgumentsScriptUrl ? 6 : 5,
81
+ custom: true,
82
+ time_frame: input.timeFrame,
83
+ recurring: input.recurring ?? false,
84
+ job_cost_prediction: input.jobCostPrediction,
85
+ timezone: input.timezone,
86
+ created_chain_id: input.createdChainId,
87
+ condition_type: input.conditionType,
88
+ upper_limit: input.upperLimit,
89
+ lower_limit: input.lowerLimit,
90
+ value_source_type: input.valueSourceType,
91
+ value_source_url: input.valueSourceUrl,
92
+ target_chain_id: input.targetChainId,
93
+ target_contract_address: input.targetContractAddress,
94
+ target_function: input.targetFunction,
95
+ abi: input.abi,
96
+ arg_type: input.dynamicArgumentsScriptUrl ? 2 : 1,
97
+ arguments: input.arguments,
98
+ dynamic_arguments_script_url: input.dynamicArgumentsScriptUrl,
99
+ is_imua: input.isImua ?? true,
100
+ };
101
+ }
102
+ // --- Encoding helpers for different job types ---
103
+ function encodeJobType1Data(timeInterval) {
104
+ return ethers_1.ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [timeInterval]);
105
+ }
106
+ function encodeJobType2Data(timeInterval, ipfsHash) {
107
+ return ethers_1.ethers.AbiCoder.defaultAbiCoder().encode(['uint256', 'bytes32'], [timeInterval, ipfsHash]);
108
+ }
109
+ function encodeJobType3or5Data(recurringJob) {
110
+ return ethers_1.ethers.AbiCoder.defaultAbiCoder().encode(['bool'], [recurringJob]);
111
+ }
112
+ function encodeJobType4or6Data(recurringJob, ipfsHash) {
113
+ return ethers_1.ethers.AbiCoder.defaultAbiCoder().encode(['bool', 'bytes32'], [recurringJob, ipfsHash]);
114
+ }
115
+ /**
116
+ * Create a job on the blockchain.
117
+ * @param client TriggerXClient instance
118
+ * @param params Parameters for creating the job
119
+ * @returns JobResponse containing the result of the job creation
120
+ */
121
+ async function createJob(client, params) {
122
+ let { jobInput, signer, encodedData } = params;
123
+ // Use the API key from the client instance
124
+ const apiKey = client.getApiKey();
125
+ let jobTitle, timeFrame, targetContractAddress, jobType;
126
+ if ('jobTitle' in jobInput)
127
+ jobTitle = jobInput.jobTitle;
128
+ if ('timeFrame' in jobInput)
129
+ timeFrame = jobInput.timeFrame;
130
+ if ('targetContractAddress' in jobInput)
131
+ targetContractAddress = jobInput.targetContractAddress;
132
+ // Infer jobType from jobInput
133
+ if ('scheduleType' in jobInput) {
134
+ jobType = jobInput.dynamicArgumentsScriptUrl ? 2 : 1; // Time-based job
135
+ }
136
+ else if ('triggerChainId' in jobInput) {
137
+ jobType = jobInput.dynamicArgumentsScriptUrl ? 4 : 3; // Event-based job
138
+ }
139
+ else {
140
+ jobType = jobInput.dynamicArgumentsScriptUrl ? 6 : 5; // Condition-based job
141
+ }
142
+ // --- Generate encodedData if not provided ---
143
+ if (!encodedData) {
144
+ // Time-based jobs
145
+ if ('scheduleType' in jobInput) {
146
+ if (jobType === 1) {
147
+ encodedData = encodeJobType1Data(jobInput.timeInterval ?? 0);
148
+ }
149
+ else if (jobType === 2) {
150
+ encodedData = encodeJobType2Data(jobInput.timeInterval ?? 0, jobInput.dynamicArgumentsScriptUrl || '');
151
+ }
152
+ }
153
+ // Event-based jobs
154
+ else if ('triggerChainId' in jobInput) {
155
+ if (jobType === 3 || jobType === 5) {
156
+ encodedData = encodeJobType3or5Data(jobInput.recurring ?? false);
157
+ }
158
+ else if (jobType === 4 || jobType === 6) {
159
+ encodedData = encodeJobType4or6Data(jobInput.recurring ?? false, jobInput.dynamicArgumentsScriptUrl || '');
160
+ }
161
+ }
162
+ // Condition-based jobs
163
+ else {
164
+ if (jobType === 3 || jobType === 5) {
165
+ encodedData = encodeJobType3or5Data(jobInput.recurring ?? false);
166
+ }
167
+ else if (jobType === 4 || jobType === 6) {
168
+ encodedData = encodeJobType4or6Data(jobInput.recurring ?? false, jobInput.dynamicArgumentsScriptUrl || '');
169
+ }
170
+ }
171
+ }
172
+ // Handle job_cost_prediction logic based on argType (static/dynamic)
173
+ // If static, set to 0.1. If dynamic, call backend API to get fee and ask user to proceed.
174
+ // Determine argType directly from user input
175
+ let argType = 1; // default to static
176
+ if ('argType' in jobInput) {
177
+ if (jobInput.argType === 'dynamic' || jobInput.argType === 2) {
178
+ argType = 2;
179
+ }
180
+ else {
181
+ argType = 1;
182
+ }
183
+ }
184
+ //if jobis time based then check the no of executions of the job from time frame and time interval by deviding time frame by time interval
185
+ let noOfExecutions = 1;
186
+ if ('scheduleType' in jobInput) {
187
+ noOfExecutions = jobInput.timeFrame / (jobInput.timeInterval ?? 0);
188
+ }
189
+ // Set job_cost_prediction
190
+ let job_cost_prediction = 0.1 * noOfExecutions; // default for static
191
+ if (argType === 2) {
192
+ // Dynamic: call backend API to get fee
193
+ const ipfs_url = jobInput.dynamicArgumentsScriptUrl;
194
+ if (!ipfs_url) {
195
+ throw new Error('dynamicArgumentsScriptUrl is required for dynamic argType');
196
+ }
197
+ // Call backend API to get fee
198
+ let fee = 0;
199
+ try {
200
+ const feeRes = await client.get('/api/fees', { params: { ipfs_url } });
201
+ // The API now returns { total_fee: number }
202
+ if (feeRes && typeof feeRes.total_fee === 'number') {
203
+ fee = feeRes.total_fee;
204
+ }
205
+ else if (feeRes && feeRes.data && typeof feeRes.data.total_fee === 'number') {
206
+ fee = feeRes.data.total_fee;
207
+ }
208
+ else {
209
+ throw new Error('Invalid response from /api/fees: missing total_fee');
210
+ }
211
+ }
212
+ catch (err) {
213
+ throw new Error('Failed to fetch job cost prediction: ' + err.message);
214
+ }
215
+ job_cost_prediction = fee * noOfExecutions;
216
+ }
217
+ // Ask user if they want to proceed
218
+ // Since this is a library, we can't prompt in Node.js directly.
219
+ // We'll throw an error with the fee and let the caller handle the prompt/confirmation.
220
+ // If you want to automate, you can add a `proceed` flag to params in the future.
221
+ // Check if the user has enough TG to cover the job cost prediction
222
+ const tgBalance = await (0, checkTgBalance_1.checkTgBalance)(signer);
223
+ if (Number(tgBalance) < job_cost_prediction) {
224
+ // Check if user has enabled auto topup
225
+ // For each job type, autotopupTG should be present in jobInput
226
+ const autoTopupTG = jobInput.autotopupTG === true;
227
+ if (!autoTopupTG) {
228
+ throw new Error(`Insufficient TG balance. Job cost prediction is ${job_cost_prediction}. Current TG balance: ${tgBalance}. Please set autotopupTG: true in jobInput.`);
229
+ }
230
+ else {
231
+ // autotopupTG is true, automatically top up
232
+ await (0, topupTg_1.topupTg)(job_cost_prediction, signer);
233
+ }
234
+ }
235
+ // Patch jobInput with job_cost_prediction for downstream usage
236
+ jobInput.jobCostPrediction = job_cost_prediction;
237
+ const jobId = await (0, JobRegistry_1.createJobOnChain)({
238
+ jobTitle: jobTitle,
239
+ jobType,
240
+ timeFrame: timeFrame,
241
+ targetContractAddress: targetContractAddress,
242
+ encodedData: encodedData || '',
243
+ contractAddress: JOB_REGISTRY_ADDRESS,
244
+ abi: JobRegistry_json_1.default.abi,
245
+ signer,
246
+ });
247
+ // 2. Convert input to CreateJobData
248
+ let jobData;
249
+ if ('scheduleType' in jobInput) {
250
+ jobData = toCreateJobDataFromTime(jobInput);
251
+ }
252
+ else if ('triggerChainId' in jobInput) {
253
+ jobData = toCreateJobDataFromEvent(jobInput);
254
+ }
255
+ else {
256
+ jobData = toCreateJobDataFromCondition(jobInput);
257
+ }
258
+ // 3. Set the job_id from contract
259
+ jobData.job_id = jobId;
260
+ // 4. Call the API
261
+ try {
262
+ const res = await client.post('/api/jobs', [jobData], {
263
+ headers: { 'Content-Type': 'application/json', 'X-API-KEY': apiKey },
264
+ });
265
+ return { success: true, data: res };
266
+ }
267
+ catch (error) {
268
+ return { success: false, error: error.message };
269
+ }
270
+ }
@@ -0,0 +1,4 @@
1
+ import { TriggerXClient } from '../client';
2
+ import { Task, ApiResponse } from '../types';
3
+ export declare function getTasks(client: TriggerXClient): Promise<ApiResponse<Task[]>>;
4
+ export declare function createTask(client: TriggerXClient, task: Partial<Task>): Promise<ApiResponse<Task>>;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTasks = getTasks;
4
+ exports.createTask = createTask;
5
+ async function getTasks(client) {
6
+ // Placeholder implementation
7
+ return client.get('/tasks');
8
+ }
9
+ async function createTask(client, task) {
10
+ // Placeholder implementation
11
+ // return client.post<ApiResponse<Task>>('/tasks', task);
12
+ return { data: { id: '1', name: task.name || '', status: 'pending', createdAt: new Date().toISOString() } };
13
+ }
@@ -0,0 +1,2 @@
1
+ import { ethers } from 'ethers';
2
+ export declare const topupTg: (tgAmount: number, signer: ethers.Signer) => Promise<any>;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.topupTg = void 0;
7
+ const ethers_1 = require("ethers");
8
+ const GasRegistry_json_1 = __importDefault(require("../contracts/abi/GasRegistry.json"));
9
+ const topupTg = async (tgAmount, signer) => {
10
+ const gasRegistryContractAddress = process.env.GAS_REGISTRY_CONTRACT_ADDRESS || '0x85ea3eB894105bD7e7e2A8D34cf66C8E8163CD2a';
11
+ const contract = new ethers_1.ethers.Contract(gasRegistryContractAddress, GasRegistry_json_1.default, signer);
12
+ // Each TG costs 0.001 ETH, so calculate the ETH required for the given TG amount
13
+ const amountInEth = tgAmount * 0.001;
14
+ const amountInEthWei = ethers_1.ethers.parseEther(amountInEth.toString());
15
+ const tx = await contract.purchaseTG(amountInEthWei, { value: amountInEthWei });
16
+ await tx.wait();
17
+ return tx;
18
+ };
19
+ exports.topupTg = topupTg;
@@ -0,0 +1,8 @@
1
+ import { ethers } from 'ethers';
2
+ /**
3
+ * Withdraw ETH in exchange for TG tokens.
4
+ * @param signer ethers.Signer instance
5
+ * @param amountTG The amount of TG tokens to withdraw (as a string or BigNumberish)
6
+ * @returns The transaction object
7
+ */
8
+ export declare const withdrawTg: (signer: ethers.Signer, amountTG: string | ethers.BigNumberish) => Promise<any>;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.withdrawTg = void 0;
7
+ const ethers_1 = require("ethers");
8
+ const GasRegistry_json_1 = __importDefault(require("../contracts/abi/GasRegistry.json"));
9
+ /**
10
+ * Withdraw ETH in exchange for TG tokens.
11
+ * @param signer ethers.Signer instance
12
+ * @param amountTG The amount of TG tokens to withdraw (as a string or BigNumberish)
13
+ * @returns The transaction object
14
+ */
15
+ const withdrawTg = async (signer, amountTG) => {
16
+ const gasRegistryContractAddress = process.env.GAS_REGISTRY_CONTRACT_ADDRESS || '0x85ea3eB894105bD7e7e2A8D34cf66C8E8163CD2a';
17
+ if (!gasRegistryContractAddress) {
18
+ throw new Error('GAS_REGISTRY_CONTRACT_ADDRESS is not set in the environment variables');
19
+ }
20
+ const contract = new ethers_1.ethers.Contract(gasRegistryContractAddress, GasRegistry_json_1.default, signer);
21
+ // Assumes the contract has a function: claimEthForTg(uint256 amount)
22
+ const amountTGWei = ethers_1.ethers.parseEther(amountTG.toString());
23
+ const tx = await contract.claimETHForTG(amountTGWei);
24
+ await tx.wait();
25
+ return tx;
26
+ };
27
+ exports.withdrawTg = withdrawTg;
@@ -0,0 +1,10 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ export declare class TriggerXClient {
3
+ private client;
4
+ private apiKey;
5
+ constructor(apiKey: string, config?: AxiosRequestConfig);
6
+ getApiKey(): string;
7
+ get<T>(url: string, config?: AxiosRequestConfig): Promise<T>;
8
+ post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
9
+ put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
10
+ }
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.TriggerXClient = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const config_1 = require("./config");
9
+ class TriggerXClient {
10
+ constructor(apiKey, config) {
11
+ this.apiKey = apiKey; // Initialize the apiKey
12
+ const baseConfig = (0, config_1.getConfig)();
13
+ this.client = axios_1.default.create({
14
+ baseURL: config?.baseURL || baseConfig.apiUrl || 'http://localhost:9002',
15
+ headers: { 'Authorization': `Bearer ${this.apiKey}` }, // Set the API key here
16
+ ...config,
17
+ });
18
+ }
19
+ // Method to get the API key
20
+ getApiKey() {
21
+ return this.apiKey;
22
+ }
23
+ async get(url, config) {
24
+ const response = await this.client.get(url, config);
25
+ return response.data;
26
+ }
27
+ async post(url, data, config) {
28
+ const response = await this.client.post(url, data, config);
29
+ return response.data;
30
+ }
31
+ // New PUT method
32
+ async put(url, data, config) {
33
+ const response = await this.client.put(url, data, config);
34
+ return response.data;
35
+ }
36
+ }
37
+ exports.TriggerXClient = TriggerXClient;
@@ -0,0 +1,6 @@
1
+ export interface SDKConfig {
2
+ apiKey: string;
3
+ apiUrl: string;
4
+ contractAddress: string;
5
+ }
6
+ export declare function getConfig(): SDKConfig;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getConfig = getConfig;
7
+ const dotenv_1 = __importDefault(require("dotenv"));
8
+ dotenv_1.default.config();
9
+ function getConfig() {
10
+ return {
11
+ apiKey: process.env.API_KEY || '',
12
+ apiUrl: process.env.API_URL || '',
13
+ contractAddress: process.env.CONTRACT_ADDRESS || '',
14
+ };
15
+ }