@vleap/warps-adapter-fastset 0.1.0-alpha.2

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 ADDED
@@ -0,0 +1,623 @@
1
+ // src/constants.ts
2
+ var WarpFastsetConstants = {
3
+ ChainName: "fastset",
4
+ ChainPrefix: "fastset",
5
+ Pi: {
6
+ Identifier: "PI",
7
+ DisplayName: "Pi",
8
+ Decimals: 18
9
+ },
10
+ GasLimit: {
11
+ Default: 21e3,
12
+ ContractCall: 1e5,
13
+ ContractDeploy: 5e5,
14
+ Transfer: 21e3,
15
+ Approve: 46e3,
16
+ Swap: 2e5
17
+ },
18
+ GasPrice: {
19
+ Default: "20000000000",
20
+ // 20 gwei
21
+ Low: "10000000000",
22
+ // 10 gwei
23
+ Medium: "20000000000",
24
+ // 20 gwei
25
+ High: "50000000000"
26
+ // 50 gwei
27
+ },
28
+ Network: {
29
+ Mainnet: {
30
+ ChainId: "1",
31
+ Name: "Fastset Mainnet",
32
+ BlockTime: 12
33
+ },
34
+ Testnet: {
35
+ ChainId: "11155111",
36
+ Name: "Fastset Testnet",
37
+ BlockTime: 12
38
+ },
39
+ Devnet: {
40
+ ChainId: "1337",
41
+ Name: "Fastset Devnet",
42
+ BlockTime: 12
43
+ }
44
+ },
45
+ Validation: {
46
+ AddressLength: 42,
47
+ HexPrefix: "0x",
48
+ MinGasLimit: 21e3,
49
+ MaxGasLimit: 3e7
50
+ },
51
+ Timeouts: {
52
+ DefaultRpcTimeout: 3e4,
53
+ // 30 seconds
54
+ GasEstimationTimeout: 1e4,
55
+ // 10 seconds
56
+ QueryTimeout: 15e3
57
+ // 15 seconds
58
+ }
59
+ };
60
+
61
+ // src/WarpFastsetBuilder.ts
62
+ var WarpFastsetBuilder = class {
63
+ constructor(config) {
64
+ this.config = config;
65
+ this.warp = {};
66
+ this.actions = [];
67
+ }
68
+ async createFromRaw(encoded) {
69
+ try {
70
+ const parsed = JSON.parse(encoded);
71
+ this.warp = parsed;
72
+ this.actions = parsed.actions || [];
73
+ return this.build();
74
+ } catch (error) {
75
+ throw new Error(`Failed to parse Fastset warp data: ${error}`);
76
+ }
77
+ }
78
+ setTitle(title) {
79
+ this.warp.title = title;
80
+ return this;
81
+ }
82
+ setDescription(description) {
83
+ this.warp.description = description;
84
+ return this;
85
+ }
86
+ setPreview(preview) {
87
+ this.warp.preview = preview;
88
+ return this;
89
+ }
90
+ setActions(actions) {
91
+ this.actions = actions;
92
+ return this;
93
+ }
94
+ addAction(action) {
95
+ this.actions.push(action);
96
+ return this;
97
+ }
98
+ async build() {
99
+ return {
100
+ protocol: "warp",
101
+ name: this.warp.name || "fastset-warp",
102
+ title: this.warp.title || "",
103
+ description: this.warp.description || null,
104
+ preview: this.warp.preview || null,
105
+ actions: this.actions,
106
+ meta: {
107
+ chain: "fastset",
108
+ hash: this.generateHash(this.warp.title || ""),
109
+ creator: this.config.user?.wallets?.fastset || "",
110
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
111
+ }
112
+ };
113
+ }
114
+ createInscriptionTransaction(warp) {
115
+ return {
116
+ type: "fastset-inscription",
117
+ data: JSON.stringify(warp)
118
+ // TODO: Add Fastset-specific transaction fields
119
+ };
120
+ }
121
+ async createFromTransaction(tx, validate = true) {
122
+ try {
123
+ const warpData = tx.data || tx.payload || tx.content;
124
+ if (!warpData) {
125
+ throw new Error("No warp data found in transaction");
126
+ }
127
+ const parsed = typeof warpData === "string" ? JSON.parse(warpData) : warpData;
128
+ if (validate) {
129
+ this.validateWarp(parsed);
130
+ }
131
+ return parsed;
132
+ } catch (error) {
133
+ throw new Error(`Failed to create warp from Fastset transaction: ${error}`);
134
+ }
135
+ }
136
+ async createFromTransactionHash(hash, cache) {
137
+ try {
138
+ const tx = await this.fetchTransaction(hash);
139
+ if (!tx) {
140
+ return null;
141
+ }
142
+ return this.createFromTransaction(tx);
143
+ } catch (error) {
144
+ console.error(`Failed to create warp from Fastset transaction hash: ${error}`);
145
+ return null;
146
+ }
147
+ }
148
+ generateHash(data) {
149
+ let hash = 0;
150
+ for (let i = 0; i < data.length; i++) {
151
+ const char = data.charCodeAt(i);
152
+ hash = (hash << 5) - hash + char;
153
+ hash = hash & hash;
154
+ }
155
+ return hash.toString(16);
156
+ }
157
+ validateWarp(warp) {
158
+ if (!warp.title) {
159
+ throw new Error("Warp must have a title");
160
+ }
161
+ if (!warp.actions || !Array.isArray(warp.actions)) {
162
+ throw new Error("Warp must have actions array");
163
+ }
164
+ }
165
+ async fetchTransaction(hash) {
166
+ const response = await fetch(`${this.getApiUrl()}/transaction/${hash}`);
167
+ if (!response.ok) {
168
+ return null;
169
+ }
170
+ return response.json();
171
+ }
172
+ getApiUrl() {
173
+ return "https://api.fastset.xyz";
174
+ }
175
+ };
176
+
177
+ // src/WarpFastsetExecutor.ts
178
+ import {
179
+ getWarpActionByIndex
180
+ } from "@vleap/warps";
181
+
182
+ // src/config.ts
183
+ var FASTSET_CHAIN_CONFIGS = {
184
+ fastset: {
185
+ mainnet: {
186
+ apiUrl: "https://mainnet.fastset.com/api",
187
+ explorerUrl: "https://explorer.fastset.com",
188
+ chainId: "1",
189
+ registryAddress: "0x0000000000000000000000000000000000000000",
190
+ nativeToken: "PI",
191
+ blockTime: 12
192
+ },
193
+ testnet: {
194
+ apiUrl: "https://testnet.fastset.com/api",
195
+ explorerUrl: "https://testnet-explorer.fastset.com",
196
+ chainId: "11155111",
197
+ registryAddress: "0x0000000000000000000000000000000000000000",
198
+ nativeToken: "PI",
199
+ blockTime: 12
200
+ },
201
+ devnet: {
202
+ apiUrl: "http://localhost:8545",
203
+ explorerUrl: "http://localhost:4000",
204
+ chainId: "1337",
205
+ registryAddress: "0x0000000000000000000000000000000000000000",
206
+ nativeToken: "PI",
207
+ blockTime: 12
208
+ }
209
+ }
210
+ };
211
+ var DEFAULT_CHAIN = "fastset";
212
+ var getFastsetChainConfig = (chain = DEFAULT_CHAIN, env) => {
213
+ const chainConfigs = FASTSET_CHAIN_CONFIGS[chain];
214
+ if (!chainConfigs) {
215
+ throw new Error(`Unsupported Fastset chain: ${chain}`);
216
+ }
217
+ const config = chainConfigs[env];
218
+ if (!config) {
219
+ throw new Error(`Unsupported environment ${env} for chain ${chain}`);
220
+ }
221
+ return config;
222
+ };
223
+ var getFastsetApiUrl = (env, chain = DEFAULT_CHAIN) => {
224
+ return getFastsetChainConfig(chain, env).apiUrl;
225
+ };
226
+
227
+ // src/WarpFastsetSerializer.ts
228
+ import {
229
+ WarpSerializer
230
+ } from "@vleap/warps";
231
+ var WarpFastsetSerializer = class {
232
+ constructor() {
233
+ this.coreSerializer = new WarpSerializer();
234
+ }
235
+ typedToString(value) {
236
+ if (typeof value === "string") {
237
+ return `string:${value}`;
238
+ }
239
+ if (typeof value === "number") {
240
+ return `number:${value}`;
241
+ }
242
+ if (typeof value === "boolean") {
243
+ return `boolean:${value}`;
244
+ }
245
+ if (typeof value === "bigint") {
246
+ return `bigint:${value.toString()}`;
247
+ }
248
+ if (Array.isArray(value)) {
249
+ const items = value.map((item) => this.typedToString(item)).join(",");
250
+ return `array:${items}`;
251
+ }
252
+ if (value === null) {
253
+ return "null:null";
254
+ }
255
+ if (value === void 0) {
256
+ return "undefined:undefined";
257
+ }
258
+ return `string:${String(value)}`;
259
+ }
260
+ typedToNative(value) {
261
+ if (typeof value === "string") {
262
+ return ["string", value];
263
+ }
264
+ if (typeof value === "number") {
265
+ return ["number", value];
266
+ }
267
+ if (typeof value === "boolean") {
268
+ return ["boolean", value];
269
+ }
270
+ if (typeof value === "bigint") {
271
+ return ["bigint", value];
272
+ }
273
+ return ["string", String(value)];
274
+ }
275
+ nativeToTyped(type, value) {
276
+ switch (type) {
277
+ case "string":
278
+ return String(value);
279
+ case "number":
280
+ return Number(value);
281
+ case "boolean":
282
+ return Boolean(value);
283
+ case "bigint":
284
+ return BigInt(value);
285
+ default:
286
+ return String(value);
287
+ }
288
+ }
289
+ nativeToType(type) {
290
+ switch (type) {
291
+ case "string":
292
+ return "string";
293
+ case "number":
294
+ return "number";
295
+ case "boolean":
296
+ return "boolean";
297
+ case "bigint":
298
+ return "bigint";
299
+ default:
300
+ return "string";
301
+ }
302
+ }
303
+ stringToTyped(value) {
304
+ const colonIndex = value.indexOf(":");
305
+ if (colonIndex === -1) {
306
+ return value;
307
+ }
308
+ const type = value.substring(0, colonIndex);
309
+ const stringValue = value.substring(colonIndex + 1);
310
+ switch (type) {
311
+ case "string":
312
+ return stringValue;
313
+ case "number":
314
+ return Number(stringValue);
315
+ case "boolean":
316
+ return stringValue === "true";
317
+ case "bigint":
318
+ return BigInt(stringValue);
319
+ case "array":
320
+ return stringValue.split(",").map((item) => this.stringToTyped(item));
321
+ case "null":
322
+ return null;
323
+ case "undefined":
324
+ return void 0;
325
+ default:
326
+ return stringValue;
327
+ }
328
+ }
329
+ };
330
+
331
+ // src/WarpFastsetExecutor.ts
332
+ var WarpFastsetExecutor = class {
333
+ constructor(config) {
334
+ this.config = config;
335
+ this.serializer = new WarpFastsetSerializer();
336
+ }
337
+ async createTransaction(executable) {
338
+ const action = getWarpActionByIndex(executable.warp, executable.action);
339
+ let tx = null;
340
+ if (action.type === "transfer") {
341
+ tx = await this.createTransferTransaction(executable);
342
+ } else if (action.type === "contract") {
343
+ tx = await this.createContractCallTransaction(executable);
344
+ } else if (action.type === "query") {
345
+ throw new Error("WarpFastsetExecutor: Invalid action type for createTransaction; Use executeQuery instead");
346
+ } else if (action.type === "collect") {
347
+ throw new Error("WarpFastsetExecutor: Invalid action type for createTransaction; Use executeCollect instead");
348
+ }
349
+ if (!tx) throw new Error(`WarpFastsetExecutor: Invalid action type (${action.type})`);
350
+ return tx;
351
+ }
352
+ async createTransferTransaction(executable) {
353
+ const userWallet = this.config.user?.wallets?.[executable.chain.name];
354
+ if (!userWallet) throw new Error("WarpFastsetExecutor: createTransfer - user address not set");
355
+ if (!this.isValidFastsetAddress(executable.destination)) {
356
+ throw new Error(`WarpFastsetExecutor: Invalid destination address: ${executable.destination}`);
357
+ }
358
+ if (executable.value < 0) {
359
+ throw new Error(`WarpFastsetExecutor: Transfer value cannot be negative: ${executable.value}`);
360
+ }
361
+ return {
362
+ type: "fastset-transfer",
363
+ from: userWallet,
364
+ to: executable.destination,
365
+ value: executable.value,
366
+ data: executable.data ? this.serializer.stringToTyped(executable.data) : ""
367
+ // TODO: Add Fastset-specific transaction fields
368
+ };
369
+ }
370
+ async createContractCallTransaction(executable) {
371
+ const userWallet = this.config.user?.wallets?.[executable.chain.name];
372
+ if (!userWallet) throw new Error("WarpFastsetExecutor: createContractCall - user address not set");
373
+ const action = getWarpActionByIndex(executable.warp, executable.action);
374
+ if (!action || !("func" in action) || !action.func) {
375
+ throw new Error("WarpFastsetExecutor: Contract action must have a function name");
376
+ }
377
+ if (!this.isValidFastsetAddress(executable.destination)) {
378
+ throw new Error(`WarpFastsetExecutor: Invalid contract address: ${executable.destination}`);
379
+ }
380
+ if (executable.value < 0) {
381
+ throw new Error(`WarpFastsetExecutor: Contract call value cannot be negative: ${executable.value}`);
382
+ }
383
+ try {
384
+ const encodedData = this.encodeFunctionData(action.func, executable.args);
385
+ return {
386
+ type: "fastset-contract-call",
387
+ from: userWallet,
388
+ to: executable.destination,
389
+ value: executable.value,
390
+ data: encodedData,
391
+ function: action.func
392
+ // TODO: Add Fastset-specific transaction fields
393
+ };
394
+ } catch (error) {
395
+ throw new Error(`WarpFastsetExecutor: Failed to encode function data for ${action.func}: ${error}`);
396
+ }
397
+ }
398
+ async executeQuery(executable) {
399
+ const action = getWarpActionByIndex(executable.warp, executable.action);
400
+ if (action.type !== "query") {
401
+ throw new Error(`WarpFastsetExecutor: Invalid action type for executeQuery: ${action.type}`);
402
+ }
403
+ if (!action.func) {
404
+ throw new Error("WarpFastsetExecutor: Query action must have a function name");
405
+ }
406
+ if (!this.isValidFastsetAddress(executable.destination)) {
407
+ throw new Error(`WarpFastsetExecutor: Invalid contract address for query: ${executable.destination}`);
408
+ }
409
+ try {
410
+ const result = await this.executeFastsetQuery(executable.destination, action.func, executable.args);
411
+ return {
412
+ success: true,
413
+ result
414
+ // TODO: Add Fastset-specific result fields
415
+ };
416
+ } catch (error) {
417
+ return {
418
+ success: false,
419
+ error: error instanceof Error ? error.message : String(error)
420
+ // TODO: Add Fastset-specific error fields
421
+ };
422
+ }
423
+ }
424
+ async preprocessInput(chain, input, type, value) {
425
+ const typedValue = this.serializer.stringToTyped(value);
426
+ switch (type) {
427
+ case "address":
428
+ if (!this.isValidFastsetAddress(typedValue)) {
429
+ throw new Error(`Invalid Fastset address format: ${typedValue}`);
430
+ }
431
+ return typedValue;
432
+ case "number":
433
+ const numValue = Number(typedValue);
434
+ if (isNaN(numValue)) {
435
+ throw new Error(`Invalid number format: ${typedValue}`);
436
+ }
437
+ return numValue.toString();
438
+ case "bigint":
439
+ const bigIntValue = BigInt(typedValue);
440
+ if (bigIntValue < 0) {
441
+ throw new Error(`Negative value not allowed for type ${type}: ${typedValue}`);
442
+ }
443
+ return bigIntValue.toString();
444
+ default:
445
+ return String(typedValue);
446
+ }
447
+ }
448
+ isValidFastsetAddress(address) {
449
+ return typeof address === "string" && address.length > 0;
450
+ }
451
+ encodeFunctionData(functionName, args) {
452
+ return JSON.stringify({
453
+ function: functionName,
454
+ arguments: args
455
+ });
456
+ }
457
+ async executeFastsetQuery(contractAddress, functionName, args) {
458
+ const response = await fetch(`${getFastsetApiUrl(this.config.env, "fastset")}/query`, {
459
+ method: "POST",
460
+ headers: {
461
+ "Content-Type": "application/json"
462
+ },
463
+ body: JSON.stringify({
464
+ contract: contractAddress,
465
+ function: functionName,
466
+ arguments: args
467
+ })
468
+ });
469
+ if (!response.ok) {
470
+ throw new Error(`Fastset query failed: ${response.statusText}`);
471
+ }
472
+ return response.json();
473
+ }
474
+ async signMessage(message, privateKey) {
475
+ throw new Error("Not implemented");
476
+ }
477
+ };
478
+
479
+ // src/WarpFastsetExplorer.ts
480
+ var WarpFastsetExplorer = class {
481
+ constructor(chainInfo, chainName = "fastset") {
482
+ this.chainInfo = chainInfo;
483
+ this.chainName = chainName;
484
+ }
485
+ getAccountUrl(address) {
486
+ const baseUrl = this.chainInfo.explorerUrl || this.getDefaultExplorerUrl();
487
+ return `${baseUrl}/address/${address}`;
488
+ }
489
+ getTransactionUrl(hash) {
490
+ const baseUrl = this.chainInfo.explorerUrl || this.getDefaultExplorerUrl();
491
+ return `${baseUrl}/tx/${hash}`;
492
+ }
493
+ getBlockUrl(blockNumber) {
494
+ const baseUrl = this.chainInfo.explorerUrl || this.getDefaultExplorerUrl();
495
+ return `${baseUrl}/block/${blockNumber}`;
496
+ }
497
+ getContractUrl(address) {
498
+ const baseUrl = this.chainInfo.explorerUrl || this.getDefaultExplorerUrl();
499
+ return `${baseUrl}/contract/${address}`;
500
+ }
501
+ getTokenUrl(address) {
502
+ const baseUrl = this.chainInfo.explorerUrl || this.getDefaultExplorerUrl();
503
+ return `${baseUrl}/token/${address}`;
504
+ }
505
+ getDefaultExplorerUrl() {
506
+ return `https://explorer.fastset.xyz`;
507
+ }
508
+ };
509
+
510
+ // src/WarpFastsetResults.ts
511
+ import {
512
+ evaluateResultsCommon,
513
+ parseResultsOutIndex,
514
+ WarpConstants
515
+ } from "@vleap/warps";
516
+ var WarpFastsetResults = class {
517
+ constructor(config) {
518
+ this.config = config;
519
+ this.serializer = new WarpFastsetSerializer();
520
+ }
521
+ async getTransactionExecutionResults(warp, tx) {
522
+ const success = this.isTransactionSuccessful(tx);
523
+ const gasUsed = this.extractGasUsed(tx);
524
+ const gasPrice = this.extractGasPrice(tx);
525
+ const blockNumber = this.extractBlockNumber(tx);
526
+ const transactionHash = this.extractTransactionHash(tx);
527
+ const logs = this.extractLogs(tx);
528
+ return {
529
+ success,
530
+ warp,
531
+ action: 0,
532
+ user: this.config.user?.wallets?.fastset || null,
533
+ txHash: transactionHash,
534
+ next: null,
535
+ values: [transactionHash, blockNumber, gasUsed, gasPrice, ...logs.length > 0 ? logs : []],
536
+ results: {},
537
+ messages: {}
538
+ };
539
+ }
540
+ async extractQueryResults(warp, typedValues, actionIndex, inputs) {
541
+ const values = typedValues.map((t) => this.serializer.typedToString(t));
542
+ const valuesRaw = typedValues.map((t) => this.serializer.typedToNative(t)[1]);
543
+ let results = {};
544
+ if (!warp.results) return { values, results };
545
+ const getNestedValue = (path) => {
546
+ const indices = path.split(".").slice(1).map((i) => parseInt(i) - 1);
547
+ if (indices.length === 0) return void 0;
548
+ let value = valuesRaw[indices[0]];
549
+ for (let i = 1; i < indices.length; i++) {
550
+ if (value === void 0 || value === null) return void 0;
551
+ value = value[indices[i]];
552
+ }
553
+ return value;
554
+ };
555
+ for (const [key, path] of Object.entries(warp.results)) {
556
+ if (path.startsWith(WarpConstants.Transform.Prefix)) continue;
557
+ const currentActionIndex = parseResultsOutIndex(path);
558
+ if (currentActionIndex !== null && currentActionIndex !== actionIndex) {
559
+ results[key] = null;
560
+ continue;
561
+ }
562
+ if (path.startsWith("out.") || path === "out" || path.startsWith("out[")) {
563
+ results[key] = getNestedValue(path) || null;
564
+ } else {
565
+ results[key] = path;
566
+ }
567
+ }
568
+ return { values, results: await evaluateResultsCommon(warp, results, actionIndex, inputs) };
569
+ }
570
+ isTransactionSuccessful(tx) {
571
+ return tx.status === "success" || tx.status === 1 || tx.success === true;
572
+ }
573
+ extractGasUsed(tx) {
574
+ return tx.gasUsed?.toString() || tx.gas_used?.toString() || "0";
575
+ }
576
+ extractGasPrice(tx) {
577
+ return tx.gasPrice?.toString() || tx.gas_price?.toString() || "0";
578
+ }
579
+ extractBlockNumber(tx) {
580
+ return tx.blockNumber?.toString() || tx.block_number?.toString() || "0";
581
+ }
582
+ extractTransactionHash(tx) {
583
+ return tx.hash || tx.transactionHash || tx.transaction_hash || "";
584
+ }
585
+ extractLogs(tx) {
586
+ const logs = tx.logs || tx.events || [];
587
+ return logs.map((log) => ({
588
+ address: log.address || log.contract,
589
+ topics: log.topics || log.topics || [],
590
+ data: log.data || log.payload || "",
591
+ blockNumber: log.blockNumber?.toString() || log.block_number?.toString() || "0",
592
+ transactionHash: log.transactionHash || log.transaction_hash || "",
593
+ index: log.index?.toString() || "0"
594
+ }));
595
+ }
596
+ };
597
+
598
+ // src/main.ts
599
+ var getFastsetAdapter = (config, fallback) => {
600
+ if (!fallback) throw new Error("Fastset adapter requires a fallback adapter");
601
+ return {
602
+ chain: WarpFastsetConstants.ChainName,
603
+ prefix: WarpFastsetConstants.ChainPrefix,
604
+ builder: () => new WarpFastsetBuilder(config),
605
+ executor: new WarpFastsetExecutor(config),
606
+ results: new WarpFastsetResults(config),
607
+ serializer: new WarpFastsetSerializer(),
608
+ registry: fallback.registry,
609
+ explorer: (chainInfo) => new WarpFastsetExplorer(chainInfo),
610
+ abiBuilder: () => fallback.abiBuilder(),
611
+ brandBuilder: () => fallback.brandBuilder()
612
+ };
613
+ };
614
+ export {
615
+ WarpFastsetBuilder,
616
+ WarpFastsetConstants,
617
+ WarpFastsetExecutor,
618
+ WarpFastsetExplorer,
619
+ WarpFastsetResults,
620
+ WarpFastsetSerializer,
621
+ getFastsetAdapter
622
+ };
623
+ //# sourceMappingURL=index.mjs.map