Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions platforms/eCurrency-api/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"graphql-request": "^6.1.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.11.3",
"reflect-metadata": "^0.2.1",
Expand Down
85 changes: 85 additions & 0 deletions platforms/eCurrency-api/src/controllers/WebhookController.ts
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
import { Request, Response } from "express";
import { UserService } from "../services/UserService";
import { GroupService } from "../services/GroupService";
import { MessageService } from "../services/MessageService";
import { adapter } from "../web3adapter/watchers/subscriber";
import { User } from "../database/entities/User";
import { Group } from "../database/entities/Group";
import { Message } from "../database/entities/Message";
import axios from "axios";

export class WebhookController {
userService: UserService;
groupService: GroupService;
messageService: MessageService;
adapter: typeof adapter;

constructor() {
this.userService = new UserService();
this.groupService = new GroupService();
this.messageService = new MessageService();
this.adapter = adapter;
}

Expand DownExpand Up@@ -179,6 +184,86 @@ export class WebhookController {
finalLocalId = group.id;
}
}
} else if (mapping.tableName === "messages") {
console.log("Processing message with data:", local.data);

// Extract sender and group from the message data
let sender: User | null = null;
let group: Group | null = null;

if (local.data.sender && typeof local.data.sender === "string") {
const senderId = local.data.sender.split("(")[1].split(")")[0];
sender = await this.userService.getUserById(senderId);
}

if (local.data.group && typeof local.data.group === "string") {
const groupId = local.data.group.split("(")[1].split(")")[0];
group = await this.groupService.getGroupById(groupId);
}
Comment thread
coodos marked this conversation as resolved.

// Check if this is a system message (no sender required)
const isSystemMessage = local.data.isSystemMessage === true ||
(local.data.text && typeof local.data.text === 'string' && local.data.text.startsWith('$$system-message$$'));

if (!group) {
console.error("Group not found for message");
return res.status(500).send();
}

// For system messages, sender can be null
if (!isSystemMessage && !sender) {
console.error("Sender not found for non-system message");
return res.status(500).send();
}

if (localId) {
console.log("Updating existing message with localId:", localId);
const message = await this.messageService.getMessageById(localId);
if (!message) {
console.error("Message not found for localId:", localId);
return res.status(500).send();
}

// For system messages, ensure the prefix is preserved
if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
message.sender = sender || undefined;
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
Comment on lines +227 to +235

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Potential data loss: sender field may be unintentionally cleared.

On line 233, setting message.sender = sender || undefined will set sender to undefined if the sender lookup fails, even if the message previously had a valid sender. This could unintentionally clear the sender field during updates.

Consider preserving the existing sender if lookup fails:

 if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
- message.sender = sender || undefined;+ // Only update sender if explicitly provided (preserve existing sender if lookup fails)+ if (local.data.sender) {+ message.sender = sender || undefined;+ }
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
message.sender=sender||undefined;
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
// Only update sender if explicitly provided (preserve existing sender if lookup fails)
if(local.data.sender){
message.sender=sender||undefined;
}
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
🤖 Prompt for AI Agents
In platforms/eCurrency-api/src/controllers/WebhookController.ts around lines 227
to 235, the code currently assigns message.sender = sender || undefined which
will clear an existing sender when the lookup returns a falsy value; change the
logic to only overwrite message.sender when sender is a valid value (e.g.,
non-null/defined) so that if the lookup fails the existing message.sender is
preserved, and ensure types are respected (cast or guard as needed) when
conditionally assigning.


this.adapter.addToLockedIds(localId);
await this.messageService.messageRepository.save(message);
console.log("Updated message:", message.id);
finalLocalId = message.id;
} else {
console.log("Creating new message");
let message: Message;

if (isSystemMessage) {
message = await this.messageService.createSystemMessageWithoutPrefix({
text: local.data.text as string,
groupId: group.id,
});
} else {
message = await this.messageService.createMessage({
text: local.data.text as string,
senderId: sender!.id, // We know sender exists for non-system messages
groupId: group.id,
});
}

console.log("Created message with ID:", message.id);
this.adapter.addToLockedIds(message.id);
await this.adapter.mappingDb.storeMapping({
localId: message.id,
globalId: req.body.id,
});
console.log("Stored mapping for message:", message.id, "->", req.body.id);
finalLocalId = message.id;
}
}

res.status(200).send();
Expand Down
4 changes: 3 additions & 1 deletion platforms/eCurrency-api/src/database/data-source.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,8 @@ import { User } from "./entities/User";
import { Group } from "./entities/Group";
import { Currency } from "./entities/Currency";
import { Ledger } from "./entities/Ledger";
import { Message } from "./entities/Message";
import { UserEVaultMapping } from "./entities/UserEVaultMapping";
import { PostgresSubscriber } from "../web3adapter/watchers/subscriber";

// Use absolute path for better CLI compatibility
Expand All@@ -16,7 +18,7 @@ export const dataSourceOptions: DataSourceOptions = {
type: "postgres",
url: process.env.ECURRENCY_DATABASE_URL,
synchronize: false, // Auto-sync in development
entities: [User, Group, Currency, Ledger],
entities: [User, Group, Currency, Ledger, Message, UserEVaultMapping],
migrations: [path.join(__dirname, "migrations", "*.ts")],
logging: process.env.NODE_ENV === "development",
subscribers: [PostgresSubscriber],
Expand Down
5 changes: 5 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Group.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
PrimaryGeneratedColumn,
Column,
ManyToMany,
OneToMany,
JoinTable,
} from "typeorm";
import { User } from "./User";
import { Message } from "./Message";

