Skip to content

Commit

Permalink
Merge pull request #10658 from hicommonwealth/rotorsoft/fix-referrals…
Browse files Browse the repository at this point in the history
…-with-new-event-attributes

Fixes referrals flow with new event attributes
  • Loading branch information
Rotorsoft authored Jan 22, 2025
2 parents c779b01 + 3e94f16 commit 321857f
Show file tree
Hide file tree
Showing 33 changed files with 497 additions and 197 deletions.
2 changes: 1 addition & 1 deletion libs/adapters/src/rabbitmq/configuration/rascalConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ export function getAllRascalConfigs(
source: RascalExchanges.MessageRelayer,
destination: RascalQueues.UserReferrals,
destinationType: 'queue',
bindingKeys: [RascalRoutingKeys.UserReferralsCommunityJoined],
bindingKeys: [RascalRoutingKeys.UserReferralsCommunityCreated],
},
[RascalBindings.FarcasterWorkerPolicy]: {
source: RascalExchanges.MessageRelayer,
Expand Down
2 changes: 1 addition & 1 deletion libs/adapters/src/rabbitmq/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export enum RascalRoutingKeys {
XpProjectionCommentUpvoted = EventNames.CommentUpvoted,
XpProjectionUserMentioned = EventNames.UserMentioned,

UserReferralsCommunityJoined = EventNames.CommunityJoined,
UserReferralsCommunityCreated = EventNames.CommunityCreated,

FarcasterWorkerPolicyCastCreated = EventNames.FarcasterCastCreated,
FarcasterWorkerPolicyReplyCastCreated = EventNames.FarcasterReplyCastCreated,
Expand Down
2 changes: 1 addition & 1 deletion libs/core/src/framework/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const command = async <
try {
const context: Context<Input, _Context> = {
actor,
payload: validate ? input.parse(payload) : payload,
payload: validate ? await input.parseAsync(payload) : payload,
};
for (const fn of auth) {
await fn(context);
Expand Down
43 changes: 43 additions & 0 deletions libs/evm-protocols/src/abis/namespaceFactoryAbi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,49 @@ export const namespaceFactoryAbi = [
name: 'DeployedNamespace',
type: 'event',
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: 'address',
name: 'namespaceAdress',
type: 'address',
},
{
indexed: true,
internalType: 'address',
name: 'feeManager',
type: 'address',
},
{
indexed: true,
internalType: 'address',
name: 'referrer',
type: 'address',
},
{
indexed: false,
internalType: 'address',
name: 'referralFeeManager',
type: 'address',
},
{
indexed: false,
internalType: 'bytes',
name: 'signature',
type: 'bytes',
},
{
indexed: false,
internalType: 'address',
name: 'namespaceDeployer',
type: 'address',
},
],
name: 'DeployedNamespaceWithReferral',
type: 'event',
},
{
anonymous: false,
inputs: [
Expand Down
1 change: 1 addition & 0 deletions libs/evm-protocols/src/event-registry/eventRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ const namespaceFactorySource = {
eventSignatures: [
EvmEventSignatures.NamespaceFactory.ContestManagerDeployed,
EvmEventSignatures.NamespaceFactory.NamespaceDeployed,
EvmEventSignatures.NamespaceFactory.NamespaceDeployedWithReferral,
],
childContracts: {
[ChildContractNames.RecurringContest]: {
Expand Down
2 changes: 2 additions & 0 deletions libs/evm-protocols/src/event-registry/eventSignatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export const EvmEventSignatures = {
NamespaceFactory: {
NamespaceDeployed:
'0x8870ba2202802ce285ce6bead5ac915b6dc2d35c8a9d6f96fa56de9de12829d5',
NamespaceDeployedWithReferral:
'0x2f5d04158abd2b403eb3b099bf1257e7949197015ef7d19db38b2c45f9e0d164',
ContestManagerDeployed:
'0x990f533044dbc89b838acde9cd2c72c400999871cf8f792d731edcae15ead693',
CommunityNamespaceCreated:
Expand Down
12 changes: 9 additions & 3 deletions libs/model/src/community/CreateCommunity.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,12 @@ export function CreateCommunity(): Command<typeof schemas.CreateCommunity> {
else if (base === ChainBase.CosmosSDK && !node.cosmos_chain_id)
throw new InvalidInput(CreateCommunityErrors.CosmosChainNameRequired);

const user = await models.User.findOne({
where: { id: actor.user.id },
attributes: ['id', 'referred_by_address'],
});
mustExist('User', user);

// == command transaction boundary ==
await models.sequelize.transaction(async (transaction) => {
await models.Community.create(
Expand Down Expand Up @@ -148,7 +154,7 @@ export function CreateCommunity(): Command<typeof schemas.CreateCommunity> {

const created = await models.Address.create(
{
user_id: actor.user.id,
user_id: user.id,
address: admin_address.address,
community_id: id,
hex:
Expand Down Expand Up @@ -176,8 +182,8 @@ export function CreateCommunity(): Command<typeof schemas.CreateCommunity> {
event_name: schemas.EventNames.CommunityCreated,
event_payload: {
community_id: id,
user_id: actor.user.id!,
referrer_address: payload.referrer_address,
user_id: user.id!,
referrer_address: user.referred_by_address ?? undefined,
created_at: created.created_at!,
},
},
Expand Down
77 changes: 45 additions & 32 deletions libs/model/src/community/GetMembers.query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import { QueryTypes } from 'sequelize';
import { z } from 'zod';
import { models } from '../database';

const buildOrderBy = (
by: 'name' | 'referrals' | 'earnings' | string,
direction: 'ASC' | 'DESC',
) => {
type OrderBy = 'name' | 'last_active' | 'referrals' | 'earnings';
type OrderDirection = 'ASC' | 'DESC';

const buildOrderBy = (by: OrderBy, direction: OrderDirection) => {
switch (by) {
case 'name':
return `profile_name ${direction}`;
Expand Down Expand Up @@ -101,7 +101,8 @@ const buildFilteredQuery = (
};

function membersSqlWithoutSearch(
orderBy: string,
by: OrderBy,
direction: OrderDirection,
limit: number,
offset: number,
) {
Expand All @@ -112,6 +113,15 @@ function membersSqlWithoutSearch(
U.profile->>'name' AS profile_name,
U.profile->>'avatar_url' AS avatar_url,
U.created_at,
(
SELECT JSON_BUILD_OBJECT(
'user_id', RU.id,
'profile_name', RU.profile->>'name',
'avatar_url', RU.profile->>'avatar_url'
)
FROM "Addresses" RA JOIN "Users" RU ON RA.user_id = RU.id
WHERE RA.address = U.referred_by_address LIMIT 1
) as referred_by,
COALESCE(U.referral_count, 0) AS referral_count,
COALESCE(U.referral_eth_earnings, 0) AS referral_eth_earnings,
MAX(COALESCE(A.last_active, U.created_at)) AS last_active,
Expand All @@ -120,15 +130,7 @@ function membersSqlWithoutSearch(
'address', A.address,
'community_id', A.community_id,
'role', A.role,
'stake_balance', 0, -- TODO: project stake balance here
'referred_by', (SELECT
JSON_BUILD_OBJECT(
'user_id', RU.id,
'profile_name', RU.profile->>'name',
'avatar_url', RU.profile->>'avatar_url'
)
FROM "Addresses" RA JOIN "Users" RU on RA.user_id = RU.id
WHERE RA.address = A.referred_by_address LIMIT 1)
'stake_balance', 0 -- TODO: project stake balance here
)) AS addresses,
COALESCE(ARRAY_AGG(M.group_id) FILTER (WHERE M.group_id IS NOT NULL), '{}') AS group_ids,
T.total
Expand All @@ -138,15 +140,21 @@ function membersSqlWithoutSearch(
JOIN T ON TRUE
WHERE
A.community_id = :community_id
${
by === 'referrals' || by === 'earnings'
? 'AND COALESCE(U.referral_count, 0) + COALESCE(U.referral_eth_earnings, 0) > 0'
: ''
}
GROUP BY U.id, T.total
ORDER BY ${orderBy}
ORDER BY ${buildOrderBy(by, direction)}
LIMIT ${limit} OFFSET ${offset};
`;
}

function membersSqlWithSearch(
cte: string,
orderBy: string,
by: OrderBy,
direction: OrderDirection,
limit: number,
offset: number,
) {
Expand All @@ -157,6 +165,15 @@ function membersSqlWithSearch(
U.profile->>'name' AS profile_name,
U.profile->>'avatar_url' AS avatar_url,
U.created_at,
(
SELECT JSON_BUILD_OBJECT(
'user_id', RU.id,
'profile_name', RU.profile->>'name',
'avatar_url', RU.profile->>'avatar_url'
)
FROM "Addresses" RA JOIN "Users" RU ON RA.user_id = RU.id
WHERE RA.address = U.referred_by_address LIMIT 1
) AS referred_by,
COALESCE(U.referral_count, 0) AS referral_count,
COALESCE(U.referral_eth_earnings, 0) AS referral_eth_earnings,
MAX(COALESCE(A.last_active, U.created_at)) AS last_active,
Expand All @@ -165,15 +182,7 @@ function membersSqlWithSearch(
'address', A.address,
'community_id', A.community_id,
'role', A.role,
'stake_balance', 0, -- TODO: project stake balance here
'referred_by', (SELECT
JSON_BUILD_OBJECT(
'user_id', RU.id,
'profile_name', RU.profile->>'name',
'avatar_url', RU.profile->>'avatar_url'
)
FROM "Addresses" RA JOIN "Users" RU on RA.user_id = RU.id
WHERE RA.address = A.referred_by_address LIMIT 1)
'stake_balance', 0 -- TODO: project stake balance here
)) AS addresses,
COALESCE(ARRAY_AGG(M.group_id) FILTER (WHERE M.group_id IS NOT NULL), '{}') AS group_ids,
T.total
Expand All @@ -182,8 +191,13 @@ function membersSqlWithSearch(
JOIN "Users" U ON A.user_id = U.id
LEFT JOIN "Memberships" M ON A.id = M.address_id AND M.reject_reason IS NULL
JOIN T ON TRUE
${
by === 'referrals' || by === 'earnings'
? 'WHERE COALESCE(U.referral_count, 0) + COALESCE(U.referral_eth_earnings, 0) > 0'
: ''
}
GROUP BY U.id, T.total
ORDER BY ${orderBy}
ORDER BY ${buildOrderBy(by, direction)}
LIMIT ${limit} OFFSET ${offset};
`;
}
Expand Down Expand Up @@ -214,10 +228,8 @@ export function GetMembers(): Query<typeof schemas.GetCommunityMembers> {
addresses,
};

const orderBy = buildOrderBy(
order_by ?? 'name',
order_direction ?? 'DESC',
);
const by = order_by ?? 'name';
const direction = order_direction ?? 'DESC';

const sql =
search || memberships || addresses.length > 0
Expand All @@ -226,11 +238,12 @@ export function GetMembers(): Query<typeof schemas.GetCommunityMembers> {
search ?? '',
buildFilters(memberships ?? '', addresses),
),
orderBy,
by,
direction,
limit,
offset,
)
: membersSqlWithoutSearch(orderBy, limit, offset);
: membersSqlWithoutSearch(by, direction, limit, offset);

const members = await models.sequelize.query<
z.infer<typeof schemas.CommunityMember> & { total?: number }
Expand Down
2 changes: 0 additions & 2 deletions libs/model/src/community/JoinCommunity.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,6 @@ export function JoinCommunity(): Command<typeof schemas.JoinCommunity> {
is_user_default: false,
ghost_address: false,
is_banned: false,
referred_by_address: payload.referrer_address,
},
{ transaction },
);
Expand All @@ -115,7 +114,6 @@ export function JoinCommunity(): Command<typeof schemas.JoinCommunity> {
event_payload: {
community_id,
user_id: actor.user.id!,
referrer_address: payload.referrer_address,
created_at: created.created_at!,
},
},
Expand Down
1 change: 0 additions & 1 deletion libs/model/src/models/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ export default (
created_at: { type: Sequelize.DATE, allowNull: false },
updated_at: { type: Sequelize.DATE, allowNull: false },
user_id: { type: Sequelize.INTEGER, allowNull: true },
referred_by_address: { type: Sequelize.STRING, allowNull: true },
ghost_address: {
type: Sequelize.BOOLEAN,
allowNull: false,
Expand Down
4 changes: 4 additions & 0 deletions libs/model/src/models/referral_fee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ export const ReferralFee = (
type: Sequelize.FLOAT,
allowNull: false,
},
referee_address: {
type: Sequelize.STRING,
allowNull: false,
},
transaction_timestamp: {
type: Sequelize.BIGINT,
allowNull: false,
Expand Down
1 change: 1 addition & 0 deletions libs/model/src/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ export default (sequelize: Sequelize.Sequelize): UserModelStatic =>
profile: { type: Sequelize.JSONB, allowNull: false },
xp_points: { type: Sequelize.INTEGER, defaultValue: 0, allowNull: true },
unsubscribe_uuid: { type: Sequelize.STRING, allowNull: true },
referred_by_address: { type: Sequelize.STRING, allowNull: true },
referral_count: {
type: Sequelize.INTEGER,
defaultValue: 0,
Expand Down
10 changes: 7 additions & 3 deletions libs/model/src/policies/ChainEventCreated.policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { systemActor } from '../middleware';
import { CreateLaunchpadToken } from '../token/CreateToken.command';
import { handleCommunityStakeTrades } from './handlers/handleCommunityStakeTrades';
import { handleLaunchpadTrade } from './handlers/handleLaunchpadTrade';
import { handleNamespaceDeployedWithReferral } from './handlers/handleNamespaceDeployedWithReferral';
import { handleReferralFeeDistributed } from './handlers/handleReferralFeeDistributed';
import { handleReferralSet } from './handlers/handleReferralSet';

const log = logger(import.meta);

Expand All @@ -17,8 +17,12 @@ export const processChainEventCreated: EventHandler<
ZodUndefined
> = async ({ payload }) => {
switch (payload.eventSource.eventSignature) {
case EvmEventSignatures.NamespaceFactory.NamespaceDeployedWithReferral:
await handleNamespaceDeployedWithReferral(payload);
break;

case EvmEventSignatures.CommunityStake.Trade:
await handleCommunityStakeTrades(models, payload);
await handleCommunityStakeTrades(payload);
break;

case EvmEventSignatures.Launchpad.TokenLaunched: {
Expand All @@ -43,7 +47,7 @@ export const processChainEventCreated: EventHandler<
break;

case EvmEventSignatures.Referrals.ReferralSet:
await handleReferralSet(payload);
// await handleReferralSet(payload);
break;

case EvmEventSignatures.Referrals.FeeDistributed:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import { getStakeTradeInfo } from '@hicommonwealth/evm-protocols';
import { chainEvents, events } from '@hicommonwealth/schemas';
import { BigNumber } from 'ethers';
import { z } from 'zod';
import { DB } from '../../models';
import { models } from '../../database';
import { chainNodeMustExist } from '../utils/utils';

const log = logger(import.meta);

export async function handleCommunityStakeTrades(
models: DB,
event: z.infer<typeof events.ChainEventCreated>,
) {
const {
Expand Down
Loading

0 comments on commit 321857f

Please sign in to comment.