-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontractService.ts
More file actions
1469 lines (1302 loc) · 41.2 KB
/
contractService.ts
File metadata and controls
1469 lines (1302 loc) · 41.2 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
/**
* Smart Contract Interaction Service
*
* Handles all interactions with AbrahamSeeds contract on Base Sepolia/Base Mainnet
* Updated for the new EdenAgent-based AbrahamSeeds contract
*/
// CRITICAL: Load environment variables FIRST before any other code runs
// This ensures env vars are available during service initialization
if (process.env.NODE_ENV !== 'production') {
const dotenv = await import('dotenv');
dotenv.config({ path: '.env' });
dotenv.config({ path: '.env.local', override: true });
}
import {
createPublicClient,
createWalletClient,
http,
encodeFunctionData,
encodeAbiParameters,
type Address,
type Hash,
type PublicClient,
type WalletClient,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { baseSepolia, base } from "viem/chains";
import { readFileSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Load the ABI from source-tracked file
// Supports both new AbrahamSeeds and old TheSeeds ABIs
let SEEDS_ABI: any;
let IS_NEW_CONTRACT = true;
try {
const abiPath = join(__dirname, "../../lib/abi/AbrahamSeeds.json");
SEEDS_ABI = JSON.parse(readFileSync(abiPath, "utf-8"));
console.log("📄 Loaded AbrahamSeeds ABI (new contract)");
} catch {
try {
const oldAbiPath = join(__dirname, "../../lib/abi/TheSeeds.json");
SEEDS_ABI = JSON.parse(readFileSync(oldAbiPath, "utf-8"));
IS_NEW_CONTRACT = false;
console.log("📄 Loaded TheSeeds ABI (legacy contract)");
} catch {
throw new Error("No contract ABI found. Run 'npm run compile' first.");
}
}
// New Seed interface matching AbrahamSeeds contract
export interface Seed {
id: bigint;
creator: Address;
ipfsHash: string;
blessings: bigint; // reactionCount in new contract
score: bigint; // reactionScore in new contract
commandmentCount: bigint;
createdAt: bigint;
submittedInRound: bigint;
creationRound: bigint; // selectedInPeriod in new contract
isRetracted: boolean;
// Legacy compatibility fields
isWinner: boolean;
winnerInRound: bigint;
}
export interface Blessing {
seedId: bigint;
blesser: Address;
score: bigint;
timestamp: bigint;
}
export interface Commandment {
id: bigint;
seedId: bigint;
author: Address;
ipfsHash: string;
createdAt: bigint;
}
/**
* Contract Service for interacting with AbrahamSeeds contract
*/
class ContractService {
private publicClient: PublicClient;
private walletClient: WalletClient | null = null;
private contractAddress: Address;
private relayerAccount: ReturnType<typeof privateKeyToAccount> | null = null;
private deploymentBlock: bigint;
constructor() {
// Get configuration from environment
const network = process.env.NETWORK || "baseSepolia";
const rpcUrl = process.env.L2_RPC_URL;
const contractAddress =
process.env.L2_SEEDS_CONTRACT ||
"0x81901f757fd6b3c37e5391dbe6fa0affe9a181b5";
const relayerKey = process.env.RELAYER_PRIVATE_KEY;
const deploymentBlock = process.env.L2_SEEDS_DEPLOYMENT_BLOCK || "35963162";
console.log("🔍 ContractService initialization:");
console.log(` Network: ${network}`);
console.log(` RPC URL: ${rpcUrl ? "✅ Set" : "❌ Not set"}`);
console.log(` Contract: ${contractAddress}`);
console.log(` Relayer Key: ${relayerKey ? "✅ Set" : "❌ Not set"}`);
console.log(` Deployment Block: ${deploymentBlock}`);
console.log(` Contract Type: ${IS_NEW_CONTRACT ? "AbrahamSeeds (new)" : "TheSeeds (legacy)"}`);
if (!contractAddress) {
throw new Error("L2_SEEDS_CONTRACT environment variable not set");
}
this.contractAddress = contractAddress as Address;
this.deploymentBlock = BigInt(deploymentBlock);
// Set up chain
const chain = network === "base" ? base : baseSepolia;
// Create public client for read operations
this.publicClient = createPublicClient({
chain,
transport: http(rpcUrl),
}) as any;
// Create wallet client if relayer key is provided
if (relayerKey) {
this.relayerAccount = privateKeyToAccount(
(relayerKey.startsWith("0x")
? relayerKey
: `0x${relayerKey}`) as `0x${string}`
);
this.walletClient = createWalletClient({
account: this.relayerAccount,
chain,
transport: http(rpcUrl),
});
console.log(
`✅ Contract service initialized with relayer: ${this.relayerAccount.address}`
);
} else {
console.warn(
"⚠️ RELAYER_PRIVATE_KEY not set - backend-signed operations disabled"
);
}
console.log(
`📄 Connected to contract at: ${this.contractAddress}`
);
console.log(`🌐 Network: ${chain.name}`);
}
/**
* Check if the service can submit blessings on behalf of users
*/
canSubmitBlessings(): boolean {
return this.walletClient !== null && this.relayerAccount !== null;
}
/**
* Get relayer address
*/
getRelayerAddress(): Address | null {
return this.relayerAccount?.address || null;
}
/**
* Encode merkle proof as bytes for the new contract
*/
private encodeMerkleProof(merkleProof: string[]): `0x${string}` {
// The new contract expects the proof as abi.encode(bytes32[])
return encodeAbiParameters(
[{ type: 'bytes32[]' }],
[merkleProof as `0x${string}`[]]
);
}
/*//////////////////////////////////////////////////////////////
READ FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* Read: Get seed information
*/
async getSeed(seedId: number): Promise<Seed> {
const seed = await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "getSeed",
args: [BigInt(seedId)],
}) as any;
// Map to unified Seed interface (works with both old and new contracts)
if (IS_NEW_CONTRACT) {
return {
id: seed.id,
creator: seed.creator,
ipfsHash: seed.ipfsHash,
blessings: seed.blessings,
score: seed.score,
commandmentCount: seed.commandmentCount,
createdAt: seed.createdAt,
submittedInRound: seed.submittedInRound,
creationRound: seed.creationRound,
isRetracted: seed.isRetracted,
// Legacy compatibility
isWinner: seed.creationRound > 0n,
winnerInRound: seed.creationRound,
};
} else {
// Legacy TheSeeds format
return seed as Seed;
}
}
/**
* Read: Check if delegate is approved for user
*/
async isDelegate(
userAddress: Address,
delegateAddress: Address
): Promise<boolean> {
const funcName = IS_NEW_CONTRACT ? "delegateApprovals" : "isDelegate";
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: funcName,
args: [userAddress, delegateAddress],
})) as boolean;
}
/**
* Read: Get blessing count for a user on a specific seed
*/
async getBlessingCount(
userAddress: Address,
seedId: number
): Promise<bigint> {
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "getBlessingCount",
args: [userAddress, BigInt(seedId)],
})) as bigint;
}
/**
* Read: Get total seed count
*/
async getSeedCount(): Promise<bigint> {
const funcName = IS_NEW_CONTRACT ? "getSeedCount" : "seedCount";
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: funcName,
args: [],
})) as bigint;
}
/**
* Read: Get current round number
*/
async getCurrentRound(): Promise<bigint> {
const funcName = IS_NEW_CONTRACT ? "getCurrentRound" : "currentRound";
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: funcName,
args: [],
})) as bigint;
}
/**
* Read: Get seeds by round number (uses events for efficiency)
*/
async getSeedsByRound(round: number): Promise<Seed[]> {
const eventName = IS_NEW_CONTRACT ? "SeedSubmitted" : "SeedSubmitted";
const events = await this.publicClient.getContractEvents({
address: this.contractAddress,
abi: SEEDS_ABI,
eventName,
fromBlock: this.deploymentBlock,
toBlock: "latest",
});
// Filter events for this round and fetch seed data
const seedPromises = events
.map((event: any) => event.args as { seedId: bigint })
.map(async (args) => {
const seed = await this.getSeed(Number(args.seedId));
if (Number(seed.submittedInRound) === round) {
return seed;
}
return null;
});
const allSeeds = await Promise.all(seedPromises);
return allSeeds.filter((s): s is Seed => s !== null);
}
/**
* Read: Get seeds from current round
*/
async getCurrentRoundSeeds(): Promise<Seed[]> {
const currentRound = await this.getCurrentRound();
return this.getSeedsByRound(Number(currentRound));
}
/**
* Read: Get time remaining until voting period ends
*/
async getTimeUntilPeriodEnd(): Promise<bigint> {
const funcName = IS_NEW_CONTRACT ? "getTimeUntilRoundEnd" : "getTimeUntilPeriodEnd";
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: funcName,
args: [],
})) as bigint;
}
/**
* Read: Get current leading seed and its blessing score
*/
async getCurrentLeader(): Promise<{ leadingSeedId: bigint; score: bigint }> {
const leaders = await this.getCurrentLeaders();
const leadingSeedId = leaders.leadingSeedIds.length > 0 ? leaders.leadingSeedIds[0] : 0n;
return { leadingSeedId, score: leaders.score };
}
/**
* Read: Get blessing score for a specific seed
*/
async getSeedBlessingScore(seedId: number): Promise<bigint> {
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "getSeedBlessingScore",
args: [BigInt(seedId)],
})) as bigint;
}
/**
* Read: Get eligible seeds count (non-winner, non-retracted)
*/
async getEligibleSeedsCount(): Promise<bigint> {
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "getEligibleSeedsCount",
args: [],
})) as bigint;
}
/**
* Read: Get remaining blessings for a user
*/
async getRemainingBlessings(
userAddress: Address,
nftCount: number
): Promise<bigint> {
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "getRemainingBlessings",
args: [userAddress, BigInt(nftCount)],
})) as bigint;
}
/**
* Read: Get blessings per NFT configuration
*/
async getBlessingsPerNFT(): Promise<bigint> {
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "blessingsPerNFT",
args: [],
})) as bigint;
}
/**
* Read: Get voting period duration
*/
async getVotingPeriod(): Promise<bigint> {
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "votingPeriod",
args: [],
})) as bigint;
}
/**
* Read: Get commandment count for a seed
*/
async getCommandmentCount(seedId: number): Promise<bigint> {
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "getCommandmentCount",
args: [BigInt(seedId)],
})) as bigint;
}
/**
* Read: Get round winner
*/
async getRoundWinner(round: number): Promise<bigint> {
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "getRoundWinner",
args: [BigInt(round)],
})) as bigint;
}
/**
* Read: Get current leaders (all tied leaders)
*/
async getCurrentLeaders(): Promise<{
leadingSeedIds: bigint[];
score: bigint;
}> {
// Get all eligible seeds and find max score
const totalSeeds = await this.getSeedCount();
let maxScore = 0n;
const leaders: bigint[] = [];
for (let i = 0; i < Number(totalSeeds); i++) {
const seedId = BigInt(i);
const seed = await this.getSeed(Number(seedId));
// Skip winners and retracted seeds
if (seed.isWinner || seed.isRetracted) continue;
const seedScore = seed.score;
if (seedScore > maxScore) {
maxScore = seedScore;
leaders.length = 0;
leaders.push(seedId);
} else if (seedScore === maxScore && seedScore > 0n) {
leaders.push(seedId);
}
}
return { leadingSeedIds: leaders, score: maxScore };
}
/*//////////////////////////////////////////////////////////////
NFT FUNCTIONS (ERC1155)
//////////////////////////////////////////////////////////////*/
/**
* Read: Get token ID for a seed ID
*/
async getTokenIdBySeedId(seedId: number): Promise<bigint> {
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "getTokenIdBySeedId",
args: [BigInt(seedId)],
})) as bigint;
}
/**
* Read: Get seed ID for a token ID
*/
async getSeedIdByTokenId(tokenId: number): Promise<bigint> {
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "getSeedIdByTokenId",
args: [BigInt(tokenId)],
})) as bigint;
}
/**
* Read: Get creation edition info
*/
async getCreationEditionInfo(tokenId: number): Promise<{
seedId: bigint;
totalMinted: bigint;
creatorEditions: bigint;
curatorEditions: bigint;
curatorDistributed: bigint;
publicEditions: bigint;
publicSold: bigint;
availableForSale: bigint;
}> {
const result = await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "getCreationEditionInfo",
args: [BigInt(tokenId)],
}) as any;
return {
seedId: result[0],
totalMinted: result[1],
creatorEditions: result[2],
curatorEditions: result[3],
curatorDistributed: result[4],
publicEditions: result[5],
publicSold: result[6],
availableForSale: result[7],
};
}
/*//////////////////////////////////////////////////////////////
BLESSING FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* Write: Bless a seed on behalf of a user (operator pattern)
* Requires OPERATOR_ROLE or user delegation
*/
async blessSeedFor(
seedId: number,
userAddress: Address,
tokenIds: number[],
merkleProof: string[]
): Promise<{
success: boolean;
txHash?: Hash;
error?: string;
}> {
if (!this.walletClient || !this.relayerAccount) {
return {
success: false,
error: "Relayer not configured - set RELAYER_PRIVATE_KEY",
};
}
try {
const tokenIdsBigInt = tokenIds.map((id) => BigInt(id));
const proofEncoded = this.encodeMerkleProof(merkleProof);
// Simulate first to catch errors
await this.publicClient.simulateContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "blessSeedFor",
args: [BigInt(seedId), userAddress, tokenIdsBigInt, proofEncoded],
account: this.relayerAccount,
});
// Submit transaction
const hash = await this.walletClient.writeContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "blessSeedFor",
args: [BigInt(seedId), userAddress, tokenIdsBigInt, proofEncoded],
} as any);
// Wait for confirmation
const receipt = await this.publicClient.waitForTransactionReceipt({
hash,
});
return {
success: receipt.status === "success",
txHash: hash,
};
} catch (error: any) {
console.error("Error blessing seed:", error);
let errorMessage = "Failed to submit blessing";
if (error.message.includes("NotAuthorized")) {
errorMessage =
"Backend not authorized - user must approve backend as delegate";
} else if (error.message.includes("SessionNotFound")) {
errorMessage = "Seed does not exist";
} else if (error.message.includes("SessionAlreadySelected")) {
errorMessage = "Cannot bless a winning seed";
} else if (error.message.includes("InvalidGatingProof")) {
errorMessage = "Invalid NFT ownership proof";
} else if (error.message.includes("DailyLimitReached")) {
errorMessage = "Daily blessing limit reached";
} else if (error.message.includes("NoTokens")) {
errorMessage = "No NFTs owned";
}
return {
success: false,
error: errorMessage,
};
}
}
/**
* Prepare blessing transaction data for client-side signing
*/
prepareBlessingTransaction(
seedId: number,
userAddress: Address,
tokenIds: number[],
merkleProof: string[]
) {
const tokenIdsBigInt = tokenIds.map((id) => BigInt(id));
const proofEncoded = this.encodeMerkleProof(merkleProof);
return {
to: this.contractAddress,
data: encodeFunctionData({
abi: SEEDS_ABI,
functionName: "blessSeed",
args: [BigInt(seedId), tokenIdsBigInt, proofEncoded],
}),
from: userAddress,
chainId: this.publicClient.chain?.id,
};
}
/**
* Prepare delegate approval transaction for client-side signing
*/
prepareDelegateApprovalTransaction(
userAddress: Address,
delegateAddress: Address,
approved: boolean
) {
return {
to: this.contractAddress,
data: encodeFunctionData({
abi: SEEDS_ABI,
functionName: "approveDelegate",
args: [delegateAddress, approved],
}),
from: userAddress,
chainId: this.publicClient.chain?.id,
};
}
/*//////////////////////////////////////////////////////////////
SEED CREATION FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* Check if an address has CREATOR_ROLE
*/
async hasCreatorRole(address: Address): Promise<boolean> {
const CREATOR_ROLE =
"0x828634d95e775031b9ff576c159e20a8a57946bda7a10f5b0e5f3b5f0e0ad4e7"; // keccak256("CREATOR_ROLE")
return (await this.publicClient.readContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "hasRole",
args: [CREATOR_ROLE as `0x${string}`, address],
})) as boolean;
}
/**
* Write: Submit a seed to the blockchain (backend-signed)
* Requires relayer to have CREATOR_ROLE
*/
async submitSeed(ipfsHash: string): Promise<{
success: boolean;
seedId?: number;
txHash?: Hash;
error?: string;
}> {
if (!this.walletClient || !this.relayerAccount) {
return {
success: false,
error: "Wallet client not initialized - RELAYER_PRIVATE_KEY not set",
};
}
try {
// Check if relayer has CREATOR_ROLE
const hasRole = await this.hasCreatorRole(this.relayerAccount.address);
if (!hasRole) {
return {
success: false,
error: "Relayer does not have CREATOR_ROLE",
};
}
const hash = await this.walletClient.writeContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "submitSeed",
args: [ipfsHash],
} as any);
const receipt = await this.publicClient.waitForTransactionReceipt({
hash,
});
if (receipt.status !== "success") {
return {
success: false,
error: "Transaction failed",
};
}
// Get the seed ID from the SeedSubmitted event
let seedId: number | undefined;
for (const log of receipt.logs) {
try {
if (log.topics[0] && log.topics[1]) {
seedId = Number(BigInt(log.topics[1]));
break;
}
} catch (e) {
// Continue if this log doesn't match
}
}
return {
success: true,
seedId,
txHash: hash,
};
} catch (error: any) {
console.error("Error submitting seed:", error);
return {
success: false,
error: error.message || "Failed to submit seed",
};
}
}
/**
* Prepare seed submission transaction for client-side signing
*/
prepareSeedSubmissionTransaction(ipfsHash: string, creatorAddress: Address) {
return {
to: this.contractAddress,
data: encodeFunctionData({
abi: SEEDS_ABI,
functionName: "submitSeed",
args: [ipfsHash],
}),
from: creatorAddress,
chainId: this.publicClient.chain?.id,
};
}
/**
* Admin: Add a creator (grant CREATOR_ROLE)
*/
async addCreator(creatorAddress: Address): Promise<{
success: boolean;
txHash?: Hash;
error?: string;
}> {
if (!this.walletClient || !this.relayerAccount) {
return {
success: false,
error: "Wallet client not initialized",
};
}
try {
const hash = await this.walletClient.writeContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "addCreator",
args: [creatorAddress],
} as any);
const receipt = await this.publicClient.waitForTransactionReceipt({
hash,
});
return {
success: receipt.status === "success",
txHash: hash,
};
} catch (error: any) {
console.error("Error adding creator:", error);
return {
success: false,
error: error.message || "Failed to add creator",
};
}
}
/*//////////////////////////////////////////////////////////////
WINNER SELECTION FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* Admin: Select daily winner (call contract's selectDailyWinner)
*/
async selectDailyWinner(): Promise<{
success: boolean;
winningSeedId?: number;
tokenId?: number;
txHash?: Hash;
error?: string;
details?: string;
diagnostics?: {
currentRound: number;
seedsInRound: number;
timeRemaining: number;
currentLeader: { seedId: number; score: string };
};
}> {
if (!this.walletClient || !this.relayerAccount) {
return {
success: false,
error: "Wallet client not initialized - RELAYER_PRIVATE_KEY required",
};
}
try {
console.log("🔍 Running pre-flight diagnostics...");
// Check current round
const currentRound = await this.getCurrentRound();
console.log(` Current Round: ${currentRound}`);
// Check eligible seeds
const eligibleCount = await this.getEligibleSeedsCount();
console.log(` Eligible Seeds: ${eligibleCount}`);
if (eligibleCount === 0n) {
return {
success: false,
error: "No eligible seeds available for winner selection",
diagnostics: {
currentRound: Number(currentRound),
seedsInRound: 0,
timeRemaining: 0,
currentLeader: { seedId: 0, score: "0" },
},
};
}
// Check time remaining
const timeRemaining = await this.getTimeUntilPeriodEnd();
console.log(` Time Until Period End: ${timeRemaining}s`);
if (timeRemaining > 0n) {
return {
success: false,
error: `Voting period not ended (${timeRemaining}s remaining)`,
diagnostics: {
currentRound: Number(currentRound),
seedsInRound: Number(eligibleCount),
timeRemaining: Number(timeRemaining),
currentLeader: { seedId: 0, score: "0" },
},
};
}
console.log("✅ Pre-flight checks passed, proceeding with winner selection...");
// Check relayer balance
const balance = await this.publicClient.getBalance({
address: this.relayerAccount.address,
});
console.log(` Relayer Balance: ${Number(balance) / 1e18} ETH`);
if (balance === 0n) {
return {
success: false,
error: `Relayer account has no balance. Please fund ${this.relayerAccount.address}`,
};
}
// Simulate transaction
console.log("🔍 Simulating transaction...");
try {
await this.publicClient.simulateContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "selectDailyWinner",
args: [],
account: this.relayerAccount,
});
console.log("✅ Simulation successful");
} catch (simError: any) {
throw new Error(`Simulation failed: ${simError.shortMessage || simError.message}`);
}
// Submit transaction
console.log("📤 Submitting transaction...");
const hash = await this.walletClient.writeContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "selectDailyWinner",
args: [],
} as any);
const receipt = await this.publicClient.waitForTransactionReceipt({
hash,
});
if (receipt.status !== "success") {
return {
success: false,
error: "Transaction failed",
};
}
// Parse events to get winner info
let winningSeedId: number | undefined;
let tokenId: number | undefined;
for (const log of receipt.logs) {
try {
// CreationMinted event: round, seedId, tokenId
if (log.topics[0] && log.topics[1] && log.topics[2]) {
winningSeedId = Number(BigInt(log.topics[2]));
// tokenId is in the data
if (log.data && log.data !== '0x') {
tokenId = Number(BigInt(log.data));
}
break;
}
} catch (e) {
// Continue
}
}
return {
success: true,
winningSeedId,
tokenId,
txHash: hash,
diagnostics: {
currentRound: Number(currentRound),
seedsInRound: Number(eligibleCount),
timeRemaining: 0,
currentLeader: { seedId: winningSeedId || 0, score: "N/A" },
},
};
} catch (error: any) {
console.error("Error selecting daily winner:", error);
let errorMessage = "Failed to select daily winner";
if (error.message?.includes("PeriodNotEnded")) {
errorMessage = "Voting period has not ended yet";
} else if (error.message?.includes("NoValidSession")) {
errorMessage = "No valid winner found";
}
return {
success: false,
error: errorMessage,
details: error.message,
};
}
}
/*//////////////////////////////////////////////////////////////
COMMANDMENT FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* Write: Add commandment on behalf of user
*/
async addCommandmentFor(
seedId: number,
userAddress: Address,
ipfsHash: string,
tokenIds: number[],
merkleProof: string[]
): Promise<{
success: boolean;
txHash?: Hash;
commandmentId?: number;
error?: string;
}> {
if (!this.walletClient || !this.relayerAccount) {
return { success: false, error: "Relayer not configured" };
}
try {
const tokenIdsBigInt = tokenIds.map((id) => BigInt(id));
const proofEncoded = this.encodeMerkleProof(merkleProof);
// The new contract uses sendMessage internally via addCommandment
const hash = await this.walletClient.writeContract({
address: this.contractAddress,
abi: SEEDS_ABI,
functionName: "addCommandment",
args: [BigInt(seedId), ipfsHash, tokenIdsBigInt, proofEncoded],
} as any);
const receipt = await this.publicClient.waitForTransactionReceipt({
hash,
});
// Parse CommandmentSubmitted event
let commandmentId: number | undefined;