Skip to content

Commit

Permalink
chore: changed username to be user id
Browse files Browse the repository at this point in the history
  • Loading branch information
gentlementlegen committed Apr 8, 2024
1 parent 9029696 commit 4defbd7
Show file tree
Hide file tree
Showing 16 changed files with 78 additions and 126 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"@octokit/webhooks": "^13.1.0",
"@octokit/webhooks-types": "^7.3.1",
"@sinclair/typebox": "^0.32.5",
"@supabase/supabase-js": "^2.39.7",
"@supabase/supabase-js": "2.42.0",
"@uniswap/permit2-sdk": "^1.2.0",
"blake2b": "^2.1.4",
"decimal.js": "^10.4.3",
Expand Down
11 changes: 0 additions & 11 deletions src/adapters/supabase/helpers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,6 @@ export class User extends Super {
return data;
}

async getUserIdByUsername(username: string) {
const { data, error } = await this.supabase.from("users").select("id").eq("username", username).single();
if (error) {
console.error(FAILED_TO_GET_USER, { username, error });
throw error;
}

console.log(SUCCESSFULLY_FETCHED_USER, { username, userId: data?.id });
return data?.id;
}

async getUserIdByWallet(wallet: string) {
const { data, error } = await this.supabase.from("wallets").select("id").eq("address", wallet).single();
if (error) {
Expand Down
35 changes: 5 additions & 30 deletions src/adapters/supabase/helpers/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,49 +9,24 @@ export class Wallet extends Super {
}

async getWalletByUserId(userId: number) {
const { data, error } = await this.supabase.from("wallets").select("address").eq("user_id", userId).single();
const { data, error } = await this.supabase.from("users").select("wallets(*)").eq("id", userId).single();
if (error) {
console.error("Failed to get wallet", { userId, error });
throw error;
}

console.info("Successfully fetched wallet", { userId, address: data.address });
return data.address;
}

async getWalletByUsername(username: string) {
const { data, error } = await this.supabase.from("users").select("id").eq("username", username).single();
if (error) {
console.error("Failed to get user", { username, error });
throw error;
}

const userId = data?.id;

if (!userId) {
console.error("Failed to get user", { username });
throw new Error("User not found");
}

const { data: walletData, error: walletError } = await this.supabase.from("wallets").select("address").eq("user_id", userId).single();

if (walletError) {
console.error("Failed to get wallet", { userId, error });
throw walletError;
}

console.info("Successfully fetched wallet", { userId, address: walletData?.address });

return walletData?.address as `0x${string}` | undefined;
console.info("Successfully fetched wallet", { userId, address: data.wallets?.address });
return data.wallets?.address;
}

async upsertWallet(userId: number, address: string) {
// TODO: fix to link to user
const { error } = await this.supabase.from("wallets").upsert([{ user_id: userId.toString(), address }]);
if (error) {
console.error("Failed to upsert wallet", { userId, address, error });
throw error;
}

console.info("Successfully upserted wallet", { userId, address });
console.info("Successfully upsert wallet", { userId, address });
}
}
4 changes: 2 additions & 2 deletions src/handlers/encode-decode.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Permit } from "../types/permits";
import { Permit, TokenType } from "../types";

