Skip to content

Commit

Permalink
chore: moving to apollo client
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicolas Burtey committed Sep 19, 2023
1 parent 3ac5772 commit e530e59
Show file tree
Hide file tree
Showing 10 changed files with 2,202 additions and 83 deletions.
39 changes: 16 additions & 23 deletions apps/boltcard/app/api/callback/route.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,16 @@
import { getCoreClient } from "@/services/core"
import { fetchByCardId } from "@/services/db/card"
import { fetchByK1 } from "@/services/db/payment"
import { gql } from "graphql-request"

import { NextRequest, NextResponse } from "next/server"

Check failure on line 1 in apps/boltcard/app/api/callback/route.ts

View workflow job for this annotation

GitHub Actions / Check Code

Cannot find module 'next/server' or its corresponding type declarations.

type LnInvoicePaymentSendMutation = {
readonly __typename: "Mutation"
readonly lnInvoicePaymentSend: {
readonly __typename: "PaymentSendPayload"
readonly status?: string | null
readonly errors: ReadonlyArray<{
readonly __typename: "GraphQLApplicationError"
readonly message: string
}>
}
}
import { FetchResult, gql } from "@apollo/client"

import { fetchByCardId } from "@/services/db/card"

Check failure on line 5 in apps/boltcard/app/api/callback/route.ts

View workflow job for this annotation

GitHub Actions / Check Code

Cannot find module '@/services/db/card' or its corresponding type declarations.
import { fetchByK1 } from "@/services/db/payment"

Check failure on line 6 in apps/boltcard/app/api/callback/route.ts

View workflow job for this annotation

GitHub Actions / Check Code

Cannot find module '@/services/db/payment' or its corresponding type declarations.
import { apollo } from "@/services/core"

Check failure on line 7 in apps/boltcard/app/api/callback/route.ts

View workflow job for this annotation

GitHub Actions / Check Code

Cannot find module '@/services/core' or its corresponding type declarations.
import {
LnInvoicePaymentSendDocument,
LnInvoicePaymentSendMutation,
} from "@/services/core/generated"

Check failure on line 11 in apps/boltcard/app/api/callback/route.ts

View workflow job for this annotation

GitHub Actions / Check Code

Cannot find module '@/services/core/generated' or its corresponding type declarations.