@Entity()
export class Group {
Expand DownExpand Up@@ -68,6 +70,9 @@ export class Group {
@Column({ type: "json", nullable: true })
originalMatchParticipants!: string[]; // Store user IDs from the original match

@OneToMany(() => Message, (message) => message.group)
messages!: Message[];

@CreateDateColumn()
createdAt!: Date;

Expand Down
41 changes: 41 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Message.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
} from "typeorm";
import { User } from "./User";
import { Group } from "./Group";

@Entity("messages")
export class Message {
@PrimaryGeneratedColumn("uuid")
id!: string;

@ManyToOne(() => User, { nullable: true })
sender?: User; // Nullable for system messages

@Column("text")
text!: string;

@ManyToOne(() => Group, (group) => group.messages)
group!: Group;

@Column({ default: false })
isSystemMessage!: boolean; // Flag to identify system messages

@Column("uuid", { nullable: true })
voteId?: string; // ID of the vote/poll this system message relates to

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;

@Column({ default: false })
isArchived!: boolean;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";

@Entity("user_evault_mappings")
export class UserEVaultMapping {
@PrimaryGeneratedColumn("uuid")
id!: string;

@Column()
localUserId!: string;

@Column()
evaultW3id!: string;

@Column()
evaultUri!: string;

@Column({ nullable: true })
userProfileId!: string; // ID of the UserProfile object in the eVault

@Column({ type: "jsonb", nullable: true })
userProfileData!: any; // Store the UserProfile data
Comment thread
coodos marked this conversation as resolved.

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class Migration1765208128946 implements MigrationInterface {
name = 'Migration1765208128946'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "messages" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "text" text NOT NULL, "isSystemMessage" boolean NOT NULL DEFAULT false, "voteId" uuid, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), "isArchived" boolean NOT NULL DEFAULT false, "senderId" uuid, "groupId" uuid, CONSTRAINT "PK_18325f38ae6de43878487eff986" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE TABLE "user_evault_mappings" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "localUserId" character varying NOT NULL, "evaultW3id" character varying NOT NULL, "evaultUri" character varying NOT NULL, "userProfileId" character varying, "userProfileData" jsonb, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_744ddb4ddca6af2de54773e9213" PRIMARY KEY ("id"))`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce" FOREIGN KEY ("senderId") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e" FOREIGN KEY ("groupId") REFERENCES "group"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
Comment thread
coodos marked this conversation as resolved.
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e"`);
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce"`);
await queryRunner.query(`DROP TABLE "user_evault_mappings"`);
await queryRunner.query(`DROP TABLE "messages"`);
}

}
18 changes: 18 additions & 0 deletions platforms/eCurrency-api/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ import { CurrencyController } from "./controllers/CurrencyController";
import { LedgerController } from "./controllers/LedgerController";
import { authMiddleware, authGuard } from "./middleware/auth";
import { adapter } from "./web3adapter/watchers/subscriber";
import { PlatformEVaultService } from "./services/PlatformEVaultService";

config({ path: path.resolve(__dirname, "../../../.env") });

Expand All@@ -24,6 +25,23 @@ AppDataSource.initialize()
.then(async () => {
console.log("Database connection established");
console.log("Web3 adapter initialized");

// Initialize platform eVault for eCurrency
try {
const platformService = PlatformEVaultService.getInstance();
const exists = await platformService.checkPlatformEVaultExists();

if (!exists) {
console.log("🔧 Creating platform eVault for eCurrency...");
const result = await platformService.createPlatformEVault();
console.log(`✅ Platform eVault created successfully: ${result.w3id}`);
} else {
console.log("✅ Platform eVault already exists for eCurrency");
}
} catch (error) {
console.error("❌ Failed to initialize platform eVault:", error);
// Don't exit the process, just log the error
}
})
.catch((error: unknown) => {
console.error("Error during initialization:", error);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions platforms/eCurrency-api/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"graphql-request": "^6.1.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.11.3",
"reflect-metadata": "^0.2.1",
Expand Down
85 changes: 85 additions & 0 deletions platforms/eCurrency-api/src/controllers/WebhookController.ts
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
import { Request, Response } from "express";
import { UserService } from "../services/UserService";
import { GroupService } from "../services/GroupService";
import { MessageService } from "../services/MessageService";
import { adapter } from "../web3adapter/watchers/subscriber";
import { User } from "../database/entities/User";
import { Group } from "../database/entities/Group";
import { Message } from "../database/entities/Message";
import axios from "axios";

export class WebhookController {
userService: UserService;
groupService: GroupService;
messageService: MessageService;
adapter: typeof adapter;

constructor() {
this.userService = new UserService();
this.groupService = new GroupService();
this.messageService = new MessageService();
this.adapter = adapter;
}

Expand DownExpand Up@@ -179,6 +184,86 @@ export class WebhookController {
finalLocalId = group.id;
}
}
} else if (mapping.tableName === "messages") {
console.log("Processing message with data:", local.data);

// Extract sender and group from the message data
let sender: User | null = null;
let group: Group | null = null;

if (local.data.sender && typeof local.data.sender === "string") {
const senderId = local.data.sender.split("(")[1].split(")")[0];
sender = await this.userService.getUserById(senderId);
}

if (local.data.group && typeof local.data.group === "string") {
const groupId = local.data.group.split("(")[1].split(")")[0];
group = await this.groupService.getGroupById(groupId);
}
Comment thread
coodos marked this conversation as resolved.

// Check if this is a system message (no sender required)
const isSystemMessage = local.data.isSystemMessage === true ||
(local.data.text && typeof local.data.text === 'string' && local.data.text.startsWith('$$system-message$$'));

if (!group) {
console.error("Group not found for message");
return res.status(500).send();
}

// For system messages, sender can be null
if (!isSystemMessage && !sender) {
console.error("Sender not found for non-system message");
return res.status(500).send();
}

if (localId) {
console.log("Updating existing message with localId:", localId);
const message = await this.messageService.getMessageById(localId);
if (!message) {
console.error("Message not found for localId:", localId);
return res.status(500).send();
}

// For system messages, ensure the prefix is preserved
if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
message.sender = sender || undefined;
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
Comment on lines +227 to +235

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Potential data loss: sender field may be unintentionally cleared.

On line 233, setting message.sender = sender || undefined will set sender to undefined if the sender lookup fails, even if the message previously had a valid sender. This could unintentionally clear the sender field during updates.

Consider preserving the existing sender if lookup fails:

 if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
- message.sender = sender || undefined;+ // Only update sender if explicitly provided (preserve existing sender if lookup fails)+ if (local.data.sender) {+ message.sender = sender || undefined;+ }
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
message.sender=sender||undefined;
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
// Only update sender if explicitly provided (preserve existing sender if lookup fails)
if(local.data.sender){
message.sender=sender||undefined;
}
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
🤖 Prompt for AI Agents
In platforms/eCurrency-api/src/controllers/WebhookController.ts around lines 227
to 235, the code currently assigns message.sender = sender || undefined which
will clear an existing sender when the lookup returns a falsy value; change the
logic to only overwrite message.sender when sender is a valid value (e.g.,
non-null/defined) so that if the lookup fails the existing message.sender is
preserved, and ensure types are respected (cast or guard as needed) when
conditionally assigning.


this.adapter.addToLockedIds(localId);
await this.messageService.messageRepository.save(message);
console.log("Updated message:", message.id);
finalLocalId = message.id;
} else {
console.log("Creating new message");
let message: Message;

if (isSystemMessage) {
message = await this.messageService.createSystemMessageWithoutPrefix({
text: local.data.text as string,
groupId: group.id,
});
} else {
message = await this.messageService.createMessage({
text: local.data.text as string,
senderId: sender!.id, // We know sender exists for non-system messages
groupId: group.id,
});
}

console.log("Created message with ID:", message.id);
this.adapter.addToLockedIds(message.id);
await this.adapter.mappingDb.storeMapping({
localId: message.id,
globalId: req.body.id,
});
console.log("Stored mapping for message:", message.id, "->", req.body.id);
finalLocalId = message.id;
}
}

res.status(200).send();
Expand Down
4 changes: 3 additions & 1 deletion platforms/eCurrency-api/src/database/data-source.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,8 @@ import { User } from "./entities/User";
import { Group } from "./entities/Group";
import { Currency } from "./entities/Currency";
import { Ledger } from "./entities/Ledger";
import { Message } from "./entities/Message";
import { UserEVaultMapping } from "./entities/UserEVaultMapping";
import { PostgresSubscriber } from "../web3adapter/watchers/subscriber";

// Use absolute path for better CLI compatibility
Expand All@@ -16,7 +18,7 @@ export const dataSourceOptions: DataSourceOptions = {
type: "postgres",
url: process.env.ECURRENCY_DATABASE_URL,
synchronize: false, // Auto-sync in development
entities: [User, Group, Currency, Ledger],
entities: [User, Group, Currency, Ledger, Message, UserEVaultMapping],
migrations: [path.join(__dirname, "migrations", "*.ts")],
logging: process.env.NODE_ENV === "development",
subscribers: [PostgresSubscriber],
Expand Down
5 changes: 5 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Group.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
PrimaryGeneratedColumn,
Column,
ManyToMany,
OneToMany,
JoinTable,
} from "typeorm";
import { User } from "./User";
import { Message } from "./Message";

@Entity()
export class Group {
Expand DownExpand Up@@ -68,6 +70,9 @@ export class Group {
@Column({ type: "json", nullable: true })
originalMatchParticipants!: string[]; // Store user IDs from the original match

@OneToMany(() => Message, (message) => message.group)
messages!: Message[];

@CreateDateColumn()
createdAt!: Date;

Expand Down
41 changes: 41 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Message.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
} from "typeorm";
import { User } from "./User";
import { Group } from "./Group";

@Entity("messages")
export class Message {
@PrimaryGeneratedColumn("uuid")
id!: string;

@ManyToOne(() => User, { nullable: true })
sender?: User; // Nullable for system messages

@Column("text")
text!: string;

@ManyToOne(() => Group, (group) => group.messages)
group!: Group;

@Column({ default: false })
isSystemMessage!: boolean; // Flag to identify system messages

@Column("uuid", { nullable: true })
voteId?: string; // ID of the vote/poll this system message relates to

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;

@Column({ default: false })
isArchived!: boolean;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";

@Entity("user_evault_mappings")
export class UserEVaultMapping {
@PrimaryGeneratedColumn("uuid")
id!: string;

@Column()
localUserId!: string;

@Column()
evaultW3id!: string;

@Column()
evaultUri!: string;

@Column({ nullable: true })
userProfileId!: string; // ID of the UserProfile object in the eVault

@Column({ type: "jsonb", nullable: true })
userProfileData!: any; // Store the UserProfile data
Comment thread
coodos marked this conversation as resolved.

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class Migration1765208128946 implements MigrationInterface {
name = 'Migration1765208128946'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "messages" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "text" text NOT NULL, "isSystemMessage" boolean NOT NULL DEFAULT false, "voteId" uuid, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), "isArchived" boolean NOT NULL DEFAULT false, "senderId" uuid, "groupId" uuid, CONSTRAINT "PK_18325f38ae6de43878487eff986" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE TABLE "user_evault_mappings" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "localUserId" character varying NOT NULL, "evaultW3id" character varying NOT NULL, "evaultUri" character varying NOT NULL, "userProfileId" character varying, "userProfileData" jsonb, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_744ddb4ddca6af2de54773e9213" PRIMARY KEY ("id"))`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce" FOREIGN KEY ("senderId") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e" FOREIGN KEY ("groupId") REFERENCES "group"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
Comment thread
coodos marked this conversation as resolved.
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e"`);
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce"`);
await queryRunner.query(`DROP TABLE "user_evault_mappings"`);
await queryRunner.query(`DROP TABLE "messages"`);
}

}
18 changes: 18 additions & 0 deletions platforms/eCurrency-api/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ import { CurrencyController } from "./controllers/CurrencyController";
import { LedgerController } from "./controllers/LedgerController";
import { authMiddleware, authGuard } from "./middleware/auth";
import { adapter } from "./web3adapter/watchers/subscriber";
import { PlatformEVaultService } from "./services/PlatformEVaultService";

config({ path: path.resolve(__dirname, "../../../.env") });

Expand All@@ -24,6 +25,23 @@ AppDataSource.initialize()
.then(async () => {
console.log("Database connection established");
console.log("Web3 adapter initialized");

// Initialize platform eVault for eCurrency
try {
const platformService = PlatformEVaultService.getInstance();
const exists = await platformService.checkPlatformEVaultExists();

if (!exists) {
console.log("🔧 Creating platform eVault for eCurrency...");
const result = await platformService.createPlatformEVault();
console.log(`✅ Platform eVault created successfully: ${result.w3id}`);
} else {
console.log("✅ Platform eVault already exists for eCurrency");
}
} catch (error) {
console.error("❌ Failed to initialize platform eVault:", error);
// Don't exit the process, just log the error
}
})
.catch((error: unknown) => {
console.error("Error during initialization:", error);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions platforms/eCurrency-api/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"graphql-request": "^6.1.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.11.3",
"reflect-metadata": "^0.2.1",
Expand Down
85 changes: 85 additions & 0 deletions platforms/eCurrency-api/src/controllers/WebhookController.ts
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
import { Request, Response } from "express";
import { UserService } from "../services/UserService";
import { GroupService } from "../services/GroupService";
import { MessageService } from "../services/MessageService";
import { adapter } from "../web3adapter/watchers/subscriber";
import { User } from "../database/entities/User";
import { Group } from "../database/entities/Group";
import { Message } from "../database/entities/Message";
import axios from "axios";

export class WebhookController {
userService: UserService;
groupService: GroupService;
messageService: MessageService;
adapter: typeof adapter;

constructor() {
this.userService = new UserService();
this.groupService = new GroupService();
this.messageService = new MessageService();
this.adapter = adapter;
}

Expand DownExpand Up@@ -179,6 +184,86 @@ export class WebhookController {
finalLocalId = group.id;
}
}
} else if (mapping.tableName === "messages") {
console.log("Processing message with data:", local.data);

// Extract sender and group from the message data
let sender: User | null = null;
let group: Group | null = null;

if (local.data.sender && typeof local.data.sender === "string") {
const senderId = local.data.sender.split("(")[1].split(")")[0];
sender = await this.userService.getUserById(senderId);
}

if (local.data.group && typeof local.data.group === "string") {
const groupId = local.data.group.split("(")[1].split(")")[0];
group = await this.groupService.getGroupById(groupId);
}
Comment thread
coodos marked this conversation as resolved.

// Check if this is a system message (no sender required)
const isSystemMessage = local.data.isSystemMessage === true ||
(local.data.text && typeof local.data.text === 'string' && local.data.text.startsWith('$$system-message$$'));

if (!group) {
console.error("Group not found for message");
return res.status(500).send();
}

// For system messages, sender can be null
if (!isSystemMessage && !sender) {
console.error("Sender not found for non-system message");
return res.status(500).send();
}

if (localId) {
console.log("Updating existing message with localId:", localId);
const message = await this.messageService.getMessageById(localId);
if (!message) {
console.error("Message not found for localId:", localId);
return res.status(500).send();
}

// For system messages, ensure the prefix is preserved
if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
message.sender = sender || undefined;
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
Comment on lines +227 to +235

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Potential data loss: sender field may be unintentionally cleared.

On line 233, setting message.sender = sender || undefined will set sender to undefined if the sender lookup fails, even if the message previously had a valid sender. This could unintentionally clear the sender field during updates.

Consider preserving the existing sender if lookup fails:

 if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
- message.sender = sender || undefined;+ // Only update sender if explicitly provided (preserve existing sender if lookup fails)+ if (local.data.sender) {+ message.sender = sender || undefined;+ }
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
message.sender=sender||undefined;
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
// Only update sender if explicitly provided (preserve existing sender if lookup fails)
if(local.data.sender){
message.sender=sender||undefined;
}
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
🤖 Prompt for AI Agents
In platforms/eCurrency-api/src/controllers/WebhookController.ts around lines 227
to 235, the code currently assigns message.sender = sender || undefined which
will clear an existing sender when the lookup returns a falsy value; change the
logic to only overwrite message.sender when sender is a valid value (e.g.,
non-null/defined) so that if the lookup fails the existing message.sender is
preserved, and ensure types are respected (cast or guard as needed) when
conditionally assigning.


this.adapter.addToLockedIds(localId);
await this.messageService.messageRepository.save(message);
console.log("Updated message:", message.id);
finalLocalId = message.id;
} else {
console.log("Creating new message");
let message: Message;

if (isSystemMessage) {
message = await this.messageService.createSystemMessageWithoutPrefix({
text: local.data.text as string,
groupId: group.id,
});
} else {
message = await this.messageService.createMessage({
text: local.data.text as string,
senderId: sender!.id, // We know sender exists for non-system messages
groupId: group.id,
});
}

console.log("Created message with ID:", message.id);
this.adapter.addToLockedIds(message.id);
await this.adapter.mappingDb.storeMapping({
localId: message.id,
globalId: req.body.id,
});
console.log("Stored mapping for message:", message.id, "->", req.body.id);
finalLocalId = message.id;
}
}

res.status(200).send();
Expand Down
4 changes: 3 additions & 1 deletion platforms/eCurrency-api/src/database/data-source.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,8 @@ import { User } from "./entities/User";
import { Group } from "./entities/Group";
import { Currency } from "./entities/Currency";
import { Ledger } from "./entities/Ledger";
import { Message } from "./entities/Message";
import { UserEVaultMapping } from "./entities/UserEVaultMapping";
import { PostgresSubscriber } from "../web3adapter/watchers/subscriber";

// Use absolute path for better CLI compatibility
Expand All@@ -16,7 +18,7 @@ export const dataSourceOptions: DataSourceOptions = {
type: "postgres",
url: process.env.ECURRENCY_DATABASE_URL,
synchronize: false, // Auto-sync in development
entities: [User, Group, Currency, Ledger],
entities: [User, Group, Currency, Ledger, Message, UserEVaultMapping],
migrations: [path.join(__dirname, "migrations", "*.ts")],
logging: process.env.NODE_ENV === "development",
subscribers: [PostgresSubscriber],
Expand Down
5 changes: 5 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Group.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
PrimaryGeneratedColumn,
Column,
ManyToMany,
OneToMany,
JoinTable,
} from "typeorm";
import { User } from "./User";
import { Message } from "./Message";

@Entity()
export class Group {
Expand DownExpand Up@@ -68,6 +70,9 @@ export class Group {
@Column({ type: "json", nullable: true })
originalMatchParticipants!: string[]; // Store user IDs from the original match

@OneToMany(() => Message, (message) => message.group)
messages!: Message[];

@CreateDateColumn()
createdAt!: Date;

Expand Down
41 changes: 41 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Message.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
} from "typeorm";
import { User } from "./User";
import { Group } from "./Group";

@Entity("messages")
export class Message {
@PrimaryGeneratedColumn("uuid")
id!: string;

@ManyToOne(() => User, { nullable: true })
sender?: User; // Nullable for system messages

@Column("text")
text!: string;

@ManyToOne(() => Group, (group) => group.messages)
group!: Group;

@Column({ default: false })
isSystemMessage!: boolean; // Flag to identify system messages

@Column("uuid", { nullable: true })
voteId?: string; // ID of the vote/poll this system message relates to

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;

@Column({ default: false })
isArchived!: boolean;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";

@Entity("user_evault_mappings")
export class UserEVaultMapping {
@PrimaryGeneratedColumn("uuid")
id!: string;

@Column()
localUserId!: string;

@Column()
evaultW3id!: string;

@Column()
evaultUri!: string;

@Column({ nullable: true })
userProfileId!: string; // ID of the UserProfile object in the eVault

@Column({ type: "jsonb", nullable: true })
userProfileData!: any; // Store the UserProfile data
Comment thread
coodos marked this conversation as resolved.

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class Migration1765208128946 implements MigrationInterface {
name = 'Migration1765208128946'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "messages" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "text" text NOT NULL, "isSystemMessage" boolean NOT NULL DEFAULT false, "voteId" uuid, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), "isArchived" boolean NOT NULL DEFAULT false, "senderId" uuid, "groupId" uuid, CONSTRAINT "PK_18325f38ae6de43878487eff986" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE TABLE "user_evault_mappings" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "localUserId" character varying NOT NULL, "evaultW3id" character varying NOT NULL, "evaultUri" character varying NOT NULL, "userProfileId" character varying, "userProfileData" jsonb, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_744ddb4ddca6af2de54773e9213" PRIMARY KEY ("id"))`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce" FOREIGN KEY ("senderId") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e" FOREIGN KEY ("groupId") REFERENCES "group"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
Comment thread
coodos marked this conversation as resolved.
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e"`);
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce"`);
await queryRunner.query(`DROP TABLE "user_evault_mappings"`);
await queryRunner.query(`DROP TABLE "messages"`);
}

}
18 changes: 18 additions & 0 deletions platforms/eCurrency-api/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ import { CurrencyController } from "./controllers/CurrencyController";
import { LedgerController } from "./controllers/LedgerController";
import { authMiddleware, authGuard } from "./middleware/auth";
import { adapter } from "./web3adapter/watchers/subscriber";
import { PlatformEVaultService } from "./services/PlatformEVaultService";

config({ path: path.resolve(__dirname, "../../../.env") });

Expand All@@ -24,6 +25,23 @@ AppDataSource.initialize()
.then(async () => {
console.log("Database connection established");
console.log("Web3 adapter initialized");

// Initialize platform eVault for eCurrency
try {
const platformService = PlatformEVaultService.getInstance();
const exists = await platformService.checkPlatformEVaultExists();

if (!exists) {
console.log("🔧 Creating platform eVault for eCurrency...");
const result = await platformService.createPlatformEVault();
console.log(`✅ Platform eVault created successfully: ${result.w3id}`);
} else {
console.log("✅ Platform eVault already exists for eCurrency");
}
} catch (error) {
console.error("❌ Failed to initialize platform eVault:", error);
// Don't exit the process, just log the error
}
})
.catch((error: unknown) => {
console.error("Error during initialization:", error);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions platforms/eCurrency-api/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"graphql-request": "^6.1.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.11.3",
"reflect-metadata": "^0.2.1",
Expand Down
85 changes: 85 additions & 0 deletions platforms/eCurrency-api/src/controllers/WebhookController.ts
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
import { Request, Response } from "express";
import { UserService } from "../services/UserService";
import { GroupService } from "../services/GroupService";
import { MessageService } from "../services/MessageService";
import { adapter } from "../web3adapter/watchers/subscriber";
import { User } from "../database/entities/User";
import { Group } from "../database/entities/Group";
import { Message } from "../database/entities/Message";
import axios from "axios";

export class WebhookController {
userService: UserService;
groupService: GroupService;
messageService: MessageService;
adapter: typeof adapter;

constructor() {
this.userService = new UserService();
this.groupService = new GroupService();
this.messageService = new MessageService();
this.adapter = adapter;
}

Expand DownExpand Up@@ -179,6 +184,86 @@ export class WebhookController {
finalLocalId = group.id;
}
}
} else if (mapping.tableName === "messages") {
console.log("Processing message with data:", local.data);

// Extract sender and group from the message data
let sender: User | null = null;
let group: Group | null = null;

if (local.data.sender && typeof local.data.sender === "string") {
const senderId = local.data.sender.split("(")[1].split(")")[0];
sender = await this.userService.getUserById(senderId);
}

if (local.data.group && typeof local.data.group === "string") {
const groupId = local.data.group.split("(")[1].split(")")[0];
group = await this.groupService.getGroupById(groupId);
}
Comment thread
coodos marked this conversation as resolved.

// Check if this is a system message (no sender required)
const isSystemMessage = local.data.isSystemMessage === true ||
(local.data.text && typeof local.data.text === 'string' && local.data.text.startsWith('$$system-message$$'));

if (!group) {
console.error("Group not found for message");
return res.status(500).send();
}

// For system messages, sender can be null
if (!isSystemMessage && !sender) {
console.error("Sender not found for non-system message");
return res.status(500).send();
}

if (localId) {
console.log("Updating existing message with localId:", localId);
const message = await this.messageService.getMessageById(localId);
if (!message) {
console.error("Message not found for localId:", localId);
return res.status(500).send();
}

// For system messages, ensure the prefix is preserved
if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
message.sender = sender || undefined;
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
Comment on lines +227 to +235

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Potential data loss: sender field may be unintentionally cleared.

On line 233, setting message.sender = sender || undefined will set sender to undefined if the sender lookup fails, even if the message previously had a valid sender. This could unintentionally clear the sender field during updates.

Consider preserving the existing sender if lookup fails:

 if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
- message.sender = sender || undefined;+ // Only update sender if explicitly provided (preserve existing sender if lookup fails)+ if (local.data.sender) {+ message.sender = sender || undefined;+ }
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
message.sender=sender||undefined;
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
// Only update sender if explicitly provided (preserve existing sender if lookup fails)
if(local.data.sender){
message.sender=sender||undefined;
}
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
🤖 Prompt for AI Agents
In platforms/eCurrency-api/src/controllers/WebhookController.ts around lines 227
to 235, the code currently assigns message.sender = sender || undefined which
will clear an existing sender when the lookup returns a falsy value; change the
logic to only overwrite message.sender when sender is a valid value (e.g.,
non-null/defined) so that if the lookup fails the existing message.sender is
preserved, and ensure types are respected (cast or guard as needed) when
conditionally assigning.


this.adapter.addToLockedIds(localId);
await this.messageService.messageRepository.save(message);
console.log("Updated message:", message.id);
finalLocalId = message.id;
} else {
console.log("Creating new message");
let message: Message;

if (isSystemMessage) {
message = await this.messageService.createSystemMessageWithoutPrefix({
text: local.data.text as string,
groupId: group.id,
});
} else {
message = await this.messageService.createMessage({
text: local.data.text as string,
senderId: sender!.id, // We know sender exists for non-system messages
groupId: group.id,
});
}

console.log("Created message with ID:", message.id);
this.adapter.addToLockedIds(message.id);
await this.adapter.mappingDb.storeMapping({
localId: message.id,
globalId: req.body.id,
});
console.log("Stored mapping for message:", message.id, "->", req.body.id);
finalLocalId = message.id;
}
}

res.status(200).send();
Expand Down
4 changes: 3 additions & 1 deletion platforms/eCurrency-api/src/database/data-source.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,8 @@ import { User } from "./entities/User";
import { Group } from "./entities/Group";
import { Currency } from "./entities/Currency";
import { Ledger } from "./entities/Ledger";
import { Message } from "./entities/Message";
import { UserEVaultMapping } from "./entities/UserEVaultMapping";
import { PostgresSubscriber } from "../web3adapter/watchers/subscriber";

// Use absolute path for better CLI compatibility
Expand All@@ -16,7 +18,7 @@ export const dataSourceOptions: DataSourceOptions = {
type: "postgres",
url: process.env.ECURRENCY_DATABASE_URL,
synchronize: false, // Auto-sync in development
entities: [User, Group, Currency, Ledger],
entities: [User, Group, Currency, Ledger, Message, UserEVaultMapping],
migrations: [path.join(__dirname, "migrations", "*.ts")],
logging: process.env.NODE_ENV === "development",
subscribers: [PostgresSubscriber],
Expand Down
5 changes: 5 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Group.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
PrimaryGeneratedColumn,
Column,
ManyToMany,
OneToMany,
JoinTable,
} from "typeorm";
import { User } from "./User";
import { Message } from "./Message";

@Entity()
export class Group {
Expand DownExpand Up@@ -68,6 +70,9 @@ export class Group {
@Column({ type: "json", nullable: true })
originalMatchParticipants!: string[]; // Store user IDs from the original match

@OneToMany(() => Message, (message) => message.group)
messages!: Message[];

@CreateDateColumn()
createdAt!: Date;

Expand Down
41 changes: 41 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Message.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
} from "typeorm";
import { User } from "./User";
import { Group } from "./Group";

@Entity("messages")
export class Message {
@PrimaryGeneratedColumn("uuid")
id!: string;

@ManyToOne(() => User, { nullable: true })
sender?: User; // Nullable for system messages

@Column("text")
text!: string;

@ManyToOne(() => Group, (group) => group.messages)
group!: Group;

@Column({ default: false })
isSystemMessage!: boolean; // Flag to identify system messages

@Column("uuid", { nullable: true })
voteId?: string; // ID of the vote/poll this system message relates to

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;

@Column({ default: false })
isArchived!: boolean;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";

@Entity("user_evault_mappings")
export class UserEVaultMapping {
@PrimaryGeneratedColumn("uuid")
id!: string;

@Column()
localUserId!: string;

@Column()
evaultW3id!: string;

@Column()
evaultUri!: string;

@Column({ nullable: true })
userProfileId!: string; // ID of the UserProfile object in the eVault

@Column({ type: "jsonb", nullable: true })
userProfileData!: any; // Store the UserProfile data
Comment thread
coodos marked this conversation as resolved.

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class Migration1765208128946 implements MigrationInterface {
name = 'Migration1765208128946'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "messages" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "text" text NOT NULL, "isSystemMessage" boolean NOT NULL DEFAULT false, "voteId" uuid, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), "isArchived" boolean NOT NULL DEFAULT false, "senderId" uuid, "groupId" uuid, CONSTRAINT "PK_18325f38ae6de43878487eff986" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE TABLE "user_evault_mappings" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "localUserId" character varying NOT NULL, "evaultW3id" character varying NOT NULL, "evaultUri" character varying NOT NULL, "userProfileId" character varying, "userProfileData" jsonb, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_744ddb4ddca6af2de54773e9213" PRIMARY KEY ("id"))`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce" FOREIGN KEY ("senderId") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e" FOREIGN KEY ("groupId") REFERENCES "group"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
Comment thread
coodos marked this conversation as resolved.
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e"`);
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce"`);
await queryRunner.query(`DROP TABLE "user_evault_mappings"`);
await queryRunner.query(`DROP TABLE "messages"`);
}

}
18 changes: 18 additions & 0 deletions platforms/eCurrency-api/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ import { CurrencyController } from "./controllers/CurrencyController";
import { LedgerController } from "./controllers/LedgerController";
import { authMiddleware, authGuard } from "./middleware/auth";
import { adapter } from "./web3adapter/watchers/subscriber";
import { PlatformEVaultService } from "./services/PlatformEVaultService";

config({ path: path.resolve(__dirname, "../../../.env") });

Expand All@@ -24,6 +25,23 @@ AppDataSource.initialize()
.then(async () => {
console.log("Database connection established");
console.log("Web3 adapter initialized");

// Initialize platform eVault for eCurrency
try {
const platformService = PlatformEVaultService.getInstance();
const exists = await platformService.checkPlatformEVaultExists();

if (!exists) {
console.log("🔧 Creating platform eVault for eCurrency...");
const result = await platformService.createPlatformEVault();
console.log(`✅ Platform eVault created successfully: ${result.w3id}`);
} else {
console.log("✅ Platform eVault already exists for eCurrency");
}
} catch (error) {
console.error("❌ Failed to initialize platform eVault:", error);
// Don't exit the process, just log the error
}
})
.catch((error: unknown) => {
console.error("Error during initialization:", error);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions platforms/eCurrency-api/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"graphql-request": "^6.1.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.11.3",
"reflect-metadata": "^0.2.1",
Expand Down
85 changes: 85 additions & 0 deletions platforms/eCurrency-api/src/controllers/WebhookController.ts
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
import { Request, Response } from "express";
import { UserService } from "../services/UserService";
import { GroupService } from "../services/GroupService";
import { MessageService } from "../services/MessageService";
import { adapter } from "../web3adapter/watchers/subscriber";
import { User } from "../database/entities/User";
import { Group } from "../database/entities/Group";
import { Message } from "../database/entities/Message";
import axios from "axios";

export class WebhookController {
userService: UserService;
groupService: GroupService;
messageService: MessageService;
adapter: typeof adapter;

constructor() {
this.userService = new UserService();
this.groupService = new GroupService();
this.messageService = new MessageService();
this.adapter = adapter;
}

Expand DownExpand Up@@ -179,6 +184,86 @@ export class WebhookController {
finalLocalId = group.id;
}
}
} else if (mapping.tableName === "messages") {
console.log("Processing message with data:", local.data);

// Extract sender and group from the message data
let sender: User | null = null;
let group: Group | null = null;

if (local.data.sender && typeof local.data.sender === "string") {
const senderId = local.data.sender.split("(")[1].split(")")[0];
sender = await this.userService.getUserById(senderId);
}

if (local.data.group && typeof local.data.group === "string") {
const groupId = local.data.group.split("(")[1].split(")")[0];
group = await this.groupService.getGroupById(groupId);
}
Comment thread
coodos marked this conversation as resolved.

// Check if this is a system message (no sender required)
const isSystemMessage = local.data.isSystemMessage === true ||
(local.data.text && typeof local.data.text === 'string' && local.data.text.startsWith('$$system-message$$'));

if (!group) {
console.error("Group not found for message");
return res.status(500).send();
}

// For system messages, sender can be null
if (!isSystemMessage && !sender) {
console.error("Sender not found for non-system message");
return res.status(500).send();
}

if (localId) {
console.log("Updating existing message with localId:", localId);
const message = await this.messageService.getMessageById(localId);
if (!message) {
console.error("Message not found for localId:", localId);
return res.status(500).send();
}

// For system messages, ensure the prefix is preserved
if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
message.sender = sender || undefined;
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
Comment on lines +227 to +235

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Potential data loss: sender field may be unintentionally cleared.

On line 233, setting message.sender = sender || undefined will set sender to undefined if the sender lookup fails, even if the message previously had a valid sender. This could unintentionally clear the sender field during updates.

Consider preserving the existing sender if lookup fails:

 if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
- message.sender = sender || undefined;+ // Only update sender if explicitly provided (preserve existing sender if lookup fails)+ if (local.data.sender) {+ message.sender = sender || undefined;+ }
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
message.sender=sender||undefined;
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
// Only update sender if explicitly provided (preserve existing sender if lookup fails)
if(local.data.sender){
message.sender=sender||undefined;
}
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
🤖 Prompt for AI Agents
In platforms/eCurrency-api/src/controllers/WebhookController.ts around lines 227
to 235, the code currently assigns message.sender = sender || undefined which
will clear an existing sender when the lookup returns a falsy value; change the
logic to only overwrite message.sender when sender is a valid value (e.g.,
non-null/defined) so that if the lookup fails the existing message.sender is
preserved, and ensure types are respected (cast or guard as needed) when
conditionally assigning.


this.adapter.addToLockedIds(localId);
await this.messageService.messageRepository.save(message);
console.log("Updated message:", message.id);
finalLocalId = message.id;
} else {
console.log("Creating new message");
let message: Message;

if (isSystemMessage) {
message = await this.messageService.createSystemMessageWithoutPrefix({
text: local.data.text as string,
groupId: group.id,
});
} else {
message = await this.messageService.createMessage({
text: local.data.text as string,
senderId: sender!.id, // We know sender exists for non-system messages
groupId: group.id,
});
}

console.log("Created message with ID:", message.id);
this.adapter.addToLockedIds(message.id);
await this.adapter.mappingDb.storeMapping({
localId: message.id,
globalId: req.body.id,
});
console.log("Stored mapping for message:", message.id, "->", req.body.id);
finalLocalId = message.id;
}
}

res.status(200).send();
Expand Down
4 changes: 3 additions & 1 deletion platforms/eCurrency-api/src/database/data-source.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,8 @@ import { User } from "./entities/User";
import { Group } from "./entities/Group";
import { Currency } from "./entities/Currency";
import { Ledger } from "./entities/Ledger";
import { Message } from "./entities/Message";
import { UserEVaultMapping } from "./entities/UserEVaultMapping";
import { PostgresSubscriber } from "../web3adapter/watchers/subscriber";

// Use absolute path for better CLI compatibility
Expand All@@ -16,7 +18,7 @@ export const dataSourceOptions: DataSourceOptions = {
type: "postgres",
url: process.env.ECURRENCY_DATABASE_URL,
synchronize: false, // Auto-sync in development
entities: [User, Group, Currency, Ledger],
entities: [User, Group, Currency, Ledger, Message, UserEVaultMapping],
migrations: [path.join(__dirname, "migrations", "*.ts")],
logging: process.env.NODE_ENV === "development",
subscribers: [PostgresSubscriber],
Expand Down
5 changes: 5 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Group.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
PrimaryGeneratedColumn,
Column,
ManyToMany,
OneToMany,
JoinTable,
} from "typeorm";
import { User } from "./User";
import { Message } from "./Message";

@Entity()
export class Group {
Expand DownExpand Up@@ -68,6 +70,9 @@ export class Group {
@Column({ type: "json", nullable: true })
originalMatchParticipants!: string[]; // Store user IDs from the original match

@OneToMany(() => Message, (message) => message.group)
messages!: Message[];

@CreateDateColumn()
createdAt!: Date;

Expand Down
41 changes: 41 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Message.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
} from "typeorm";
import { User } from "./User";
import { Group } from "./Group";

@Entity("messages")
export class Message {
@PrimaryGeneratedColumn("uuid")
id!: string;

@ManyToOne(() => User, { nullable: true })
sender?: User; // Nullable for system messages

@Column("text")
text!: string;

@ManyToOne(() => Group, (group) => group.messages)
group!: Group;

@Column({ default: false })
isSystemMessage!: boolean; // Flag to identify system messages

@Column("uuid", { nullable: true })
voteId?: string; // ID of the vote/poll this system message relates to

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;

@Column({ default: false })
isArchived!: boolean;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";

@Entity("user_evault_mappings")
export class UserEVaultMapping {
@PrimaryGeneratedColumn("uuid")
id!: string;

@Column()
localUserId!: string;

@Column()
evaultW3id!: string;

@Column()
evaultUri!: string;

@Column({ nullable: true })
userProfileId!: string; // ID of the UserProfile object in the eVault

@Column({ type: "jsonb", nullable: true })
userProfileData!: any; // Store the UserProfile data
Comment thread
coodos marked this conversation as resolved.

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class Migration1765208128946 implements MigrationInterface {
name = 'Migration1765208128946'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "messages" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "text" text NOT NULL, "isSystemMessage" boolean NOT NULL DEFAULT false, "voteId" uuid, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), "isArchived" boolean NOT NULL DEFAULT false, "senderId" uuid, "groupId" uuid, CONSTRAINT "PK_18325f38ae6de43878487eff986" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE TABLE "user_evault_mappings" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "localUserId" character varying NOT NULL, "evaultW3id" character varying NOT NULL, "evaultUri" character varying NOT NULL, "userProfileId" character varying, "userProfileData" jsonb, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_744ddb4ddca6af2de54773e9213" PRIMARY KEY ("id"))`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce" FOREIGN KEY ("senderId") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e" FOREIGN KEY ("groupId") REFERENCES "group"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
Comment thread
coodos marked this conversation as resolved.
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e"`);
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce"`);
await queryRunner.query(`DROP TABLE "user_evault_mappings"`);
await queryRunner.query(`DROP TABLE "messages"`);
}

}
18 changes: 18 additions & 0 deletions platforms/eCurrency-api/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ import { CurrencyController } from "./controllers/CurrencyController";
import { LedgerController } from "./controllers/LedgerController";
import { authMiddleware, authGuard } from "./middleware/auth";
import { adapter } from "./web3adapter/watchers/subscriber";
import { PlatformEVaultService } from "./services/PlatformEVaultService";

config({ path: path.resolve(__dirname, "../../../.env") });

Expand All@@ -24,6 +25,23 @@ AppDataSource.initialize()
.then(async () => {
console.log("Database connection established");
console.log("Web3 adapter initialized");

// Initialize platform eVault for eCurrency
try {
const platformService = PlatformEVaultService.getInstance();
const exists = await platformService.checkPlatformEVaultExists();

if (!exists) {
console.log("🔧 Creating platform eVault for eCurrency...");
const result = await platformService.createPlatformEVault();
console.log(`✅ Platform eVault created successfully: ${result.w3id}`);
} else {
console.log("✅ Platform eVault already exists for eCurrency");
}
} catch (error) {
console.error("❌ Failed to initialize platform eVault:", error);
// Don't exit the process, just log the error
}
})
.catch((error: unknown) => {
console.error("Error during initialization:", error);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions platforms/eCurrency-api/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"graphql-request": "^6.1.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.11.3",
"reflect-metadata": "^0.2.1",
Expand Down
85 changes: 85 additions & 0 deletions platforms/eCurrency-api/src/controllers/WebhookController.ts
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
import { Request, Response } from "express";
import { UserService } from "../services/UserService";
import { GroupService } from "../services/GroupService";
import { MessageService } from "../services/MessageService";
import { adapter } from "../web3adapter/watchers/subscriber";
import { User } from "../database/entities/User";
import { Group } from "../database/entities/Group";
import { Message } from "../database/entities/Message";
import axios from "axios";

export class WebhookController {
userService: UserService;
groupService: GroupService;
messageService: MessageService;
adapter: typeof adapter;

constructor() {
this.userService = new UserService();
this.groupService = new GroupService();
this.messageService = new MessageService();
this.adapter = adapter;
}

Expand DownExpand Up@@ -179,6 +184,86 @@ export class WebhookController {
finalLocalId = group.id;
}
}
} else if (mapping.tableName === "messages") {
console.log("Processing message with data:", local.data);

// Extract sender and group from the message data
let sender: User | null = null;
let group: Group | null = null;

if (local.data.sender && typeof local.data.sender === "string") {
const senderId = local.data.sender.split("(")[1].split(")")[0];
sender = await this.userService.getUserById(senderId);
}

if (local.data.group && typeof local.data.group === "string") {
const groupId = local.data.group.split("(")[1].split(")")[0];
group = await this.groupService.getGroupById(groupId);
}
Comment thread
coodos marked this conversation as resolved.

// Check if this is a system message (no sender required)
const isSystemMessage = local.data.isSystemMessage === true ||
(local.data.text && typeof local.data.text === 'string' && local.data.text.startsWith('$$system-message$$'));

if (!group) {
console.error("Group not found for message");
return res.status(500).send();
}

// For system messages, sender can be null
if (!isSystemMessage && !sender) {
console.error("Sender not found for non-system message");
return res.status(500).send();
}

if (localId) {
console.log("Updating existing message with localId:", localId);
const message = await this.messageService.getMessageById(localId);
if (!message) {
console.error("Message not found for localId:", localId);
return res.status(500).send();
}

// For system messages, ensure the prefix is preserved
if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
message.sender = sender || undefined;
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
Comment on lines +227 to +235

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Potential data loss: sender field may be unintentionally cleared.

On line 233, setting message.sender = sender || undefined will set sender to undefined if the sender lookup fails, even if the message previously had a valid sender. This could unintentionally clear the sender field during updates.

Consider preserving the existing sender if lookup fails:

 if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
- message.sender = sender || undefined;+ // Only update sender if explicitly provided (preserve existing sender if lookup fails)+ if (local.data.sender) {+ message.sender = sender || undefined;+ }
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
message.sender=sender||undefined;
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
// Only update sender if explicitly provided (preserve existing sender if lookup fails)
if(local.data.sender){
message.sender=sender||undefined;
}
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
🤖 Prompt for AI Agents
In platforms/eCurrency-api/src/controllers/WebhookController.ts around lines 227
to 235, the code currently assigns message.sender = sender || undefined which
will clear an existing sender when the lookup returns a falsy value; change the
logic to only overwrite message.sender when sender is a valid value (e.g.,
non-null/defined) so that if the lookup fails the existing message.sender is
preserved, and ensure types are respected (cast or guard as needed) when
conditionally assigning.


this.adapter.addToLockedIds(localId);
await this.messageService.messageRepository.save(message);
console.log("Updated message:", message.id);
finalLocalId = message.id;
} else {
console.log("Creating new message");
let message: Message;

if (isSystemMessage) {
message = await this.messageService.createSystemMessageWithoutPrefix({
text: local.data.text as string,
groupId: group.id,
});
} else {
message = await this.messageService.createMessage({
text: local.data.text as string,
senderId: sender!.id, // We know sender exists for non-system messages
groupId: group.id,
});
}

console.log("Created message with ID:", message.id);
this.adapter.addToLockedIds(message.id);
await this.adapter.mappingDb.storeMapping({
localId: message.id,
globalId: req.body.id,
});
console.log("Stored mapping for message:", message.id, "->", req.body.id);
finalLocalId = message.id;
}
}

res.status(200).send();
Expand Down
4 changes: 3 additions & 1 deletion platforms/eCurrency-api/src/database/data-source.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,8 @@ import { User } from "./entities/User";
import { Group } from "./entities/Group";
import { Currency } from "./entities/Currency";
import { Ledger } from "./entities/Ledger";
import { Message } from "./entities/Message";
import { UserEVaultMapping } from "./entities/UserEVaultMapping";
import { PostgresSubscriber } from "../web3adapter/watchers/subscriber";

// Use absolute path for better CLI compatibility
Expand All@@ -16,7 +18,7 @@ export const dataSourceOptions: DataSourceOptions = {
type: "postgres",
url: process.env.ECURRENCY_DATABASE_URL,
synchronize: false, // Auto-sync in development
entities: [User, Group, Currency, Ledger],
entities: [User, Group, Currency, Ledger, Message, UserEVaultMapping],
migrations: [path.join(__dirname, "migrations", "*.ts")],
logging: process.env.NODE_ENV === "development",
subscribers: [PostgresSubscriber],
Expand Down
5 changes: 5 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Group.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
PrimaryGeneratedColumn,
Column,
ManyToMany,
OneToMany,
JoinTable,
} from "typeorm";
import { User } from "./User";
import { Message } from "./Message";

@Entity()
export class Group {
Expand DownExpand Up@@ -68,6 +70,9 @@ export class Group {
@Column({ type: "json", nullable: true })
originalMatchParticipants!: string[]; // Store user IDs from the original match

@OneToMany(() => Message, (message) => message.group)
messages!: Message[];

@CreateDateColumn()
createdAt!: Date;

Expand Down
41 changes: 41 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Message.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
} from "typeorm";
import { User } from "./User";
import { Group } from "./Group";

@Entity("messages")
export class Message {
@PrimaryGeneratedColumn("uuid")
id!: string;

@ManyToOne(() => User, { nullable: true })
sender?: User; // Nullable for system messages

@Column("text")
text!: string;

@ManyToOne(() => Group, (group) => group.messages)
group!: Group;

@Column({ default: false })
isSystemMessage!: boolean; // Flag to identify system messages

@Column("uuid", { nullable: true })
voteId?: string; // ID of the vote/poll this system message relates to

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;

@Column({ default: false })
isArchived!: boolean;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";

@Entity("user_evault_mappings")
export class UserEVaultMapping {
@PrimaryGeneratedColumn("uuid")
id!: string;

@Column()
localUserId!: string;

@Column()
evaultW3id!: string;

@Column()
evaultUri!: string;

@Column({ nullable: true })
userProfileId!: string; // ID of the UserProfile object in the eVault

@Column({ type: "jsonb", nullable: true })
userProfileData!: any; // Store the UserProfile data
Comment thread
coodos marked this conversation as resolved.

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class Migration1765208128946 implements MigrationInterface {
name = 'Migration1765208128946'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "messages" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "text" text NOT NULL, "isSystemMessage" boolean NOT NULL DEFAULT false, "voteId" uuid, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), "isArchived" boolean NOT NULL DEFAULT false, "senderId" uuid, "groupId" uuid, CONSTRAINT "PK_18325f38ae6de43878487eff986" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE TABLE "user_evault_mappings" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "localUserId" character varying NOT NULL, "evaultW3id" character varying NOT NULL, "evaultUri" character varying NOT NULL, "userProfileId" character varying, "userProfileData" jsonb, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_744ddb4ddca6af2de54773e9213" PRIMARY KEY ("id"))`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce" FOREIGN KEY ("senderId") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e" FOREIGN KEY ("groupId") REFERENCES "group"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
Comment thread
coodos marked this conversation as resolved.
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e"`);
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce"`);
await queryRunner.query(`DROP TABLE "user_evault_mappings"`);
await queryRunner.query(`DROP TABLE "messages"`);
}

}
18 changes: 18 additions & 0 deletions platforms/eCurrency-api/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ import { CurrencyController } from "./controllers/CurrencyController";
import { LedgerController } from "./controllers/LedgerController";
import { authMiddleware, authGuard } from "./middleware/auth";
import { adapter } from "./web3adapter/watchers/subscriber";
import { PlatformEVaultService } from "./services/PlatformEVaultService";

config({ path: path.resolve(__dirname, "../../../.env") });

Expand All@@ -24,6 +25,23 @@ AppDataSource.initialize()
.then(async () => {
console.log("Database connection established");
console.log("Web3 adapter initialized");

// Initialize platform eVault for eCurrency
try {
const platformService = PlatformEVaultService.getInstance();
const exists = await platformService.checkPlatformEVaultExists();

if (!exists) {
console.log("🔧 Creating platform eVault for eCurrency...");
const result = await platformService.createPlatformEVault();
console.log(`✅ Platform eVault created successfully: ${result.w3id}`);
} else {
console.log("✅ Platform eVault already exists for eCurrency");
}
} catch (error) {
console.error("❌ Failed to initialize platform eVault:", error);
// Don't exit the process, just log the error
}
})
.catch((error: unknown) => {
console.error("Error during initialization:", error);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions platforms/eCurrency-api/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"graphql-request": "^6.1.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.11.3",
"reflect-metadata": "^0.2.1",
Expand Down
85 changes: 85 additions & 0 deletions platforms/eCurrency-api/src/controllers/WebhookController.ts
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
import { Request, Response } from "express";
import { UserService } from "../services/UserService";
import { GroupService } from "../services/GroupService";
import { MessageService } from "../services/MessageService";
import { adapter } from "../web3adapter/watchers/subscriber";
import { User } from "../database/entities/User";
import { Group } from "../database/entities/Group";
import { Message } from "../database/entities/Message";
import axios from "axios";

export class WebhookController {
userService: UserService;
groupService: GroupService;
messageService: MessageService;
adapter: typeof adapter;

constructor() {
this.userService = new UserService();
this.groupService = new GroupService();
this.messageService = new MessageService();
this.adapter = adapter;
}

Expand DownExpand Up@@ -179,6 +184,86 @@ export class WebhookController {
finalLocalId = group.id;
}
}
} else if (mapping.tableName === "messages") {
console.log("Processing message with data:", local.data);

// Extract sender and group from the message data
let sender: User | null = null;
let group: Group | null = null;

if (local.data.sender && typeof local.data.sender === "string") {
const senderId = local.data.sender.split("(")[1].split(")")[0];
sender = await this.userService.getUserById(senderId);
}

if (local.data.group && typeof local.data.group === "string") {
const groupId = local.data.group.split("(")[1].split(")")[0];
group = await this.groupService.getGroupById(groupId);
}
Comment thread
coodos marked this conversation as resolved.

// Check if this is a system message (no sender required)
const isSystemMessage = local.data.isSystemMessage === true ||
(local.data.text && typeof local.data.text === 'string' && local.data.text.startsWith('$$system-message$$'));

if (!group) {
console.error("Group not found for message");
return res.status(500).send();
}

// For system messages, sender can be null
if (!isSystemMessage && !sender) {
console.error("Sender not found for non-system message");
return res.status(500).send();
}

if (localId) {
console.log("Updating existing message with localId:", localId);
const message = await this.messageService.getMessageById(localId);
if (!message) {
console.error("Message not found for localId:", localId);
return res.status(500).send();
}

// For system messages, ensure the prefix is preserved
if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
message.sender = sender || undefined;
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
Comment on lines +227 to +235

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Potential data loss: sender field may be unintentionally cleared.

On line 233, setting message.sender = sender || undefined will set sender to undefined if the sender lookup fails, even if the message previously had a valid sender. This could unintentionally clear the sender field during updates.

Consider preserving the existing sender if lookup fails:

 if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
- message.sender = sender || undefined;+ // Only update sender if explicitly provided (preserve existing sender if lookup fails)+ if (local.data.sender) {+ message.sender = sender || undefined;+ }
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
message.sender=sender||undefined;
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
// Only update sender if explicitly provided (preserve existing sender if lookup fails)
if(local.data.sender){
message.sender=sender||undefined;
}
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
🤖 Prompt for AI Agents
In platforms/eCurrency-api/src/controllers/WebhookController.ts around lines 227
to 235, the code currently assigns message.sender = sender || undefined which
will clear an existing sender when the lookup returns a falsy value; change the
logic to only overwrite message.sender when sender is a valid value (e.g.,
non-null/defined) so that if the lookup fails the existing message.sender is
preserved, and ensure types are respected (cast or guard as needed) when
conditionally assigning.


this.adapter.addToLockedIds(localId);
await this.messageService.messageRepository.save(message);
console.log("Updated message:", message.id);
finalLocalId = message.id;
} else {
console.log("Creating new message");
let message: Message;

if (isSystemMessage) {
message = await this.messageService.createSystemMessageWithoutPrefix({
text: local.data.text as string,
groupId: group.id,
});
} else {
message = await this.messageService.createMessage({
text: local.data.text as string,
senderId: sender!.id, // We know sender exists for non-system messages
groupId: group.id,
});
}

console.log("Created message with ID:", message.id);
this.adapter.addToLockedIds(message.id);
await this.adapter.mappingDb.storeMapping({
localId: message.id,
globalId: req.body.id,
});
console.log("Stored mapping for message:", message.id, "->", req.body.id);
finalLocalId = message.id;
}
}

res.status(200).send();
Expand Down
4 changes: 3 additions & 1 deletion platforms/eCurrency-api/src/database/data-source.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,8 @@ import { User } from "./entities/User";
import { Group } from "./entities/Group";
import { Currency } from "./entities/Currency";
import { Ledger } from "./entities/Ledger";
import { Message } from "./entities/Message";
import { UserEVaultMapping } from "./entities/UserEVaultMapping";
import { PostgresSubscriber } from "../web3adapter/watchers/subscriber";

// Use absolute path for better CLI compatibility
Expand All@@ -16,7 +18,7 @@ export const dataSourceOptions: DataSourceOptions = {
type: "postgres",
url: process.env.ECURRENCY_DATABASE_URL,
synchronize: false, // Auto-sync in development
entities: [User, Group, Currency, Ledger],
entities: [User, Group, Currency, Ledger, Message, UserEVaultMapping],
migrations: [path.join(__dirname, "migrations", "*.ts")],
logging: process.env.NODE_ENV === "development",
subscribers: [PostgresSubscriber],
Expand Down
5 changes: 5 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Group.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
PrimaryGeneratedColumn,
Column,
ManyToMany,
OneToMany,
JoinTable,
} from "typeorm";
import { User } from "./User";
import { Message } from "./Message";

@Entity()
export class Group {
Expand DownExpand Up@@ -68,6 +70,9 @@ export class Group {
@Column({ type: "json", nullable: true })
originalMatchParticipants!: string[]; // Store user IDs from the original match

@OneToMany(() => Message, (message) => message.group)
messages!: Message[];

@CreateDateColumn()
createdAt!: Date;

Expand Down
41 changes: 41 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Message.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
} from "typeorm";
import { User } from "./User";
import { Group } from "./Group";

@Entity("messages")
export class Message {
@PrimaryGeneratedColumn("uuid")
id!: string;

@ManyToOne(() => User, { nullable: true })
sender?: User; // Nullable for system messages

@Column("text")
text!: string;

@ManyToOne(() => Group, (group) => group.messages)
group!: Group;

@Column({ default: false })
isSystemMessage!: boolean; // Flag to identify system messages

@Column("uuid", { nullable: true })
voteId?: string; // ID of the vote/poll this system message relates to

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;

@Column({ default: false })
isArchived!: boolean;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";

@Entity("user_evault_mappings")
export class UserEVaultMapping {
@PrimaryGeneratedColumn("uuid")
id!: string;

@Column()
localUserId!: string;

@Column()
evaultW3id!: string;

@Column()
evaultUri!: string;

@Column({ nullable: true })
userProfileId!: string; // ID of the UserProfile object in the eVault

@Column({ type: "jsonb", nullable: true })
userProfileData!: any; // Store the UserProfile data
Comment thread
coodos marked this conversation as resolved.

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class Migration1765208128946 implements MigrationInterface {
name = 'Migration1765208128946'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "messages" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "text" text NOT NULL, "isSystemMessage" boolean NOT NULL DEFAULT false, "voteId" uuid, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), "isArchived" boolean NOT NULL DEFAULT false, "senderId" uuid, "groupId" uuid, CONSTRAINT "PK_18325f38ae6de43878487eff986" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE TABLE "user_evault_mappings" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "localUserId" character varying NOT NULL, "evaultW3id" character varying NOT NULL, "evaultUri" character varying NOT NULL, "userProfileId" character varying, "userProfileData" jsonb, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_744ddb4ddca6af2de54773e9213" PRIMARY KEY ("id"))`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce" FOREIGN KEY ("senderId") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e" FOREIGN KEY ("groupId") REFERENCES "group"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
Comment thread
coodos marked this conversation as resolved.
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e"`);
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce"`);
await queryRunner.query(`DROP TABLE "user_evault_mappings"`);
await queryRunner.query(`DROP TABLE "messages"`);
}

}
18 changes: 18 additions & 0 deletions platforms/eCurrency-api/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ import { CurrencyController } from "./controllers/CurrencyController";
import { LedgerController } from "./controllers/LedgerController";
import { authMiddleware, authGuard } from "./middleware/auth";
import { adapter } from "./web3adapter/watchers/subscriber";
import { PlatformEVaultService } from "./services/PlatformEVaultService";

config({ path: path.resolve(__dirname, "../../../.env") });

Expand All@@ -24,6 +25,23 @@ AppDataSource.initialize()
.then(async () => {
console.log("Database connection established");
console.log("Web3 adapter initialized");

// Initialize platform eVault for eCurrency
try {
const platformService = PlatformEVaultService.getInstance();
const exists = await platformService.checkPlatformEVaultExists();

if (!exists) {
console.log("🔧 Creating platform eVault for eCurrency...");
const result = await platformService.createPlatformEVault();
console.log(`✅ Platform eVault created successfully: ${result.w3id}`);
} else {
console.log("✅ Platform eVault already exists for eCurrency");
}
} catch (error) {
console.error("❌ Failed to initialize platform eVault:", error);
// Don't exit the process, just log the error
}
})
.catch((error: unknown) => {
console.error("Error during initialization:", error);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions platforms/eCurrency-api/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,6 +17,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"graphql-request": "^6.1.0",
"jsonwebtoken": "^9.0.2",
"pg": "^8.11.3",
"reflect-metadata": "^0.2.1",
Expand Down
85 changes: 85 additions & 0 deletions platforms/eCurrency-api/src/controllers/WebhookController.ts
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
import { Request, Response } from "express";
import { UserService } from "../services/UserService";
import { GroupService } from "../services/GroupService";
import { MessageService } from "../services/MessageService";
import { adapter } from "../web3adapter/watchers/subscriber";
import { User } from "../database/entities/User";
import { Group } from "../database/entities/Group";
import { Message } from "../database/entities/Message";
import axios from "axios";

export class WebhookController {
userService: UserService;
groupService: GroupService;
messageService: MessageService;
adapter: typeof adapter;

constructor() {
this.userService = new UserService();
this.groupService = new GroupService();
this.messageService = new MessageService();
this.adapter = adapter;
}

Expand DownExpand Up@@ -179,6 +184,86 @@ export class WebhookController {
finalLocalId = group.id;
}
}
} else if (mapping.tableName === "messages") {
console.log("Processing message with data:", local.data);

// Extract sender and group from the message data
let sender: User | null = null;
let group: Group | null = null;

if (local.data.sender && typeof local.data.sender === "string") {
const senderId = local.data.sender.split("(")[1].split(")")[0];
sender = await this.userService.getUserById(senderId);
}

if (local.data.group && typeof local.data.group === "string") {
const groupId = local.data.group.split("(")[1].split(")")[0];
group = await this.groupService.getGroupById(groupId);
}
Comment thread
coodos marked this conversation as resolved.

// Check if this is a system message (no sender required)
const isSystemMessage = local.data.isSystemMessage === true ||
(local.data.text && typeof local.data.text === 'string' && local.data.text.startsWith('$$system-message$$'));

if (!group) {
console.error("Group not found for message");
return res.status(500).send();
}

// For system messages, sender can be null
if (!isSystemMessage && !sender) {
console.error("Sender not found for non-system message");
return res.status(500).send();
}

if (localId) {
console.log("Updating existing message with localId:", localId);
const message = await this.messageService.getMessageById(localId);
if (!message) {
console.error("Message not found for localId:", localId);
return res.status(500).send();
}

// For system messages, ensure the prefix is preserved
if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
message.sender = sender || undefined;
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
Comment on lines +227 to +235

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Potential data loss: sender field may be unintentionally cleared.

On line 233, setting message.sender = sender || undefined will set sender to undefined if the sender lookup fails, even if the message previously had a valid sender. This could unintentionally clear the sender field during updates.

Consider preserving the existing sender if lookup fails:

 if (isSystemMessage && !(local.data.text as string).startsWith('$$system-message$$')) {
message.text = `$$system-message$$ ${local.data.text as string}`;
} else {
message.text = local.data.text as string;
}
- message.sender = sender || undefined;+ // Only update sender if explicitly provided (preserve existing sender if lookup fails)+ if (local.data.sender) {+ message.sender = sender || undefined;+ }
message.group = group;
message.isSystemMessage = isSystemMessage as boolean;
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
message.sender=sender||undefined;
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
// For system messages, ensure the prefix is preserved
if(isSystemMessage&&!(local.data.textasstring).startsWith('$$system-message$$')){
message.text=`$$system-message$$ ${local.data.textasstring}`;
}else{
message.text=local.data.textasstring;
}
// Only update sender if explicitly provided (preserve existing sender if lookup fails)
if(local.data.sender){
message.sender=sender||undefined;
}
message.group=group;
message.isSystemMessage=isSystemMessageasboolean;
🤖 Prompt for AI Agents
In platforms/eCurrency-api/src/controllers/WebhookController.ts around lines 227
to 235, the code currently assigns message.sender = sender || undefined which
will clear an existing sender when the lookup returns a falsy value; change the
logic to only overwrite message.sender when sender is a valid value (e.g.,
non-null/defined) so that if the lookup fails the existing message.sender is
preserved, and ensure types are respected (cast or guard as needed) when
conditionally assigning.


this.adapter.addToLockedIds(localId);
await this.messageService.messageRepository.save(message);
console.log("Updated message:", message.id);
finalLocalId = message.id;
} else {
console.log("Creating new message");
let message: Message;

if (isSystemMessage) {
message = await this.messageService.createSystemMessageWithoutPrefix({
text: local.data.text as string,
groupId: group.id,
});
} else {
message = await this.messageService.createMessage({
text: local.data.text as string,
senderId: sender!.id, // We know sender exists for non-system messages
groupId: group.id,
});
}

console.log("Created message with ID:", message.id);
this.adapter.addToLockedIds(message.id);
await this.adapter.mappingDb.storeMapping({
localId: message.id,
globalId: req.body.id,
});
console.log("Stored mapping for message:", message.id, "->", req.body.id);
finalLocalId = message.id;
}
}

res.status(200).send();
Expand Down
4 changes: 3 additions & 1 deletion platforms/eCurrency-api/src/database/data-source.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,8 @@ import { User } from "./entities/User";
import { Group } from "./entities/Group";
import { Currency } from "./entities/Currency";
import { Ledger } from "./entities/Ledger";
import { Message } from "./entities/Message";
import { UserEVaultMapping } from "./entities/UserEVaultMapping";
import { PostgresSubscriber } from "../web3adapter/watchers/subscriber";

// Use absolute path for better CLI compatibility
Expand All@@ -16,7 +18,7 @@ export const dataSourceOptions: DataSourceOptions = {
type: "postgres",
url: process.env.ECURRENCY_DATABASE_URL,
synchronize: false, // Auto-sync in development
entities: [User, Group, Currency, Ledger],
entities: [User, Group, Currency, Ledger, Message, UserEVaultMapping],
migrations: [path.join(__dirname, "migrations", "*.ts")],
logging: process.env.NODE_ENV === "development",
subscribers: [PostgresSubscriber],
Expand Down
5 changes: 5 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Group.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,11 @@ import {
PrimaryGeneratedColumn,
Column,
ManyToMany,
OneToMany,
JoinTable,
} from "typeorm";
import { User } from "./User";
import { Message } from "./Message";

@Entity()
export class Group {
Expand DownExpand Up@@ -68,6 +70,9 @@ export class Group {
@Column({ type: "json", nullable: true })
originalMatchParticipants!: string[]; // Store user IDs from the original match

@OneToMany(() => Message, (message) => message.group)
messages!: Message[];

@CreateDateColumn()
createdAt!: Date;

Expand Down
41 changes: 41 additions & 0 deletions platforms/eCurrency-api/src/database/entities/Message.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
} from "typeorm";
import { User } from "./User";
import { Group } from "./Group";

@Entity("messages")
export class Message {
@PrimaryGeneratedColumn("uuid")
id!: string;

@ManyToOne(() => User, { nullable: true })
sender?: User; // Nullable for system messages

@Column("text")
text!: string;

@ManyToOne(() => Group, (group) => group.messages)
group!: Group;

@Column({ default: false })
isSystemMessage!: boolean; // Flag to identify system messages

@Column("uuid", { nullable: true })
voteId?: string; // ID of the vote/poll this system message relates to

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;

@Column({ default: false })
isArchived!: boolean;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";

@Entity("user_evault_mappings")
export class UserEVaultMapping {
@PrimaryGeneratedColumn("uuid")
id!: string;

@Column()
localUserId!: string;

@Column()
evaultW3id!: string;

@Column()
evaultUri!: string;

@Column({ nullable: true })
userProfileId!: string; // ID of the UserProfile object in the eVault

@Column({ type: "jsonb", nullable: true })
userProfileData!: any; // Store the UserProfile data
Comment thread
coodos marked this conversation as resolved.

@CreateDateColumn()
createdAt!: Date;

@UpdateDateColumn()
updatedAt!: Date;
}

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class Migration1765208128946 implements MigrationInterface {
name = 'Migration1765208128946'

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "messages" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "text" text NOT NULL, "isSystemMessage" boolean NOT NULL DEFAULT false, "voteId" uuid, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), "isArchived" boolean NOT NULL DEFAULT false, "senderId" uuid, "groupId" uuid, CONSTRAINT "PK_18325f38ae6de43878487eff986" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE TABLE "user_evault_mappings" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "localUserId" character varying NOT NULL, "evaultW3id" character varying NOT NULL, "evaultUri" character varying NOT NULL, "userProfileId" character varying, "userProfileData" jsonb, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_744ddb4ddca6af2de54773e9213" PRIMARY KEY ("id"))`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce" FOREIGN KEY ("senderId") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "messages" ADD CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e" FOREIGN KEY ("groupId") REFERENCES "group"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
Comment thread
coodos marked this conversation as resolved.
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_438f09ab5b4bbcd27683eac2a5e"`);
await queryRunner.query(`ALTER TABLE "messages" DROP CONSTRAINT "FK_2db9cf2b3ca111742793f6c37ce"`);
await queryRunner.query(`DROP TABLE "user_evault_mappings"`);
await queryRunner.query(`DROP TABLE "messages"`);
}

}
18 changes: 18 additions & 0 deletions platforms/eCurrency-api/src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ import { CurrencyController } from "./controllers/CurrencyController";
import { LedgerController } from "./controllers/LedgerController";
import { authMiddleware, authGuard } from "./middleware/auth";
import { adapter } from "./web3adapter/watchers/subscriber";
import { PlatformEVaultService } from "./services/PlatformEVaultService";

config({ path: path.resolve(__dirname, "../../../.env") });

Expand All@@ -24,6 +25,23 @@ AppDataSource.initialize()
.then(async () => {
console.log("Database connection established");
console.log("Web3 adapter initialized");

// Initialize platform eVault for eCurrency
try {
const platformService = PlatformEVaultService.getInstance();
const exists = await platformService.checkPlatformEVaultExists();

if (!exists) {
console.log("🔧 Creating platform eVault for eCurrency...");
const result = await platformService.createPlatformEVault();
console.log(`✅ Platform eVault created successfully: ${result.w3id}`);
} else {
console.log("✅ Platform eVault already exists for eCurrency");
}
} catch (error) {
console.error("❌ Failed to initialize platform eVault:", error);
// Don't exit the process, just log the error
}
})
.catch((error: unknown) => {
console.error("Error during initialization:", error);
Expand Down
Loading