/**
* Returns a base64 encoded string containing all the permit data
Expand All @@ -7,7 +7,7 @@ export function encodePermits(permits: Permit[]) {
return Buffer.from(
JSON.stringify(
permits.map((permit) => {
if (permit.tokenType === "ERC20") {
if (permit.tokenType === TokenType.ERC20) {
return {
type: "erc20-permit",
permit: {
Expand Down
18 changes: 8 additions & 10 deletions src/handlers/generate-erc20-permit.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,32 @@
import { PERMIT2_ADDRESS, PermitTransferFrom, SignatureTransfer } from "@uniswap/permit2-sdk";
import { ethers, keccak256, MaxInt256, parseUnits, toUtf8Bytes } from "ethers";
import { Context, Logger } from "../types/context";
import { Permit } from "../types/permits";
import { Permit, TokenType } from "../types";
import { decryptKeys } from "../utils/keys";
import { getPayoutConfigByNetworkId } from "../utils/payoutConfigByNetworkId";

export async function generateErc20PermitSignature(
username: string,
userId: number,
amount: number,
evmNetworkId: number,
evmPrivateEncrypted: string,
userId: number,
walletAddress: string,
issueId: number,
logger: Logger
): Promise<Permit>;
export async function generateErc20PermitSignature(username: string, amount: number, context: Context): Promise<Permit>;
export async function generateErc20PermitSignature(userId: number, amount: number, context: Context): Promise<Permit>;
export async function generateErc20PermitSignature(
username: string,
userId: number,
amount: number,
contextOrNetworkId: Context | number,
evmPrivateEncrypted?: string,
userId?: number,
walletAddress?: string,
issueId?: number,
logger?: Logger
): Promise<Permit> {
let _logger: Logger;
let _userId: number;
let _walletAddress: string | null;
let _walletAddress: string | null | undefined;
let _issueId: number;
let _evmNetworkId: number;
let _evmPrivateEncrypted: string;
Expand All @@ -44,8 +42,8 @@ export async function generateErc20PermitSignature(
const config = contextOrNetworkId.config;
_logger = contextOrNetworkId.logger;
const { evmNetworkId, evmPrivateEncrypted } = config;
const { user, wallet } = contextOrNetworkId.adapters.supabase;
_userId = await user.getUserIdByUsername(username);
const { wallet } = contextOrNetworkId.adapters.supabase;
_userId = userId;
_walletAddress = await wallet.getWalletByUserId(_userId);
_evmNetworkId = evmNetworkId;
_evmPrivateEncrypted = evmPrivateEncrypted;
Expand Down Expand Up @@ -120,7 +118,7 @@ export async function generateErc20PermitSignature(
});

const erc20Permit: Permit = {
tokenType: "ERC20",
tokenType: TokenType.ERC20,
tokenAddress: permitTransferFromData.permitted.token,
beneficiary: permitTransferFromData.spender,
nonce: permitTransferFromData.nonce.toString(),
Expand Down
34 changes: 20 additions & 14 deletions src/handlers/generate-erc721-permit.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { getPayoutConfigByNetworkId } from "../utils/payoutConfigByNetworkId";
import { ethers } from "ethers";
import { MaxUint256 } from "@uniswap/permit2-sdk";
import { keccak256, toUtf8Bytes } from "ethers";
import { Permit } from "../types/permits";
import { ethers, keccak256, toUtf8Bytes } from "ethers";
import { Context, Logger } from "../types/context";
import { Permit, TokenType } from "../types";
import { isIssueEvent } from "../types/typeguards";
import { getPayoutConfigByNetworkId } from "../utils/payoutConfigByNetworkId";

interface Erc721PermitSignatureData {
beneficiary: string;
Expand All @@ -31,41 +30,43 @@ export interface PermitPayload {
evmNetworkId: number;
nftMinterPrivateKey: string;
nftContractAddress: string;
userId: string;
walletAddress: string;
logger: Logger;
issueId: string;
organizationName: string;
repositoryName: string;
userName: string;
}

export async function generateErc721PermitSignature(username: string, contributionType: string, permitPayload: PermitPayload): Promise<Permit>;
export async function generateErc721PermitSignature(username: string, contributionType: string, context: Context): Promise<Permit>;
export async function generateErc721PermitSignature(userId: number, contributionType: string, permitPayload: PermitPayload): Promise<Permit>;
export async function generateErc721PermitSignature(userId: number, contributionType: string, context: Context): Promise<Permit>;
export async function generateErc721PermitSignature(
username: string,
userId: number,
contributionType: string,
contextOrPermitPayload: Context | PermitPayload
): Promise<Permit> {
let _logger: Logger;
let _nftContractAddress: string;
let _evmNetworkId: number;
let _nftMinterPrivateKey: string;
let _userId: string;
let _userId: number;
let _walletAddress: string;
let _issueId: string;
let _organizationName: string;
let _repositoryName: string;
let _username: string;

if ("evmNetworkId" in contextOrPermitPayload) {
_logger = contextOrPermitPayload.logger;
_nftContractAddress = contextOrPermitPayload.nftContractAddress;
_nftMinterPrivateKey = contextOrPermitPayload.nftMinterPrivateKey;
_evmNetworkId = contextOrPermitPayload.evmNetworkId;
_walletAddress = contextOrPermitPayload.walletAddress;
_userId = contextOrPermitPayload.userId;
_userId = userId;
_issueId = contextOrPermitPayload.issueId;
_organizationName = contextOrPermitPayload.organizationName;
_repositoryName = contextOrPermitPayload.repositoryName;
_username = contextOrPermitPayload.userName;
} else {
const { NFT_MINTER_PRIVATE_KEY, NFT_CONTRACT_ADDRESS } = contextOrPermitPayload.env;
const { evmNetworkId } = contextOrPermitPayload.config;
Expand All @@ -74,20 +75,25 @@ export async function generateErc721PermitSignature(
_nftContractAddress = NFT_CONTRACT_ADDRESS;
_evmNetworkId = evmNetworkId;
_nftMinterPrivateKey = NFT_MINTER_PRIVATE_KEY;
const walletAddress = await adapters.supabase.wallet.getWalletByUsername(username);
_userId = userId;
const walletAddress = await adapters.supabase.wallet.getWalletByUserId(_userId);
if (!walletAddress) {
_logger.error("No wallet found for user");
throw new Error("No wallet found for user");
}
_walletAddress = walletAddress;
_userId = await adapters.supabase.user.getUserIdByWallet(_walletAddress);
if (isIssueEvent(contextOrPermitPayload)) {
_issueId = contextOrPermitPayload.payload.issue.id.toString();
} else {
throw new Error("Issue Id is missing.");
}
_organizationName = contextOrPermitPayload.payload.repository.owner.login;
_repositoryName = contextOrPermitPayload.payload.repository.name;
const { data: userData } = await contextOrPermitPayload.octokit.request("GET /user/:id", { id: _userId });
if (!userData) {
throw new Error(`GitHub user was not found for id ${_userId}`);
}
_username = userData.login;
}

const { rpc } = getPayoutConfigByNetworkId(_evmNetworkId);
Expand Down Expand Up @@ -123,7 +129,7 @@ export async function generateErc721PermitSignature(
GITHUB_ORGANIZATION_NAME: _organizationName,
GITHUB_REPOSITORY_NAME: _repositoryName,
GITHUB_ISSUE_ID: _issueId,
GITHUB_USERNAME: username,
GITHUB_USERNAME: _username,
GITHUB_CONTRIBUTION_TYPE: contributionType,
};

Expand All @@ -149,7 +155,7 @@ export async function generateErc721PermitSignature(
});

const erc721Permit: Permit = {
tokenType: "ERC721",
tokenType: TokenType.ERC721,
tokenAddress: _nftContractAddress,
beneficiary: _walletAddress,
amount: "1",
Expand Down
6 changes: 3 additions & 3 deletions src/handlers/generate-payout-permit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ export async function generatePayoutPermit(context: Context, permitRequests: Per
const permits: Permit[] = [];

for (const permitRequest of permitRequests) {
const { type, amount, username, contributionType } = permitRequest;
const { type, amount, userId, contributionType } = permitRequest;

let permit: Permit;
switch (type) {
case "ERC20":
permit = await generateErc20PermitSignature(username, amount, context);
permit = await generateErc20PermitSignature(userId, amount, context);
break;
case "ERC721":
permit = await generateErc721PermitSignature(username, contributionType, context);
permit = await generateErc721PermitSignature(userId, contributionType, context);
break;
default:
context.logger.error(`Invalid permit type: ${type}`);
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./handlers";
export * from "./adapters";
export * from "./generate-permits-from-context";
export * from "./types";
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./permits";
5 changes: 4 additions & 1 deletion src/types/permits.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
type TokenType = "ERC20" | "ERC721";
export enum TokenType {
ERC20 = "ERC20",
ERC721 = "ERC721",
}

export interface Permit {
tokenType: TokenType;
Expand Down
2 changes: 1 addition & 1 deletion src/types/plugin-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export interface PluginInputs<T extends WebhookEventName = SupportedEvents> {

export const permitRequestSchema = T.Object({
type: T.Union([T.Literal("ERC20"), T.Literal("ERC721")]),
username: T.String(),
userId: T.Number(),
amount: T.Number(),
contributionType: T.String(),
});
Expand Down
20 changes: 0 additions & 20 deletions src/utils/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,6 @@
import Decimal from "decimal.js";
import { Context } from "../types/context";

export async function getWalletRecord(context: Context, senderID?: number, username?: string) {
const { wallet } = context.adapters.supabase;
let walletRecord = null;

if (senderID) {
walletRecord = await wallet.getWalletByUserId(senderID);
}

if (username) {
walletRecord = await wallet.getWalletByUsername(username);
}

if (!walletRecord) {
context.logger.error("No wallet found for user");
return null;
}

return walletRecord;
}

export async function handleNoWalletFound(context: Context, issueNumber: number, userLogin: string) {
const { logger, octokit } = context;
const repository = context.payload.repository;
Expand Down
2 changes: 1 addition & 1 deletion tests/constants.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Context } from "../src/types/context";

export const NFT_CONTRACT_ADDRESS = "0x0000000000000000000000000000000000000003";
export const SPENDER = "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d";
export const SPENDER = 123;

export const WALLET_ADDRESS = "0xefC0e701A824943b469a694aC564Aa1efF7Ab7dd";

Expand Down
Loading

0 comments on commit 4defbd7

Please sign in to comment.