const lnInvoicePaymentSendMutation = gql`
gql`
mutation lnInvoicePaymentSend($input: LnInvoicePaymentInput!) {
lnInvoicePaymentSend(input: $input) {
errors {
Expand Down Expand Up @@ -52,13 +45,13 @@ export async function GET(req: NextRequest) {

const card = await fetchByCardId(cardId)

const client = getCoreClient(card.token)
const client = apollo(card.token).getClient()
const { walletId } = card

let result: LnInvoicePaymentSendMutation
let result: FetchResult<LnInvoicePaymentSendMutation>
try {
result = await client.request<LnInvoicePaymentSendMutation>({
document: lnInvoicePaymentSendMutation,
result = await client.mutate<LnInvoicePaymentSendMutation>({
mutation: LnInvoicePaymentSendDocument,
variables: { input: { walletId, paymentRequest: pr } },
})
} catch (error) {
Expand All @@ -69,13 +62,13 @@ export async function GET(req: NextRequest) {
)
}

if (result.lnInvoicePaymentSend.status === "SUCCESS") {
if (result.data?.lnInvoicePaymentSend.status === "SUCCESS") {
return NextResponse.json({ status: "OK" })
} else {
return NextResponse.json(
{
status: "ERROR",
reason: `payment failed: ${result.lnInvoicePaymentSend.errors[0].message}`,
reason: `payment failed: ${result.data?.lnInvoicePaymentSend.errors[0].message}`,
},
{ status: 400 },
)
Expand Down
16 changes: 16 additions & 0 deletions apps/boltcard/app/api/card/id/[id]/transactions/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { NextRequest, NextResponse } from "next/server"

Check failure on line 1 in apps/boltcard/app/api/card/id/[id]/transactions/route.ts

View workflow job for this annotation

GitHub Actions / Check Code

Cannot find module 'next/server' or its corresponding type declarations.

import { fetchByCardId } from "@/services/db/card"

Check failure on line 3 in apps/boltcard/app/api/card/id/[id]/transactions/route.ts

View workflow job for this annotation

GitHub Actions / Check Code

Cannot find module '@/services/db/card' or its corresponding type declarations.

export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
const id = params.id
const card = await fetchByCardId(id)
if (!card) {
return NextResponse.json(
{ status: "ERROR", reason: "card not found" },
{ status: 400 },
)
}

return NextResponse.json(card)
}
75 changes: 26 additions & 49 deletions apps/boltcard/app/api/ln/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { randomBytes } from "crypto"

import { NextRequest, NextResponse } from "next/server"

import { ApolloQueryResult, gql } from "@apollo/client"

import { aesDecryptKey, serverUrl } from "@/services/config"
import { getCoreClient } from "@/services/core"
import { aesDecrypt, checkSignature } from "@/services/crypto/aes"
import { decodePToUidCtr } from "@/services/crypto/decoder"
import { createCard, fetchByUid } from "@/services/db/card"
Expand All @@ -13,9 +14,15 @@ import {
markCardInitAsUsed,
} from "@/services/db/card-init"
import { insertPayment } from "@/services/db/payment"
import { gql } from "graphql-request"
import { apollo } from "@/services/core"
import {
GetUsdWalletIdDocument,
GetUsdWalletIdQuery,
OnChainAddressCurrentDocument,
OnChainAddressCurrentMutation,
} from "@/services/core/generated"

function generateReadableCode(numDigits: number): string {
function generateReadableCode(numDigits: number, separator: number = 4): string {
const allowedNumbers = ["3", "4", "6", "7", "9"]
const allowedLetters = [
"A",
Expand Down Expand Up @@ -43,6 +50,9 @@ function generateReadableCode(numDigits: number): string {
const allowedChars = [...allowedNumbers, ...allowedLetters]
let code = ""
for (let i = 0; i < numDigits; i++) {
if (i > 0 && i % separator === 0) {
code += "-"
}
const randomIndex = Math.floor(Math.random() * allowedChars.length)
code += allowedChars[randomIndex]
}
Expand Down Expand Up @@ -88,28 +98,7 @@ const maybeSetupCard = async ({
return null
}

type GetUsdWalletIdQuery = {
readonly me?: {
readonly defaultAccount: {
readonly id: string
readonly defaultWalletId: string
readonly wallets: ReadonlyArray<
| {
readonly id: string
readonly walletCurrency: string
readonly balance: number
}
| {
readonly id: string
readonly walletCurrency: string
readonly balance: number
}
>
}
} | null
}

const getUsdWalletIdQuery = gql`
gql`
query getUsdWalletId {
me {
defaultAccount {
Expand All @@ -123,21 +112,7 @@ const getUsdWalletIdQuery = gql`
}
}
}
`

type OnChainAddressCurrentMutation = {
readonly __typename: "Mutation"
readonly onChainAddressCurrent: {
readonly __typename: "OnChainAddressPayload"
readonly address?: string | null
readonly errors: ReadonlyArray<{
readonly __typename: "GraphQLApplicationError"
readonly message: string
}>
}
}
const onChainAddressCurrent = gql`
mutation onChainAddressCurrent($input: OnChainAddressCurrentInput!) {
onChainAddressCurrent(input: $input) {
errors {
Expand Down Expand Up @@ -189,11 +164,13 @@ export async function GET(req: NextRequest) {
if (result) {
const { k0AuthKey, k2CmacKey, k3, k4, token } = result

const client = getCoreClient(token)
const client = apollo(token).getClient()

let data: GetUsdWalletIdQuery
let data: ApolloQueryResult<GetUsdWalletIdQuery>
try {
data = await client.request<GetUsdWalletIdQuery>(getUsdWalletIdQuery)
data = await client.query<GetUsdWalletIdQuery>({
query: GetUsdWalletIdDocument,
})
} catch (error) {
console.error(error)
return NextResponse.json(
Expand All @@ -202,15 +179,15 @@ export async function GET(req: NextRequest) {
)
}

const accountId = data?.me?.defaultAccount?.id
const accountId = data.data?.me?.defaultAccount?.id
if (!accountId) {
return NextResponse.json(
{ status: "ERROR", reason: "no accountId found" },
{ status: 400 },
)
}

const wallets = data.me?.defaultAccount.wallets
const wallets = data.data?.me?.defaultAccount.wallets

if (!wallets) {
return NextResponse.json(
Expand All @@ -231,20 +208,20 @@ export async function GET(req: NextRequest) {
)
}

const dataOnchain = await client.request<OnChainAddressCurrentMutation>({
document: onChainAddressCurrent,
const dataOnchain = await client.mutate<OnChainAddressCurrentMutation>({
mutation: OnChainAddressCurrentDocument,
variables: { input: { walletId } },
})
const onchainAddress = dataOnchain?.onChainAddressCurrent?.address
const onchainAddress = dataOnchain.data?.onChainAddressCurrent?.address
if (!onchainAddress) {
console.log(dataOnchain.onChainAddressCurrent, "dataOnchain")
console.log(dataOnchain.data?.onChainAddressCurrent, "dataOnchain")
return NextResponse.json(
{ status: "ERROR", reason: `onchain address not found` },
{ status: 400 },
)
}

const id = generateReadableCode(16)
const id = generateReadableCode(12)
console.log({ id, onchainAddress }, "new card id")

await markCardInitAsUsed(k2CmacKey)
Expand Down
3 changes: 2 additions & 1 deletion apps/boltcard/app/api/new/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server"

import { aesDecryptKey, serverUrl } from "@/services/config"
import { fetchByOneTimeCode } from "@/services/db/card-init"
import { NextRequest, NextResponse } from "next/server"

interface NewCardResponse {
protocol_name: string
Expand Down
2 changes: 1 addition & 1 deletion apps/boltcard/bats/e2e-test.bats
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ load "../../../test/bats/helpers/ln"
bitcoin_cli -generate 2

# retry 30 1 check_for_onchain_initiated_settled "$token_name" "$address"
sleep 1
sleep 2
}

@test "callback" {
Expand Down
Binary file modified apps/boltcard/bun.lockb
Binary file not shown.
60 changes: 60 additions & 0 deletions apps/boltcard/codegen.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
overwrite: true
schema:
- "https://raw.githubusercontent.com/GaloyMoney/galoy/main/src/graphql/public/schema.graphql"
- "https://raw.githubusercontent.com/GaloyMoney/galoy/main/src/graphql/admin/schema.graphql"
documents:
- "**/*.{ts,tsx}"
generates:
services/core/generated.ts:
plugins:
- typescript
- typescript-operations
- typescript-react-apollo
- add:
content: "// this file is autogenerated by codegen"
- add:
content: "\/* eslint-disable *\/"
config:
# typesPrefix: GQL
enumsAsConst: true
immutableTypes: true
strictScalars: true
nonOptionalTypename: true
scalars:
AccountApiKeyLabel: "string"
AuthToken: "string"
CentAmount: "number"
ContactAlias: "string"
Hex32Bytes: "string"
Language: "string"
LnPaymentPreImage: "string"
LnPaymentRequest: "string"
LnPaymentSecret: "string"
Memo: "string"
OnChainAddress: "string"
OnChainTxHash: "string"
OneTimeAuthCode: "string"
PaymentHash: "string"
Phone: "string"
SafeInt: "number"
SatAmount: "number"
SignedAmount: "number"
TargetConfirmations: "number"
Timestamp: "number"
Username: "string"
WalletId: "string"
Seconds: "number"
DisplayCurrency: "string"
SignedDisplayMajorAmount: "string"
CountryCode: "string"
EmailRegistrationId: "string"
TotpRegistrationId: "string"
EmailAddress: "string"
TotpSecret: "string"
TotpCode: "string"
Feedback: "string"
Minutes: "string"
LnPubkey: "string"
EndpointId: "string"
EndpointUrl: "string"
Object: "string"
14 changes: 11 additions & 3 deletions apps/boltcard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"lint": "next lint",
"codegen": "graphql-codegen --config codegen.yml"
},
"dependencies": {
"@apollo/client": "latest",
"@apollo/experimental-nextjs-app-support": "^0.4.2",
"@types/node": "20.6.2",
"@types/react": "18.2.21",
"@types/react-dom": "18.2.7",
Expand All @@ -18,7 +21,6 @@
"eslint": "8.49.0",
"eslint-config-next": "13.4.19",
"graphql": "^16.8.0",
"graphql-request": "^6.1.0",
"knex": "^2.5.1",
"next": "13.4.19",
"node-aes-cmac": "^0.1.1",
Expand All @@ -31,6 +33,12 @@
},
"devDependencies": {
"@types/pg": "^8.10.2",
"encoding": "^0.1.13"
"encoding": "^0.1.13",
"@graphql-codegen/add": "^5.0.0",
"@graphql-codegen/cli": "^5.0.0",
"@graphql-codegen/client-preset": "^4.1.0",
"@graphql-codegen/typescript": "^4.0.1",
"@graphql-codegen/typescript-operations": "^4.0.1",
"@graphql-codegen/typescript-react-apollo": "^3.3.7"
}
}
Loading

0 comments on commit e530e59

Please sign in to comment.