-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathcommon-schemas.ts
More file actions
1087 lines (980 loc) · 31.6 KB
/
common-schemas.ts
File metadata and controls
1087 lines (980 loc) · 31.6 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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Common Zod Schema Definitions
*
* This file contains reusable Zod schemas for common Hedera data types
* that are used across multiple plugin command outputs.
*
* Based on ADR-003: Result-Oriented Command Handler Contract
*/
import type { Credential } from '@/core/services/kms/kms-types.interface';
import { z } from 'zod';
import { ValidationError } from '@/core/errors';
import {
CredentialType,
KeyManager,
} from '@/core/services/kms/kms-types.interface';
import {
HEDERA_AUTO_RENEW_PERIOD_MAX,
HEDERA_AUTO_RENEW_PERIOD_MIN,
HEDERA_EXPIRATION_TIME_MAX,
HEDERA_SCHEDULE_EXPIRATION_MAX,
HederaTokenType,
KeyAlgorithm,
} from '@/core/shared/constants';
import {
EntityReferenceType,
SupplyType,
SupportedNetwork,
} from '@/core/types/shared.types';
import { parseAutoRenewPeriodToSeconds } from '@/core/utils/parse-auto-renew-period';
// Raw key patterns (without prefix) for validation
const PUBLIC_KEY_PATTERN =
/^(?:0[2-3][0-9a-fA-F]{64}|[0-9a-fA-F]{64}|30[0-9a-fA-F]{60,150})$/;
const PRIVATE_KEY_PATTERN =
/^(?:(?:0x)?[0-9a-fA-F]{64}|(?:0x)?[0-9a-fA-F]{128}|(?:0x)?30[0-9a-fA-F]{80,180})$/;
// ======================================================
// 1. ECDSA (secp256k1) Keys
// ======================================================
// Public key — ecdsa:public:<key>, raw 33 bytes (compressed) or DER (~70 bytes)
export const EcdsaPublicKeySchema = z
.string()
.trim()
.transform((s) => (s.startsWith('ecdsa:public') ? s.slice(13) : s))
.refine(
(s) => PUBLIC_KEY_PATTERN.test(s),
'Invalid ECDSA public key: use ecdsa:public:<key> or 33-byte compressed hex / DER encoding',
);
// Private key — ecdsa:private:<key>, raw 32 bytes (hex) or DER (~120 bytes)
export const EcdsaPrivateKeySchema = z
.string()
.trim()
.transform((s) => (s.startsWith('ecdsa:private') ? s.slice(14) : s))
.refine(
(s) => PRIVATE_KEY_PATTERN.test(s),
'Invalid ECDSA private key: use ecdsa:private:<key> or 32-byte hex / DER encoding',
);
// ======================================================
// 2. Ed25519 Keys
// ======================================================
// Public key — ed25519:public:<key> or raw 32 bytes (hex) or DER (~44 bytes)
export const Ed25519PublicKeySchema = z
.string()
.trim()
.transform((s) => (s.startsWith('ed25519:public') ? s.slice(15) : s))
.refine(
(s) => PUBLIC_KEY_PATTERN.test(s),
'Invalid Ed25519 public key: use ed25519:public:<key> or 32-byte hex / DER encoding',
);
// Private key — ed25519:private:<key> or raw 32/64 bytes (hex) or DER (~80 bytes)
export const Ed25519PrivateKeySchema = z
.string()
.trim()
.transform((s) => (s.startsWith('ed25519:private') ? s.slice(16) : s))
.refine(
(s) => PRIVATE_KEY_PATTERN.test(s),
'Invalid Ed25519 private key: use ed25519:private:<key> or 32/64-byte hex / DER encoding',
);
// ======================================================
// 3. HBAR balances (in HBARs, decimal format)
// ======================================================
// 1 HBAR = 100,000,000 tinybars (8 decimals)
// Safe 64-bit signed tinybar limit = 9,223,372,036,854,775,807 tinybars
const MAX_TINYBARS = 9_223_372_036_854_775_807n;
const MIN_TINYBARS = -9_223_372_036_854_775_808n;
// ======================================================
// 4. Tinybar balances (base unit integer)
// ======================================================
export const TinybarSchema = z
.union([
z.string().regex(/^-?\d+$/, 'Tinybars must be integer string'),
z.int(),
z.bigint(),
])
.transform((val) => BigInt(val))
.refine(
(val) => val >= MIN_TINYBARS && val <= MAX_TINYBARS,
`Tinybars out of int64 range (${MIN_TINYBARS}..${MAX_TINYBARS})`,
);
// ======================================================
// 5. HTS Token Balances
// ======================================================
// HTS decimals(immutable after token creation)
export const HtsDecimalsSchema = z.int().min(0);
// HTS base unit (integer form)
export const HtsBaseUnitSchema = z
.union([
z.string().regex(/^\d+$/, 'Base unit must be integer string'),
z.int(),
z.bigint(),
])
.transform((val) => BigInt(val))
.refine(
(val) => val >= 0n && val <= MAX_TINYBARS,
`HTS base unit out of int64 range`,
);
// ======================================================
// 6. EVM Token Balances (ERC-20 style)
// ======================================================
export const EvmDecimalsSchema = z
.union([z.int(), z.bigint()])
.transform((val) => Number(val))
.pipe(z.number().int());
// Base unit (wei-like integer)
export const EvmBaseUnitSchema = z
.union([
z.string().regex(/^\d+$/, 'Base unit must be integer string'),
z.int(),
z.bigint(),
])
.transform((val) => BigInt(val))
.refine((val) => val >= 0n, 'EVM base unit cannot be negative');
// ======================================================
// 7. Legacy Schemas (for backward compatibility)
// ======================================================
/**
* Hedera Entity ID pattern
* Format: 0.0.12345
* Example: 0.0.123456
*/
export const EntityIdSchema = z
.string()
.regex(
/^0\.0\.[1-9][0-9]*$/,
'Hedera entity ID must be in format 0.0.{number}',
)
.describe('Hedera entity ID in format 0.0.{number}');
/**
* Hedera Timestamp pattern
* Format: {seconds}.{nanoseconds}
* Example: 1700000000.123456789
*/
export const TimestampSchema = z
.string()
.regex(
/^[0-9]+\.[0-9]{9}$/,
'Hedera timestamp must be in format {seconds}.{nanoseconds}',
)
.describe('Hedera timestamp in format {seconds}.{nanoseconds}');
/**
* Hedera Transaction ID pattern
* Format: {accountId}@{timestamp}
* Example: [email protected]
*/
export const TransactionIdSchema = z
.string()
.regex(
/^0\.0\.[1-9][0-9]*@[0-9]+\.[0-9]{9}$/,
'Hedera transaction ID must be in format {accountId}@{timestamp}',
)
.describe('Hedera transaction ID in format {accountId}@{timestamp}');
/**
* EVM Address (Ethereum-compatible address)
* Format: 0x followed by 40 hexadecimal characters
*/
export const EvmAddressSchema = z
.string()
.regex(
/^0x[0-9a-fA-F]{40}$/,
'EVM address must be 0x followed by 40 hexadecimal characters',
)
.describe('EVM-compatible address');
/**
* Account ID with Private Key (without keyType support)
* Format: accountId:privateKey
* Supports both ECDSA and ED25519 keys in HEX or DER format
* Example: 0.0.123456:302e020100301006072a8648ce3d020106052b8104000a04220420...
* Example: 0.0.123456:1234567890abcdef...
*/
export const AccountIdWithPrivateKeySchema = z
.string()
.regex(
/^0\.0\.[1-9][0-9]*:(?:(?:0x)?[0-9a-fA-F]{64}|(?:0x)?[0-9a-fA-F]{128}|30[0-9a-fA-F]{80,})$/i,
'Account ID with private key must be in format {accountId}:{private_key}',
)
.transform((val) => {
const [accountId, ...keyParts] = val.split(':');
return {
accountId,
privateKey: keyParts.join(':'),
};
})
.describe('Account ID with private key in format {accountId}:{private_key}');
/**
* Network name
* Supported Hedera network names
*/
export const NetworkSchema = z
.enum(SupportedNetwork)
.describe('Hedera network identifier');
/**
* Key Type
* Supported key types in Hedera
*/
export const KeyTypeSchema = z
.enum([KeyAlgorithm.ECDSA, KeyAlgorithm.ED25519])
.describe('Cryptographic key type');
/**
* Token Supply Type
*/
export const SupplyTypeSchema = z
.enum(SupplyType)
.describe('Token supply type');
/**
* ISO 8601 Timestamp
* Standard date-time format
*/
export const IsoTimestampSchema = z.iso
.datetime()
.describe('ISO 8601 timestamp');
// ======================================================
// 8. Composite Schemas
// ======================================================
/**
* Token Data (Full)
* Complete token information
*/
export const TokenDataSchema = z
.object({
tokenId: EntityIdSchema,
name: z.string().describe('Token name'),
symbol: z.string().describe('Token symbol'),
decimals: HtsDecimalsSchema,
initialSupply: z.string().describe('Initial supply in base units'),
supplyType: SupplyTypeSchema,
treasuryId: EntityIdSchema,
network: NetworkSchema,
})
.describe('Complete token information');
// ======================================================
// 9. Input Schemas (Command Arguments - Reusable)
// ======================================================
/**
* Positive Integer Filter Field
* Used for numeric comparison operators (gt, gte, lt, lte, eq)
* Accepts integers > 0 (Mirror Node API requirement)
*/
export const PositiveIntFilterFieldSchema = z
.number()
.int()
.positive('Filter value must be greater than 0')
.optional()
.describe('Positive integer filter value');
/**
* Alias Name Input (Base Schema)
* Base schema for all entity aliases (alphanumeric, hyphens, underscores)
* Used as foundation for AccountNameSchema, TopicNameSchema, TokenAliasNameSchema
*/
export const AliasNameSchema = z
.string()
.trim()
.min(1, 'Alias name cannot be empty')
.regex(
/^[a-zA-Z0-9_-]+$/,
'Alias name must contain only letters, numbers, hyphens, and underscores',
)
.describe('Entity alias name');
/**
* Account Name Input
* Account name/alias (alphanumeric, hyphens, underscores)
*/
export const AccountNameSchema = AliasNameSchema.describe(
'Account name or alias',
);
/**
* Entity Reference Input (ID or Name)
* Universal schema for referencing any Hedera entity by ID or name
* Used for tokens, topics, contracts, etc.
* Accepts: Hedera entity ID (0.0.xxx) or alias name
*/
export const EntityReferenceSchema = z
.union([EntityIdSchema, AliasNameSchema], {
error: () => ({
message:
'Entity reference must be a valid Hedera ID (0.0.xxx) or alias name',
}),
})
.describe('Entity reference (ID or name)');
/**
* Entity or EVM Address Reference Input
* Universal schema for referencing any Hedera entity by ID, EVM address, or alias name
*/
export const EntityOrEvmAddressReferenceSchema = z
.union([EntityIdSchema, AliasNameSchema, EvmAddressSchema], {
error: () => ({
message:
'Entity reference must be a valid Hedera ID (0.0.xxx), alias name, or EVM address (0x...)',
}),
})
.describe('Entity reference (ID, EVM address, or name)');
/**
* Parsed contract reference as a discriminated object by type (EVM address, entity ID, or alias).
* Use this when the handler needs to branch on which kind of reference was provided.
*/
export const ContractReferenceObjectSchema = z
.string()
.trim()
.min(1, 'Contract identifier cannot be empty')
.transform((val): { type: EntityReferenceType; value: string } => {
if (EvmAddressSchema.safeParse(val).success) {
return { type: EntityReferenceType.EVM_ADDRESS, value: val };
}
if (EntityIdSchema.safeParse(val).success) {
return { type: EntityReferenceType.ENTITY_ID, value: val };
}
if (AliasNameSchema.safeParse(val).success) {
return { type: EntityReferenceType.ALIAS, value: val };
}
throw new ValidationError(
'Contract reference must be a valid Hedera ID (0.0.xxx), alias name, or EVM address (0x...)',
);
})
.describe('Contract identifier (ID, EVM address, or alias)');
/**
* Parsed account reference as a discriminated object by type (EVM address, entity ID, or alias).
* Use this when the handler needs to branch on which kind of reference was provided.
*/
export const AccountReferenceObjectSchema = z
.string()
.trim()
.min(1, 'Account identifier cannot be empty')
.transform((val): { type: EntityReferenceType; value: string } => {
if (EvmAddressSchema.safeParse(val).success) {
return { type: EntityReferenceType.EVM_ADDRESS, value: val };
}
if (EntityIdSchema.safeParse(val).success) {
return { type: EntityReferenceType.ENTITY_ID, value: val };
}
if (AliasNameSchema.safeParse(val).success) {
return { type: EntityReferenceType.ALIAS, value: val };
}
throw new ValidationError(
'Account reference must be a valid Hedera ID (0.0.xxx), alias name, or EVM address (0x...)',
);
})
.describe('Account identifier (ID, EVM address, or alias)');
/**
* Parsed token reference as a discriminated object by type (entity ID or alias).
*/
export const TokenReferenceObjectSchema = z
.string()
.trim()
.min(1, 'Token identifier cannot be empty')
.transform((val): { type: EntityReferenceType; value: string } => {
if (EntityIdSchema.safeParse(val).success) {
return { type: EntityReferenceType.ENTITY_ID, value: val };
}
if (AliasNameSchema.safeParse(val).success) {
return { type: EntityReferenceType.ALIAS, value: val };
}
throw new ValidationError(
'Token reference must be a valid Hedera ID (0.0.xxx) or alias name',
);
})
.describe('Token identifier (ID or alias)');
/**
* Parsed token reference as a discriminated object by type (entity ID or alias).
*/
export const ScheduleReferenceObjectSchema = z
.string()
.trim()
.min(1, 'Schedule identifier cannot be empty')
.transform((val): { type: EntityReferenceType; value: string } => {
if (EntityIdSchema.safeParse(val).success) {
return { type: EntityReferenceType.ENTITY_ID, value: val };
}
if (AliasNameSchema.safeParse(val).success) {
return { type: EntityReferenceType.ALIAS, value: val };
}
throw new ValidationError(
'Schedule reference must be a valid Hedera ID (0.0.xxx) or alias name',
);
})
.describe('Schedule identifier (ID or alias)');
/**
* Account Reference Input (ID or Name)
* Extended schema for referencing accounts specifically
* Supports: Hedera account ID (0.0.xxx), EVM address (0x...), or account name/alias
*/
export const AccountReferenceSchema = z
.union([EntityIdSchema, AccountNameSchema], {
error: () => ({
message:
'Account reference must be a valid Hedera ID (0.0.xxx) or alias name',
}),
})
.describe('Account reference (ID, EVM address, or name)');
/**
* Contract Reference Input (ID or Alias)
* Supports: Hedera contract ID (0.0.xxx) or alias name
*/
export const ContractReferenceSchema = z
.union([EntityIdSchema, AliasNameSchema], {
error: () => ({
message:
'Contract reference must be a valid Hedera ID (0.0.xxx) or alias name',
}),
})
.describe('Contract reference (ID or alias)');
/**
* Amount Input
* Accepts amount as string in format:
* - "100" (integer amount)
* - "100.5" (float amount)
* - "100t" (integer in base units / tinybars)
* NOTE: Float with "t" suffix (e.g., "100.5t") is NOT allowed
* Handler is responsible for parsing and converting to appropriate unit
* Used for amounts, supply, balance, and other numeric inputs
*/
export const AmountInputSchema = z.coerce
.string()
.trim()
.regex(
/^(?:\d+\.\d+|\d+t|\d+)$/,
'Must be: integer, float, or integer with "t" for base units (float with "t" is not allowed)',
)
.describe(
'Numeric value (integer, float, or integer with "t" suffix for base units)',
);
/**
* Key Manager Type
* Supported key manager implementations for private key storage
*/
export const KeyManagerTypeSchema = z
.enum(KeyManager)
.describe('Key manager type for storing private keys');
/**
* Topic Name Input
* Topic name/alias (alphanumeric, hyphens, underscores)
*/
export const TopicNameSchema = AliasNameSchema.describe('Topic name or alias');
/**
* Token Alias Name Input
* Local alias for a token (alphanumeric, hyphens, underscores)
* NOTE: This is different from TokenNameSchema which is the on-chain token name
*/
export const TokenAliasNameSchema = AliasNameSchema.describe(
'Token alias name (local identifier, not on-chain name)',
);
export const TokenFreezeDefaultSchema = z.boolean().default(false);
/**
* Memo Input
* Optional memo field for transactions
* Max 100 characters as per Hedera specifications
*/
export const MemoSchema = z
.string()
.trim()
.max(100, 'Memo must be 100 characters or less')
.optional()
.describe('Optional memo for the transaction');
/**
* Token Type schema
* Optional Token Type field for transactions
* Enum of HederaTokenType
*/
export const TokenTypeSchema = z
.enum(HederaTokenType)
.optional()
.default(HederaTokenType.FUNGIBLE_COMMON);
/**
* Key or Account Alias Input (Normalized)
* Accepts AccountID:privateKey pair format or account name/alias
* Transforms input into normalized discriminated union for easier handler processing:
* - alias input → { type: 'alias', alias: string }
* - keypair input → { type: 'keypair', accountId: string, privateKey: string }
* The keyType must be fetched from mirror node when keypair is provided
*/
export const KeyOrAccountAliasSchema = z
.union([AccountIdWithPrivateKeySchema, AccountNameSchema])
.transform((val) =>
typeof val === 'string'
? { type: 'alias' as const, alias: val }
: { type: 'keypair' as const, ...val },
)
.describe(
'Account ID with private key in format {accountId}:{private_key} or account name/alias',
);
export const KeyReferenceSchema = z
.string()
.trim()
.regex(
/^kr_[A-Za-z0-9]+$/,
'Key reference must start with "kr_" and contain only alphanumeric characters after the prefix',
)
.describe(
'Key reference identifier (kr_ prefix + alphanumeric) managed by the key manager',
);
export const KeySchema = z
.string()
.transform((val): Credential => {
const accountKeypair = AccountIdWithPrivateKeySchema.safeParse(val);
if (accountKeypair.success) {
return {
type: CredentialType.ACCOUNT_KEY_PAIR,
accountId: accountKeypair.data.accountId,
privateKey: accountKeypair.data.privateKey,
rawValue: val,
};
}
const privateKey = PrivateKeyDefinitionWithTypeSchema.safeParse(val);
if (privateKey.success) {
return {
type: CredentialType.PRIVATE_KEY,
privateKey: privateKey.data.privateKey,
keyType: privateKey.data.keyType,
rawValue: val,
};
}
const publicKey = PublicKeyDefinitionWithTypeSchema.safeParse(val);
if (publicKey.success) {
return {
type: CredentialType.PUBLIC_KEY,
publicKey: publicKey.data.publicKey,
keyType: publicKey.data.keyType,
rawValue: val,
};
}
const accountId = EntityIdSchema.safeParse(val);
if (accountId.success) {
return {
type: CredentialType.ACCOUNT_ID,
accountId: accountId.data,
rawValue: val,
};
}
const keyRef = KeyReferenceSchema.safeParse(val);
if (keyRef.success) {
return {
type: CredentialType.KEY_REFERENCE,
keyReference: keyRef.data,
rawValue: val,
};
}
const evmAddress = EvmAddressSchema.safeParse(val);
if (evmAddress.success) {
return {
type: CredentialType.EVM_ADDRESS,
evmAddress: evmAddress.data,
rawValue: val,
};
}
const alias = AliasNameSchema.safeParse(val);
if (alias.success) {
return {
type: CredentialType.ALIAS,
alias: alias.data,
rawValue: val,
};
}
throw new ValidationError(
'Key must be a valid account ID and private key pair in format {account-id:private-key}, account ID, private key in format {ed25519|ecdsa}:{private-key}, public key in format {ed25519|ecdsa}:{public-key}, key reference, EVM address (0x...) or alias name',
);
})
.describe(
'Account ID with private key in {accountId}:{private_key} format, account public key in {ed25519|ecdsa}:{public-key} format, account private key in {ed25519|ecdsa}:{private-key} format, account ID, account name/alias or account key reference',
);
export const PrivateKeySchema = z
.string()
.transform((val): Credential => {
const accountKeypair = AccountIdWithPrivateKeySchema.safeParse(val);
if (accountKeypair.success) {
return {
type: CredentialType.ACCOUNT_KEY_PAIR,
accountId: accountKeypair.data.accountId,
privateKey: accountKeypair.data.privateKey,
rawValue: val,
};
}
const privateKey = PrivateKeyDefinitionWithTypeSchema.safeParse(val);
if (privateKey.success) {
return {
type: CredentialType.PRIVATE_KEY,
privateKey: privateKey.data.privateKey,
keyType: privateKey.data.keyType,
rawValue: val,
};
}
const keyRef = KeyReferenceSchema.safeParse(val);
if (keyRef.success) {
return {
type: CredentialType.KEY_REFERENCE,
keyReference: keyRef.data,
rawValue: val,
};
}
const alias = AliasNameSchema.safeParse(val);
if (alias.success) {
return {
type: CredentialType.ALIAS,
alias: alias.data,
rawValue: val,
};
}
throw new ValidationError(
'Private key must be a valid account ID and private key pair in {account-id:private-key} format, private key in format {ed25519|ecdsa}:{private-key}, key reference or alias name',
);
})
.describe(
'Account ID and private key pair in {account-id:private-key} format, account private key in format {ed25519|ecdsa}:{private-key}, account key reference or alias name',
);
export const PrivateKeyWithAccountIdSchema = z
.string()
.transform((val): Credential => {
const accountKeypair = AccountIdWithPrivateKeySchema.safeParse(val);
if (accountKeypair.success) {
return {
type: CredentialType.ACCOUNT_KEY_PAIR,
accountId: accountKeypair.data.accountId,
privateKey: accountKeypair.data.privateKey,
rawValue: val,
};
}
const keyRef = KeyReferenceSchema.safeParse(val);
if (keyRef.success) {
return {
type: CredentialType.KEY_REFERENCE,
keyReference: keyRef.data,
rawValue: val,
};
}
const alias = AliasNameSchema.safeParse(val);
if (alias.success) {
return {
type: CredentialType.ALIAS,
alias: alias.data,
rawValue: val,
};
}
throw new ValidationError(
'Private key with account ID must be a valid account ID and private key pair in {account-id:private-key} format, key reference or alias name',
);
})
.describe(
'Account ID and private key pair in {account-id:private-key} format, account key reference or alias name',
);
/**
* Configuration Option Name
* Name of a configuration option (alphanumeric, hyphens, underscores)
*/
export const ConfigOptionNameSchema = z
.string()
.trim()
.min(1, 'Configuration option name cannot be empty')
.regex(
/^[a-zA-Z0-9_-]+$/,
'Configuration option name must contain only letters, numbers, hyphens, and underscores',
)
.describe('Configuration option name');
/**
* Configuration Option Value
* Value for configuration option (can be string, number, or boolean as string)
* Handler will parse it to appropriate type
*/
export const ConfigOptionValueSchema = z
.preprocess(
(value) => {
if (typeof value !== 'string') return value;
const s = value.trim().toLowerCase();
if (s === 'true') return true;
if (s === 'false') return false;
const n = Number(value);
if (!Number.isNaN(n) && Number.isFinite(n)) return n;
return value;
},
z.union([z.boolean(), z.number(), z.string()]),
)
.describe('Configuration option value (boolean, number, or string)');
/**
* Key Reference ID
* Identifier for a key stored in KMS (Key Management System)
*/
export const KeyRefIdSchema = z
.string()
.trim()
.min(1, 'Key reference ID cannot be empty')
.describe('Key reference ID from KMS storage');
/**
* Plugin Name
* Name of a plugin (alphanumeric, hyphens, underscores)
*/
export const PluginNameSchema = z
.string()
.trim()
.min(1, 'Plugin name cannot be empty')
.regex(
/^[a-zA-Z0-9_-]+$/,
'Plugin name must contain only letters, numbers, hyphens, and underscores',
)
.describe('Plugin name');
/**
* File Path
* Filesystem path (absolute or relative)
*/
export const FilePathSchema = z
.string()
.trim()
.min(1, 'File path cannot be empty')
.describe('Filesystem path (absolute or relative)');
/**
* Token Name
* Name of a token (alphanumeric, spaces, hyphens)
*/
export const TokenNameSchema = z
.string()
.trim()
.min(1, 'Token name cannot be empty')
.max(100, 'Token name must be 100 characters or less')
.describe('Token name');
/**
* Token Symbol
* Symbol/ticker for a token (alphanumeric, uppercase)
*/
export const TokenSymbolSchema = z
.string()
.trim()
.min(1, 'Token symbol cannot be empty')
.max(20, 'Token symbol must be 20 characters or less')
.describe('Token symbol');
/**
* NFT Serial Numbers Input
* Comma-separated list of NFT serial numbers
* Transformed to array of positive integers
*/
export const NftSerialNumbersSchema = z
.string()
.trim()
.transform((val) => val.split(',').map((s) => parseInt(s.trim(), 10)))
.pipe(
z
.array(z.int().positive('Serial numbers must be positive integers'))
.min(1, 'At least one serial number is required')
.max(10, 'Maximum 10 serial numbers allowed'),
)
.describe('NFT serial numbers (comma-separated list)');
// ======================================================
// 10. Legacy Compatibility Exports
// ======================================================
// For backward compatibility
export const TokenAmountSchema = HtsBaseUnitSchema;
export const TokenBalanceSchema = z
.object({
baseUnitAmount: HtsBaseUnitSchema,
name: z.string().describe('Token name or symbol'),
decimals: HtsDecimalsSchema,
})
.describe('Token balance with denomination information');
export const TinybarBalanceSchema = TinybarSchema;
// Generic public key schema for backward compatibility
export const PublicKeyDefinitionSchema = z.union([
EcdsaPublicKeySchema,
Ed25519PublicKeySchema,
]);
export const PublicKeyDefinitionWithTypeSchema = z.union([
EcdsaPublicKeySchema.transform((key) => ({
keyType: KeyAlgorithm.ECDSA,
publicKey: key,
})),
Ed25519PublicKeySchema.transform((key) => ({
keyType: KeyAlgorithm.ED25519,
publicKey: key,
})),
]);
// Generic private key schema (ECDSA or ED25519)
export const PrivateKeyDefinitionSchema = z.union([
EcdsaPrivateKeySchema,
Ed25519PrivateKeySchema,
]);
export const PrivateKeyDefinitionWithTypeSchema = z.union([
EcdsaPrivateKeySchema.transform((key) => ({
keyType: KeyAlgorithm.ECDSA,
privateKey: key,
})),
Ed25519PrivateKeySchema.transform((key) => ({
keyType: KeyAlgorithm.ED25519,
privateKey: key,
})),
]);
export const NonNegativeNumberOrBigintSchema = z
.union([z.number(), z.bigint()])
.transform((val) => BigInt(val))
.pipe(z.bigint().nonnegative());
/**
* Contract Name Input (Base Schema)
* Base schema for all contract names (alphanumeric, hyphens, underscores)
* Used as foundation for ContractNameSchema
*/
export const ContractNameSchema = z
.string()
.trim()
.min(1, 'Contract name cannot be empty')
.regex(
/^[a-zA-Z0-9_-]+$/,
'Contract name must contain only letters, numbers, hyphens, and underscores',
)
.describe('Contract name');
export const ContractVerifiedSchema = z
.boolean()
.optional()
.describe('Contract verification status');
/**
* Contract Symbol Input (Base Schema)
* Base schema for all contract symbols (alphanumeric, hyphens, underscores)
* Used as foundation for ContractSymbolSchema
*/
export const ContractSymbolSchema = z
.string()
.trim()
.min(1, 'Contract symbol cannot be empty')
.regex(
/^[a-zA-Z0-9_-]+$/,
'Contract symbol must contain only letters, numbers, hyphens, and underscores',
)
.describe('Contract symbol');
/**
* Solidity Compiler Version Input
* Optional solidity compiler version field for transactions
* Max 100 characters
*/
export const SolidityCompilerVersion = z
.string()
.trim()
.optional()
.describe('Optional Solidity compiler version');
export const GasInputSchema = z.number().min(0).optional().default(100000);
/**
* Approved Flag Input Schema
* Accepts string ("true"/"false") and transforms to boolean
*/
export const ApprovedFlagSchema = z
.stringbool({
truthy: ['true'],
falsy: ['false'],
})
.describe(
'Whether to approve or revoke the operator. Value must be "true" or "false"',
);
export const ContractErc721TokenIdSchema = z
.int()
.nonnegative('Token ID must be greater than or equal to 0')
.describe('Token ID (uint256) for tokenURI query');
/**
* Hex encoded data validation
* Format: 0x followed by 40 hexadecimal characters
*/
export const HexEncodedDataSchema = z
.string()
.regex(
/^0x[0-9a-fA-F]+$/,
'Data must be a hex encoded string starting in format "0x12abfe456123"',
)
.describe('HEX encoded data format');
export const ResolvedAccountCredentialSchema = z.object({
keyRefId: z.string(),
accountId: z.string(),
publicKey: z.string(),
});
export const ResolvedPublicKeySchema = z.object({
keyRefId: z.string(),
publicKey: z.string(),
});
export const NullLiteralSchema = z.literal('null');
export const KeyThresholdSchema = z
.number()
.int()
.positive()
.describe('M-of-N signing threshold');
export const MaxAutoAssociationsSchema = z
.number()
.int()
.min(-1, 'Value must be -1 (unlimited) or a non-negative integer')
.max(5000, 'Maximum value is 5000')
.optional()
.describe(
'Max automatic token associations (-1 for unlimited, 0 to disable)',
);
export const NodeIdSchema = z
.number()
.int()
.min(0, 'Node ID must be a non-negative integer')
.optional()