From 01d908407238f49ccff38b51c891ff2fdf385210 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 27 Jun 2024 11:41:03 +0300 Subject: [PATCH 01/58] First iteration - still WIP --- README.md | 2 +- docker/dev/docker-compose.yml | 1 - docker/prod/docker-compose.yml | 1 - .../wallet/backend/src/account/service.ts | 13 + packages/wallet/backend/src/app.ts | 13 +- packages/wallet/backend/src/config/env.ts | 1 - .../backend/src/config/walletAddress.ts | 25 ++ .../wallet/backend/src/createContainer.ts | 6 - packages/wallet/backend/src/rafiki/service.ts | 50 --- .../wallet/backend/src/rapyd/controller.ts | 1 - .../wallet/backend/src/rapyd/rapyd-client.ts | 2 +- .../wallet/backend/src/transaction/service.ts | 28 +- packages/wallet/backend/src/user/service.ts | 2 - .../backend/src/walletAddress/controller.ts | 8 +- .../wallet/backend/src/walletAddress/model.ts | 1 - .../backend/src/walletAddress/service.ts | 163 +++----- .../backend/src/walletAddress/validation.ts | 1 - .../src/webMonetization/transaction/model.ts | 21 -- .../webMonetization/transaction/service.ts | 74 ---- .../tests/incomingPayment/service.test.ts | 2 +- packages/wallet/backend/tests/mocks.ts | 2 +- .../backend/tests/rafiki/service.test.ts | 1 - .../tests/walletAddress/controller.test.ts | 2 - .../tests/walletAddress/service.test.ts | 83 ++-- .../components/cards/WalletAddressCard.tsx | 10 +- .../dialogs/CreateWalletAddressDialog.tsx | 12 - .../src/components/onboarding/Onboarding.tsx | 6 +- .../frontend/src/lib/api/walletAddress.ts | 1 - .../src/pages/account/[accountId].tsx | 356 +++++++----------- .../frontend/src/pages/account/create.tsx | 4 +- packages/wallet/frontend/src/pages/index.tsx | 2 +- .../frontend/src/pages/transfer/request.tsx | 2 +- .../frontend/src/pages/transfer/send.tsx | 2 +- packages/wallet/frontend/src/utils/helpers.ts | 4 +- 34 files changed, 312 insertions(+), 590 deletions(-) create mode 100644 packages/wallet/backend/src/config/walletAddress.ts delete mode 100644 packages/wallet/backend/src/webMonetization/transaction/model.ts delete mode 100644 packages/wallet/backend/src/webMonetization/transaction/service.ts diff --git a/README.md b/README.md index e8f5d5451..4395ac6f5 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ The `RAPYD_ACCESS_KEY` and `RAPYD_SECRET_KEY` variables values can be found in y To create a new Interledger Test Wallet account, a verification email will be sent to the provided email address. If you want to send emails within the development environment, you will need to have a personal Sendgrid account and update the following environment variables: `SEND_EMAIL` to `true`, `SENDGRID_API_KEY` and `FROM_EMAIL`. If you prefer not to send emails in the development environment, simply set `SEND_EMAIL` to `false` and use the verification link found in the Docker `wallet-backend` container logs to finalize the registration process for a new user. Cross-currency transactions are supported. To enable this functionality, you will need to register at [freecurrencyapi.com/](https://freecurrencyapi.com/) and update the `RATE_API_KEY` environment variable with your own API key. -Currencies can be added in the `admin` environment. For example `assetCode` is `EUR`, `assetScale` is `2`, and you will need to add an amount to `liquidity`. +Currencies can be added in the `admin` environment. For example `assetCode` is `USD`, `assetScale` is `2`, and you will need to add an amount to `liquidity`. To have everything ready for `DEV` environment, we already set up some default values for Interledger Test Wallet, this way developers are ready to login without validation, and test e-commerce application without any additional setup: diff --git a/docker/dev/docker-compose.yml b/docker/dev/docker-compose.yml index 0e4d80b03..670d3975f 100644 --- a/docker/dev/docker-compose.yml +++ b/docker/dev/docker-compose.yml @@ -54,7 +54,6 @@ services: RATE_API_KEY: ${RATE_API_KEY} BASE_ASSET_SCALE: 2 MAX_ASSET_SCALE: 9 - WM_THRESHOLD: 100000000 DEBT_THRESHOLD: 5 REDIS_URL: redis://redis:6379/0 restart: always diff --git a/docker/prod/docker-compose.yml b/docker/prod/docker-compose.yml index e84dadbd3..581c38d6e 100644 --- a/docker/prod/docker-compose.yml +++ b/docker/prod/docker-compose.yml @@ -67,7 +67,6 @@ services: RATE_API_KEY: ${WALLET_BACKEND_RATE_API_KEY} BASE_ASSET_SCALE: ${WALLET_BACKEND_BASE_ASSET_SCALE} MAX_ASSET_SCALE: ${WALLET_BACKEND_MAX_ASSET_SCALE} - WM_THRESHOLD: ${WALLET_BACKEND_WM_THRESHOLD} DEBT_THRESHOLD: ${WALLET_BACKEND_DEBT_THRESHOLD} REDIS_URL: ${WALLET_BACKEND_REDIS_URL} networks: diff --git a/packages/wallet/backend/src/account/service.ts b/packages/wallet/backend/src/account/service.ts index 86c606ad7..fabd0ccd3 100644 --- a/packages/wallet/backend/src/account/service.ts +++ b/packages/wallet/backend/src/account/service.ts @@ -218,6 +218,19 @@ export class AccountService implements IAccountService { ) } + async getVirtualAccountBalance(userId: string, assetCode: string): Promise { + const account = await Account.query() + .where('userId', userId) + .where('assetCode', assetCode) + .first() + + if (!account) { + throw new NotFound() + } + + return account.balance + } + public async fundAccount(args: FundAccountArgs): Promise { const existingAccount = await Account.query() .where('userId', args.userId) diff --git a/packages/wallet/backend/src/app.ts b/packages/wallet/backend/src/app.ts index 0055d943b..2a4bed3dc 100644 --- a/packages/wallet/backend/src/app.ts +++ b/packages/wallet/backend/src/app.ts @@ -38,7 +38,6 @@ import { UserController } from './user/controller' import type { UserService } from './user/service' import { SocketService } from './socket/service' import { GrantService } from '@/grant/service' -import { WMTransactionService } from '@/webMonetization/transaction/service' import { AwilixContainer } from 'awilix' import { Cradle } from '@/createContainer' import { initErrorHandler, RedisClient } from '@shared/backend' @@ -78,7 +77,6 @@ export interface Bindings { grantService: GrantService emailService: EmailService socketService: SocketService - wmTransactionService: WMTransactionService } export class App { @@ -336,24 +334,25 @@ export class App { }) } - private async processWMWalletAddresses() { + private async keepBalancesSynced(lastProcessedTimestamp: Date) { const logger = await this.container.resolve('logger') const walletAddressService = await this.container.resolve( 'walletAddressService' ) return walletAddressService - .processWMWalletAddresses() + .keepBalancesSynced(lastProcessedTimestamp) .catch((e) => { logger.error(e) return false }) .then((trx) => { + const newTimestamp = new Date(); if (trx) { - process.nextTick(() => this.processWMWalletAddresses()) + process.nextTick(() => this.keepBalancesSynced(newTimestamp)) } else { setTimeout( - () => this.processWMWalletAddresses(), + () => this.keepBalancesSynced(lastProcessedTimestamp), 1000 * 60 * 5 ).unref() } @@ -362,7 +361,7 @@ export class App { async processResources() { process.nextTick(() => this.processPendingTransactions()) - process.nextTick(() => this.processWMWalletAddresses()) + process.nextTick(() => this.keepBalancesSynced(new Date())) } async createDefaultUsers() { diff --git a/packages/wallet/backend/src/config/env.ts b/packages/wallet/backend/src/config/env.ts index c865c3c47..2fbe35270 100644 --- a/packages/wallet/backend/src/config/env.ts +++ b/packages/wallet/backend/src/config/env.ts @@ -34,7 +34,6 @@ const envSchema = z.object({ .transform((value) => value === 'true'), BASE_ASSET_SCALE: z.coerce.number().nonnegative().default(2), MAX_ASSET_SCALE: z.coerce.number().nonnegative().default(9), - WM_THRESHOLD: z.coerce.bigint().nonnegative().default(100_000_000n), // $0.1 in asset scale 9 DEBT_THRESHOLD: z.coerce.number().multipleOf(0.01).nonnegative().default(5.0), // $5.00 DEFAULT_WALLET_ACCOUNT: z .object({ diff --git a/packages/wallet/backend/src/config/walletAddress.ts b/packages/wallet/backend/src/config/walletAddress.ts new file mode 100644 index 000000000..321478a18 --- /dev/null +++ b/packages/wallet/backend/src/config/walletAddress.ts @@ -0,0 +1,25 @@ +import { Env } from '@/config/env' +import { RafikiClient } from '@/rafiki/rafiki-client' +import { AccountService } from '@/account/service' +import { WalletAddressService } from '@/walletAddress/service' +import { TransactionService } from '@/transaction/service' +import { RapydClient } from '@/rapyd/rapyd-client' +import { Logger } from 'winston' + +export function createWalletAddressService( + env: Env, + rafikiClient: RafikiClient, + accountService: AccountService, + rapydClient: RapydClient, + transactionService: TransactionService, + logger: Logger +) { + return new WalletAddressService( + accountService, + rafikiClient, + env, + transactionService, + rapydClient, + logger + ) +} diff --git a/packages/wallet/backend/src/createContainer.ts b/packages/wallet/backend/src/createContainer.ts index 945cb6789..eda9d5b56 100644 --- a/packages/wallet/backend/src/createContainer.ts +++ b/packages/wallet/backend/src/createContainer.ts @@ -30,7 +30,6 @@ import { type Knex } from 'knex' import { SocketService } from './socket/service' import { GrantService } from './grant/service' import { RatesService } from './rates/service' -import { WMTransactionService } from '@/webMonetization/transaction/service' import { Logger } from 'winston' import { asClass, @@ -69,7 +68,6 @@ export interface Cradle { accountService: AccountService ratesService: RatesService redisClient: RedisClient - wmTransactionService: WMTransactionService walletAddressService: WalletAddressService walletAddressKeyService: WalletAddressKeyService transactionService: TransactionService @@ -119,10 +117,6 @@ export async function createContainer( accountService: asClass(AccountService).singleton(), ratesService: asClass(RatesService).singleton(), redisClient: asFunction(createRedis).singleton(), - wmTransactionService: asClassSingletonWithLogger( - WMTransactionService, - logger - ), transactionService: asClassSingletonWithLogger(TransactionService, logger), walletAddressService: asClassSingletonWithLogger( WalletAddressService, diff --git a/packages/wallet/backend/src/rafiki/service.ts b/packages/wallet/backend/src/rafiki/service.ts index b8b621c49..9032751b6 100644 --- a/packages/wallet/backend/src/rafiki/service.ts +++ b/packages/wallet/backend/src/rafiki/service.ts @@ -8,9 +8,7 @@ import { UserService } from '@/user/service' import { SocketService } from '@/socket/service' import { NodeCacheInstance } from '@/utils/helpers' import { WalletAddressService } from '@/walletAddress/service' -import { WMTransactionService } from '@/webMonetization/transaction/service' import { Account } from '@/account/model' -import { WMTransaction } from '@/webMonetization/transaction/model' import MessageType from '@/socket/messageType' import { BadRequest } from '@shared/backend' @@ -85,7 +83,6 @@ export class RafikiService implements IRafikiService { private rafikiClient: RafikiClient, private transactionService: TransactionService, private walletAddressService: WalletAddressService, - private wmTransactionService: WMTransactionService ) {} public async onWebHook(wh: WebHook): Promise { @@ -177,17 +174,6 @@ export class RafikiService implements IRafikiService { const walletAddress = await this.getWalletAddress(wh) const amount = this.getAmountFromWebHook(wh) - if (walletAddress.isWM) { - await this.rafikiClient.withdrawLiqudity(wh.id) - - await this.wmTransactionService.updateTransaction( - { paymentId: wh.data.id }, - { status: 'COMPLETED', value: amount.value } - ) - - return - } - const receiverWalletId = await this.getRapydWalletId(walletAddress) if (!this.validateAmount(amount, wh.type)) { @@ -246,12 +232,6 @@ export class RafikiService implements IRafikiService { private async handleIncomingPaymentCreated(wh: WebHook) { const walletAddress = await this.getWalletAddress(wh) - if (walletAddress.isWM) { - await this.wmTransactionService.createIncomingTransaction(wh.data) - - return - } - await this.transactionService.createIncomingTransaction( wh.data, walletAddress @@ -262,12 +242,6 @@ export class RafikiService implements IRafikiService { const walletAddress = await this.getWalletAddress(wh) const amount = this.getAmountFromWebHook(wh) - if (walletAddress.isWM) { - await this.rafikiClient.depositLiquidity(wh.id) - await this.wmTransactionService.createOutgoingTransaction(wh.data) - return - } - const rapydWalletId = await this.getRapydWalletId(walletAddress) if (!this.validateAmount(amount, wh.type)) { @@ -304,17 +278,6 @@ export class RafikiService implements IRafikiService { const walletAddress = await this.getWalletAddress(wh) const debitAmount = this.getAmountFromWebHook(wh) - if (walletAddress.isWM) { - await this.rafikiClient.withdrawLiqudity(wh.id) - - await this.wmTransactionService.updateTransaction( - { paymentId: wh.data.id }, - { status: 'COMPLETED', value: debitAmount.value } - ) - - return - } - const source_ewallet = await this.getRapydWalletId(walletAddress) if (!this.validateAmount(debitAmount, wh.type)) { @@ -376,19 +339,6 @@ export class RafikiService implements IRafikiService { const sentAmount = this.parseAmount(wh.data.sentAmount as AmountJSON) - if (walletAddress.isWM) { - await this.rafikiClient.withdrawLiqudity(wh.id) - - const update: Partial = sentAmount.value - ? { status: 'COMPLETED', value: sentAmount.value } - : { status: 'FAILED', value: 0n } - await this.wmTransactionService.updateTransaction( - { paymentId: wh.data.id }, - update - ) - - return - } const source_ewallet = await this.getRapydWalletId(walletAddress) diff --git a/packages/wallet/backend/src/rapyd/controller.ts b/packages/wallet/backend/src/rapyd/controller.ts index 2a4f5bffb..88d939711 100644 --- a/packages/wallet/backend/src/rapyd/controller.ts +++ b/packages/wallet/backend/src/rapyd/controller.ts @@ -97,7 +97,6 @@ export class RapydController implements IRapydController { walletAddressName, publicName: 'Default Payment Pointer', userId: id, - isWM: false }) } diff --git a/packages/wallet/backend/src/rapyd/rapyd-client.ts b/packages/wallet/backend/src/rapyd/rapyd-client.ts index 89feb8904..e223bd708 100644 --- a/packages/wallet/backend/src/rapyd/rapyd-client.ts +++ b/packages/wallet/backend/src/rapyd/rapyd-client.ts @@ -289,7 +289,7 @@ export class RapydClient implements IRapydClient { : ',' const [street, city, postCode] = args.user.address?.split(', ') ?? [] let address = [street, postCode].join(addressDelimiter) - if (args.assetCode === 'EUR') address = address.replace(/[,\s]+/g, '') + if (args.assetCode === 'USD') address = address.replace(/[,\s]+/g, '') // withdraw funds/create payout from wallet account into bank account const userDetails: RequiredFieldsType = { diff --git a/packages/wallet/backend/src/transaction/service.ts b/packages/wallet/backend/src/transaction/service.ts index 63ea8a6a8..2699a4069 100644 --- a/packages/wallet/backend/src/transaction/service.ts +++ b/packages/wallet/backend/src/transaction/service.ts @@ -1,5 +1,5 @@ -import { Transaction } from './model' -import { OrderByDirection, Page, PartialModelObject } from 'objection' +import { Transaction, TransactionType } from './model' +import { OrderByDirection, Page, PartialModelObject, TransactionOrKnex } from 'objection' import { AccountService } from '@/account/service' import { Logger } from 'winston' import { PaginationQueryParams } from '@/shared/types' @@ -164,4 +164,28 @@ export class TransactionService implements ITransactionService { description: params.metadata?.description }) } + + async sumByWalletAddressIdSince( + walletAddressId: string, + type: TransactionType, + since: Date, + trx?: TransactionOrKnex + ) { + //TODO updatedAt instead of createdAt? + const transactions = await Transaction.query(trx).where({ + walletAddressId, + type, + status: 'COMPLETED' + }).andWhere('createdAt', '>', since); + + const ids = transactions.map(({ id }) => id) + const sumResult = (await Transaction.query(trx) + .whereIn('id', ids) + .sum('value')) as unknown as [{ sum: bigint }] + + return { + ids, + sum: sumResult[0].sum ?? 0n + } + } } diff --git a/packages/wallet/backend/src/user/service.ts b/packages/wallet/backend/src/user/service.ts index 015cea805..10070152f 100644 --- a/packages/wallet/backend/src/user/service.ts +++ b/packages/wallet/backend/src/user/service.ts @@ -150,7 +150,6 @@ export class UserService implements IUserService { walletAddressName: typedArray[0].toString(16), publicName: 'Default Payment Pointer', userId: walletInfo.createdUser.id, - isWM: false }) const boutiqueWallet = await this.walletAddressService.create({ @@ -158,7 +157,6 @@ export class UserService implements IUserService { walletAddressName: 'boutique', publicName: 'Default Payment Pointer', userId: boutiqueInfo.createdUser.id, - isWM: false }) await this.walletAddressKeyService.registerKey({ diff --git a/packages/wallet/backend/src/walletAddress/controller.ts b/packages/wallet/backend/src/walletAddress/controller.ts index 47faebe5b..ddcedd18d 100644 --- a/packages/wallet/backend/src/walletAddress/controller.ts +++ b/packages/wallet/backend/src/walletAddress/controller.ts @@ -8,12 +8,11 @@ import { updateWalletAddressSchema } from './validation' import { Controller, toSuccessResponse } from '@shared/backend' -import { ListWalletAddressesResponse } from '@wallet/shared/src' import { WalletAddressOP, WalletAddressResponse } from '@wallet/shared' interface IWalletAddressController { create: Controller - list: Controller + list: Controller getById: Controller softDelete: Controller } @@ -30,7 +29,7 @@ export class WalletAddressController implements IWalletAddressController { const userId = req.session.user.id const { accountId } = req.params const { - body: { walletAddressName, publicName, isWM } + body: { walletAddressName, publicName } } = await validate(walletAddressSchema, req) const walletAddress = await this.walletAddressService.create({ @@ -38,7 +37,6 @@ export class WalletAddressController implements IWalletAddressController { accountId, walletAddressName, publicName, - isWM }) res.status(200).json(toSuccessResponse(walletAddress)) } catch (e) { @@ -48,7 +46,7 @@ export class WalletAddressController implements IWalletAddressController { list = async ( req: Request, - res: CustomResponse, + res: CustomResponse, next: NextFunction ) => { const userId = req.session.user.id diff --git a/packages/wallet/backend/src/walletAddress/model.ts b/packages/wallet/backend/src/walletAddress/model.ts index 39a9bff52..39bbdcfe7 100644 --- a/packages/wallet/backend/src/walletAddress/model.ts +++ b/packages/wallet/backend/src/walletAddress/model.ts @@ -12,7 +12,6 @@ export class WalletAddress extends BaseModel implements IWalletAddressResponse { readonly id!: string readonly url!: string readonly accountId!: string - isWM!: boolean assetCode!: string | null assetScale!: number | null incomingBalance!: bigint diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index 2020ad559..294880331 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -4,18 +4,16 @@ import { Env } from '@/config/env' import { RafikiClient } from '@/rafiki/rafiki-client' import axios from 'axios' import { getRandomValues } from 'crypto' -import { Cache, RedisClient } from '@shared/backend' import { WalletAddress } from './model' -import { WMTransactionService } from '@/webMonetization/transaction/service' import { PartialModelObject, TransactionOrKnex, raw } from 'objection' import { RapydClient } from '@/rapyd/rapyd-client' import { TransactionType } from '@/transaction/model' import { Logger } from 'winston' import { TransactionService } from '@/transaction/service' -import { BadRequest, Conflict, NotFound } from '@shared/backend' +import { Conflict, NotFound } from '@shared/backend' import { WalletAddressOP } from '@wallet/shared' -interface HandleBalanceParams { +interface HandleImbalanceParams { type: TransactionType balance: bigint walletAddress: WalletAddress @@ -33,7 +31,6 @@ export interface CreateWalletAddressArgs { accountId: string walletAddressName: string publicName: string - isWM: boolean } export type GetWalletAddressArgs = { @@ -42,15 +39,10 @@ export type GetWalletAddressArgs = { userId?: string } -export type WalletAddressList = { - wmWalletAddresses: WalletAddress[] - walletAddresses: WalletAddress[] -} - interface IWalletAddressService { create: (params: CreateWalletAddressArgs) => Promise update: (args: UpdateWalletAddressArgs) => Promise - list: (userId: string, accountId: string) => Promise + list: (userId: string, accountId: string) => Promise getById: (args: GetWalletAddressArgs) => Promise softDelete: (userId: string, id: string) => Promise } @@ -77,25 +69,20 @@ export const createWalletAddressIfFalsy = async ({ accountId, walletAddressName: getRandomValues(new Uint32Array(1))[0].toString(16), publicName, - isWM: false }) return newWalletAddress } export class WalletAddressService implements IWalletAddressService { - private cache: Cache constructor( private accountService: AccountService, private rafikiClient: RafikiClient, private env: Env, - redisClient: RedisClient, - private wmTransactionService: WMTransactionService, private transactionService: TransactionService, private rapydClient: RapydClient, private logger: Logger ) { - this.cache = new Cache(redisClient, 'WMWalletAddresses') } async create(args: CreateWalletAddressArgs): Promise { @@ -127,26 +114,7 @@ export class WalletAddressService implements IWalletAddressService { ) } } else { - let webMonetizationAsset - if (args.isWM) { - // @TEMPORARY: Enable WM only for USD - if (account.assetCode !== 'USD') { - throw new BadRequest( - 'Web Monetization is enabled exclusively for USD.' - ) - } - - webMonetizationAsset = await this.rafikiClient.getRafikiAsset( - 'USD', - this.env.MAX_ASSET_SCALE - ) - - if (!webMonetizationAsset) { - throw new NotFound('Web monetization asset not found.') - } - } - - const assetId = webMonetizationAsset?.id || account.assetId + const assetId = account.assetId const rafikiWalletAddress = await this.rafikiClient.createRafikiWalletAddress( args.publicName, @@ -159,48 +127,27 @@ export class WalletAddressService implements IWalletAddressService { publicName: args.publicName, accountId: args.accountId, id: rafikiWalletAddress.id, - isWM: args.isWM, - assetCode: webMonetizationAsset?.code, - assetScale: webMonetizationAsset?.scale + assetCode: null, + assetScale: this.env.MAX_ASSET_SCALE }) - - args.isWM && - (await this.cache.set(walletAddress.id, walletAddress, { - expiry: 60 - })) } return walletAddress } - async list(userId: string, accountId: string): Promise { + async list(userId: string, accountId: string): Promise { const account = await this.accountService.findAccountById(accountId, userId) const walletAddressesResult = await WalletAddress.query() .where('accountId', account.id) .where('active', true) - const result = walletAddressesResult.reduce( - (acc, pp) => { - if (pp.isWM) { - acc.wmWalletAddresses.push(pp) - } else { - acc.walletAddresses.push(pp) - } - return acc - }, - { - wmWalletAddresses: [] as WalletAddress[], - walletAddresses: [] as WalletAddress[] - } - ) - - return result + return walletAddressesResult } async listAll(userId: string): Promise { return WalletAddress.query() - .where({ isWM: false, active: true }) + .where({ active: true }) .joinRelated('account') .where({ 'account.userId': userId @@ -208,13 +155,6 @@ export class WalletAddressService implements IWalletAddressService { } async getById(args: GetWalletAddressArgs): Promise { - //* Cache only contains WalletAddresses with isWM = true - const cacheHit = await this.cache.get(args.walletAddressId) - if (cacheHit) { - //* TODO: reset ttl - return cacheHit - } - if (args.userId && args.accountId) { await this.accountService.findAccountById(args.accountId, args.userId) } @@ -231,12 +171,6 @@ export class WalletAddressService implements IWalletAddressService { throw new NotFound() } - if (walletAddress.isWM) { - await this.cache.set(walletAddress.id, walletAddress, { - expiry: 60 - }) - } - return walletAddress } @@ -324,13 +258,6 @@ export class WalletAddressService implements IWalletAddressService { } async findByIdWithoutValidation(id: string) { - //* Cache only contains WalletAddresses with isWM = true - const cacheHit = await this.cache.get(id) - if (cacheHit) { - //* TODO: reset ttl - return cacheHit - } - const walletAddress = await WalletAddress.query() .findById(id) .where('active', true) @@ -339,17 +266,11 @@ export class WalletAddressService implements IWalletAddressService { throw new NotFound() } - if (walletAddress.isWM) { - await this.cache.set(walletAddress.id, walletAddress, { - expiry: 60 - }) - } - return walletAddress } - private async handleBalance( - { type, balance, walletAddress }: HandleBalanceParams, + private async handleImbalance( + { type, balance, walletAddress }: HandleImbalanceParams, trx: TransactionOrKnex ): Promise { if (!walletAddress.assetCode || !walletAddress.assetScale) { @@ -357,9 +278,17 @@ export class WalletAddressService implements IWalletAddressService { `Missing asset information for payment pointer "${walletAddress.url} (ID: ${walletAddress.id})"` ) } + + this.logger.debug( + `Passed first throw` + ) + + // 10000000 is 0.01 i.e. one cent in asset scale 9 + // One cent is the lowest number that can be represented in asset scale 2 by Rapyd + const rapydMinRepresentation = 10000000n const amount = Number( ( - Number(balance * this.env.WM_THRESHOLD) * + Number(balance * rapydMinRepresentation) * 10 ** -walletAddress.assetScale ).toPrecision(2) ) @@ -370,6 +299,10 @@ export class WalletAddressService implements IWalletAddressService { ) } + this.logger.debug( + `Passed second throw` + ) + let destination = walletAddress.account.user.rapydWalletId let source = this.env.RAPYD_SETTLEMENT_EWALLET @@ -387,9 +320,14 @@ export class WalletAddressService implements IWalletAddressService { if (transfer.status?.status !== 'SUCCESS') { if (type === 'OUTGOING') { + //TODO this might not be needed await walletAddress.$relatedQuery('account', trx).patch({ debt: raw('?? + ?', ['debt', amount]) }) + + this.logger.debug( + `Early return` + ) return } @@ -400,6 +338,10 @@ export class WalletAddressService implements IWalletAddressService { ) } + this.logger.debug( + `Passed third throw` + ) + const updatedField: keyof Pick< PartialModelObject, 'incomingBalance' | 'outgoingBalance' @@ -407,7 +349,7 @@ export class WalletAddressService implements IWalletAddressService { const updatePart: PartialModelObject = { [updatedField]: raw('?? - ?', [ updatedField, - this.env.WM_THRESHOLD * balance + rapydMinRepresentation * balance ]) } @@ -419,23 +361,23 @@ export class WalletAddressService implements IWalletAddressService { value: BigInt(amount * 10 ** this.env.BASE_ASSET_SCALE), type, status: 'COMPLETED', - description: 'Web Monetization' + description: 'Asset scale 9 imbalance' }), walletAddress.$query(trx).update(updatePart) ]) - this.logger.info( - `Proccesed WM transactions for payment pointer ${walletAddress.url}. Type: ${type} | Amount: ${amount}` + //TODO remove this after testing + this.logger.debug( + `Proccesed asset scale 9 transactions for payment pointer ${walletAddress.url}. Type: ${type} | Amount: ${amount}` ) } - async processWMWalletAddresses(): Promise { + async keepBalancesSynced(lastProcessedTimestamp: Date): Promise { const trx = await WalletAddress.startTransaction() try { const walletAddresses = await WalletAddress.query(trx) .where({ - isWM: true, active: true }) .withGraphFetched('account.user') @@ -446,14 +388,16 @@ export class WalletAddressService implements IWalletAddressService { } const [incoming, outgoing] = await Promise.all([ - this.wmTransactionService.sumByWalletAddressId( + this.transactionService.sumByWalletAddressIdSince( walletAddress.id, 'INCOMING', + lastProcessedTimestamp, trx ), - this.wmTransactionService.sumByWalletAddressId( + this.transactionService.sumByWalletAddressIdSince( walletAddress.id, 'OUTGOING', + lastProcessedTimestamp, trx ) ]) @@ -465,18 +409,21 @@ export class WalletAddressService implements IWalletAddressService { outgoingBalance: raw('?? + ?', ['outgoingBalance', outgoing.sum]) }) - await this.wmTransactionService.deleteByTransactionIds( - incoming.ids.concat(outgoing.ids), - trx - ) + // 10000000 is 0.01 i.e. one cent in asset scale 9 + // One cent is the lowest number that can be represented in asset scale 2 by Rapyd + const rapydMinRepresentation = 10000000n const incomingBalance = - tmpWalletAddress.incomingBalance / this.env.WM_THRESHOLD + tmpWalletAddress.incomingBalance / rapydMinRepresentation const outgoingBalance = - tmpWalletAddress.outgoingBalance / this.env.WM_THRESHOLD + tmpWalletAddress.outgoingBalance / rapydMinRepresentation + + this.logger.debug( + `Incoming balance: ${incomingBalance}. Outgoing balance: ${outgoingBalance}` + ) if (incomingBalance > 0n) { - await this.handleBalance( + await this.handleImbalance( { balance: incomingBalance, walletAddress, @@ -487,7 +434,7 @@ export class WalletAddressService implements IWalletAddressService { } if (outgoingBalance > 0n) { - await this.handleBalance( + await this.handleImbalance( { balance: outgoingBalance, walletAddress, @@ -501,7 +448,7 @@ export class WalletAddressService implements IWalletAddressService { } catch (e) { this.logger.error(e) await trx.rollback() - throw new Error('Error while processing WM payment pointers.') + throw new Error('Error while processing payment pointers.') } } } diff --git a/packages/wallet/backend/src/walletAddress/validation.ts b/packages/wallet/backend/src/walletAddress/validation.ts index 85eeb0632..0f032d615 100644 --- a/packages/wallet/backend/src/walletAddress/validation.ts +++ b/packages/wallet/backend/src/walletAddress/validation.ts @@ -45,7 +45,6 @@ export const walletAddressSchema = z.object({ .string() .trim() .min(3, { message: 'Public name must be at least 3 characters long' }), - isWM: z.boolean() }) }) diff --git a/packages/wallet/backend/src/webMonetization/transaction/model.ts b/packages/wallet/backend/src/webMonetization/transaction/model.ts deleted file mode 100644 index 96ed7fbcf..000000000 --- a/packages/wallet/backend/src/webMonetization/transaction/model.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { TransactionBaseModel } from '@/transaction/model' -import { Model } from 'objection' -import { WalletAddress } from '@/walletAddress/model' - -export class WMTransaction extends TransactionBaseModel { - static tableName = 'wmTransactions' - - walletAddressId!: string - walletAddress!: WalletAddress - - static relationMappings = () => ({ - wmWalletAddress: { - relation: Model.BelongsToOneRelation, - modelClass: WalletAddress, - join: { - from: 'wmTransactions.walletAddressId', - to: 'walletAddresses.id' - } - } - }) -} diff --git a/packages/wallet/backend/src/webMonetization/transaction/service.ts b/packages/wallet/backend/src/webMonetization/transaction/service.ts deleted file mode 100644 index addf86740..000000000 --- a/packages/wallet/backend/src/webMonetization/transaction/service.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { WMTransaction } from './model' -import { PartialModelObject, TransactionOrKnex } from 'objection' -import { Logger } from 'winston' -import { - IncomingPayment, - OutgoingPayment -} from '@/rafiki/backend/generated/graphql' -import { TransactionType } from '@/transaction/model' -import { addMinutes } from 'date-fns' - -export interface IWMTransactionService {} - -export class WMTransactionService implements IWMTransactionService { - constructor(private logger: Logger) {} - - async updateTransaction( - where: PartialModelObject, - update: PartialModelObject - ): Promise { - try { - this.logger.info(`Updating transaction with: ${JSON.stringify(update)}`) - await WMTransaction.query().where(where).update(update) - } catch (e) { - this.logger.error(`Update transaction error:`, e) - } - } - async createIncomingTransaction(params: IncomingPayment) { - return WMTransaction.query().insert({ - walletAddressId: params.walletAddressId, - paymentId: params.id, - expiresAt: params.expiresAt - ? new Date(params.expiresAt) - : addMinutes(new Date(), 10), - type: 'INCOMING', - status: 'PENDING' - }) - } - - async createOutgoingTransaction(params: OutgoingPayment) { - const amount = params.debitAmount - return WMTransaction.query().insert({ - walletAddressId: params.walletAddressId, - paymentId: params.id, - value: amount.value, - type: 'OUTGOING', - status: 'PENDING' - }) - } - - async deleteByTransactionIds(ids: string[], trx?: TransactionOrKnex) { - return WMTransaction.query(trx).del().whereIn('id', ids) - } - - async sumByWalletAddressId( - walletAddressId: string, - type: TransactionType, - trx?: TransactionOrKnex - ) { - const transactions = await WMTransaction.query(trx).where({ - walletAddressId, - type, - status: 'COMPLETED' - }) - const ids = transactions.map(({ id }) => id) - const sumResult = (await WMTransaction.query(trx) - .whereIn('id', ids) - .sum('value')) as unknown as [{ sum: bigint }] - - return { - ids, - sum: sumResult[0].sum ?? 0n - } - } -} diff --git a/packages/wallet/backend/tests/incomingPayment/service.test.ts b/packages/wallet/backend/tests/incomingPayment/service.test.ts index 76b8dd343..673047fc6 100644 --- a/packages/wallet/backend/tests/incomingPayment/service.test.ts +++ b/packages/wallet/backend/tests/incomingPayment/service.test.ts @@ -168,7 +168,7 @@ describe('Incoming Payment Service', () => { faker.internet.url() ) expect(receivedAmount).toMatchObject({ - assetCode: 'EUR', + assetCode: 'USD', assetScale: 1, value: '0' }) diff --git a/packages/wallet/backend/tests/mocks.ts b/packages/wallet/backend/tests/mocks.ts index d54212fea..bfc3f5450 100644 --- a/packages/wallet/backend/tests/mocks.ts +++ b/packages/wallet/backend/tests/mocks.ts @@ -526,6 +526,6 @@ export const mockWalletAddress = { } export const mockExternalPayment = { - receivedAmount: { value: '0', assetCode: 'EUR', assetScale: 1 }, + receivedAmount: { value: '0', assetCode: 'USD', assetScale: 1 }, authServer: 'http://rafiki-auth:3006' } diff --git a/packages/wallet/backend/tests/rafiki/service.test.ts b/packages/wallet/backend/tests/rafiki/service.test.ts index b096ee9e0..f935636f9 100644 --- a/packages/wallet/backend/tests/rafiki/service.test.ts +++ b/packages/wallet/backend/tests/rafiki/service.test.ts @@ -64,7 +64,6 @@ describe('Rafiki Service', () => { walletAddressService: { findByIdWithoutValidation: () => walletAddress || mockWalletAddress }, - wmTransactionService: {}, env: bindings.resolve('env'), logger: bindings.resolve('logger') } diff --git a/packages/wallet/backend/tests/walletAddress/controller.test.ts b/packages/wallet/backend/tests/walletAddress/controller.test.ts index b0fc1acfc..ca96f2f20 100644 --- a/packages/wallet/backend/tests/walletAddress/controller.test.ts +++ b/packages/wallet/backend/tests/walletAddress/controller.test.ts @@ -136,7 +136,6 @@ describe('Wallet Address', () => { req.body = { walletAddressName: faker.lorem.slug(), publicName: faker.lorem.words({ min: 2, max: 2 }), - isWM: false } await walletAddressController.create(req, res, next) expect(res.statusCode).toBe(200) @@ -157,7 +156,6 @@ describe('Wallet Address', () => { req.body = { walletAddressName: faker.lorem.slug(), publicName: faker.lorem.words({ min: 2, max: 2 }), - isWM: false } await walletAddressController.create(req, res, (err) => { next() diff --git a/packages/wallet/backend/tests/walletAddress/service.test.ts b/packages/wallet/backend/tests/walletAddress/service.test.ts index 71120519c..9df161475 100644 --- a/packages/wallet/backend/tests/walletAddress/service.test.ts +++ b/packages/wallet/backend/tests/walletAddress/service.test.ts @@ -30,7 +30,6 @@ describe('Wallet Address Service', () => { const prepareWADependencies = async ( paymentPointerName: string, isAccountAssigned = true, - isWM?: { assetCode?: string; assetScale?: number; isWM: boolean } ) => { let extraAcc = {} as Account if (!isAccountAssigned) @@ -57,9 +56,8 @@ describe('Wallet Address Service', () => { publicName: faker.string.alpha(10), accountId: isAccountAssigned ? account.id : extraAcc.id, id: faker.string.uuid(), - assetCode: isWM?.assetCode || undefined, - assetScale: isWM?.assetScale || undefined, - isWM: isWM?.isWM + assetCode: undefined, + assetScale: 9, }) return { @@ -73,10 +71,6 @@ describe('Wallet Address Service', () => { accountService, env: serviceEnv, logger, - cache: { - get: jest.fn(), - set: jest.fn() - }, rafikiClient: { createRafikiWalletAddress: () => ({ id: faker.string.uuid(), @@ -88,12 +82,12 @@ describe('Wallet Address Service', () => { revokeWalletAddressKey: jest.fn(), updateWalletAddress: jest.fn() }, - wmTransactionService: { - deleteByTransactionIds: jest.fn(), - sumByWalletAddressId: () => ({ + transactionService: { + sumByWalletAddressIdSince: () => ({ ids: [uuid()], sum: sumWS - }) + }), + updateTransaction: jest.fn() } } @@ -145,7 +139,6 @@ describe('Wallet Address Service', () => { accountId: account.id, walletAddressName: 'my-wallet', publicName: 'My Wallet', - isWM: false }) expect(result).toHaveProperty('publicName') expect(result).toHaveProperty('accountId') @@ -163,7 +156,6 @@ describe('Wallet Address Service', () => { accountId: account.id, walletAddressName: 'my-wallet', publicName: 'My Wallet', - isWM: false }) expect(result).toHaveProperty('publicName') expect(result).toHaveProperty('accountId') @@ -182,7 +174,6 @@ describe('Wallet Address Service', () => { accountId: account.id, walletAddressName: 'my-work', publicName: 'My Work', - isWM: false }) ).rejects.toThrowError( /This payment pointer already exists. Please choose another name./ @@ -195,9 +186,7 @@ describe('Wallet Address Service', () => { const { account, walletAddress } = await prepareWADependencies('my-wallet') const result = await waService.list(userId, account.id) - expect(result).toHaveProperty('wmWalletAddresses') - expect(result).toHaveProperty('walletAddresses') - expect(result.walletAddresses[0]).toMatchObject({ + expect(result[0]).toMatchObject({ url: walletAddress.url, accountId: account.id }) @@ -293,7 +282,7 @@ describe('Wallet Address Service', () => { url: `${serviceEnv.OPEN_PAYMENTS_HOST}/test`, publicName: 'Test Wallet', assetCode: 'USD', - assetScale: 2 + assetScale: 9 } }) ) @@ -307,7 +296,7 @@ describe('Wallet Address Service', () => { url: `${serviceEnv.OPEN_PAYMENTS_HOST}/test`, publicName: 'Test Wallet', assetCode: 'USD', - assetScale: 2 + assetScale: 9 }) }) }) @@ -332,37 +321,27 @@ describe('Wallet Address Service', () => { }) }) - describe('Sum By Wallet AddressId', () => { - it('should return undefined by zero sum', async () => { - await prepareWADependencies('my-wallet', true, { - assetCode: 'USD', - assetScale: 2, - isWM: true - }) - - const result = await waService.processWMWalletAddresses() - expect(result).toBeUndefined() - }) - - it('should return undefined by non zero sum', async () => { - prepareWSDepsMock(1000n) - - await prepareWADependencies('my-wallet', true, { - assetCode: 'USD', - assetScale: 2, - isWM: true - }) - - const result = await waService.processWMWalletAddresses() - expect(result).toBeUndefined() - }) - - it('should throw missing assetCode err', async () => { - await prepareWADependencies('my-wallet', true, { isWM: true }) - - await expect(waService.processWMWalletAddresses()).rejects.toThrowError( - /Error while processing WM payment pointers/ - ) - }) + describe('Sum By Wallet AddressId Since', () => { + it('should complete without errors for zero sum', async () => { + await prepareWADependencies('my-wallet', true); + + await expect(waService.keepBalancesSynced(new Date(0))).resolves.toBeUndefined(); + }); + + it('should complete without errors for non-zero sum', async () => { + prepareWSDepsMock(1000n); + + await prepareWADependencies('my-wallet', true); + + await expect(waService.keepBalancesSynced(new Date(0))).resolves.toBeUndefined(); + }); + + it('should throw missing assetCode error', async () => { + await prepareWADependencies('my-wallet', true); + + await expect(waService.keepBalancesSynced(new Date(0))).rejects.toThrowError( + /Error while processing payment pointers/ + ); + }); }) }) diff --git a/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx b/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx index 7c0d4c57c..151e4cb91 100644 --- a/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx +++ b/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx @@ -19,7 +19,6 @@ import { WalletAddressResponse } from '@wallet/shared/src' type WalletAddressCardProps = { walletAddress: WalletAddressResponse - isWM: boolean idOnboarding?: string } @@ -61,7 +60,6 @@ WalletAddressCardButton.displayName = 'WalletAddressCardButton' export const WalletAddressCard = ({ walletAddress, - isWM, idOnboarding }: WalletAddressCardProps) => { return ( @@ -69,11 +67,7 @@ export const WalletAddressCard = ({
{walletAddress.url}
- {isWM ? ( - - {formattedAmount(walletAddress).amount} - - ) : ( + View - )} + & { accountName: string @@ -71,11 +69,9 @@ export const CreateWalletAddressDialog = ({
-
{ - data.isWM = isWebMonetization ? true : data.isWM const response = await walletAddressService.create( accountId, data @@ -135,14 +131,6 @@ export const CreateWalletAddressDialog = ({ } {...createWalletAddressForm.register('publicName')} /> - { - if (isWebMonetization) e.preventDefault() - }} - {...createWalletAddressForm.register('isWM')} - />
)} - - {({ selected }) => ( -
- Web Monetization -
-
- )} -
- - -
- -
-

Balance

-

- {formattedAmount.amount} -

-
+ +
+ +
+

Balance

+

+ {formattedAmounts.amountScale2.amount} +

+

+ {formattedAmounts.amountScale9.amount} +

-
-
- - { - if (isUserFirstTime) { - setRunOnboarding(false) - } - openDialog( - - ) - }} - className="group flex aspect-square h-24 w-24 flex-col items-center justify-center rounded-lg border border-green-5 bg-white shadow-md hover:border-green-6" - > - - - Add money - - - - openDialog( - - ) +
+
+
+
-
-

- Payment Pointers -

-
-
- {allWalletAddresses.walletAddresses.length > 0 ? ( - allWalletAddresses.walletAddresses.map( - (walletAddress, index) => ( - - ) + openDialog( + + ); + }} + className="group flex aspect-square h-24 w-24 flex-col items-center justify-center -space-y-1 rounded-lg border border-green-5 bg-white shadow-md hover:border-green-6" + > + +
+

+ Add payment{' '} +

+

+ pointer +

+
+ + { + if (isUserFirstTime) { + setRunOnboarding(false); + } + openDialog( + + ); + }} + className="group flex aspect-square h-24 w-24 flex-col items-center justify-center rounded-lg border border-green-5 bg-white shadow-md hover:border-green-6" + > + + + Add money + + + + openDialog( + ) - ) : ( -
- No payment pointers found for this account. -
- )} -
+ } + className="group flex aspect-square h-24 w-24 flex-col items-center justify-center rounded-lg border border-green-5 bg-white shadow-md hover:border-green-6" + > + + + Withdraw + + + + + + Exchange + +
- - - {account.assetCode === 'USD' ? ( - <> -
- -
-

Balance

-

- {balance.amount} -

-
-
-
- -
-
-
-

- Account -

-
-
- - {account.name} - - - {formattedAmount.symbol} - -
-
- {allWalletAddresses.wmWalletAddresses.length > 0 ? ( - allWalletAddresses.wmWalletAddresses.map( - (walletAddress) => ( - - ) - ) - ) : ( -
- - No web monetization payment pointers found for this - account. - -
- )} -
+
+

+ Account +

+
+
+ {account.name} + + {formattedAmounts.amountScale2.symbol} + +
+
+ {allWalletAddresses.length > 0 ? ( + allWalletAddresses.map((walletAddress, index) => ( + + )) + ) : ( +
+ No payment pointers found for this account.
- - ) : ( - - )} - - + )} +
+
+
- ) + ) } const querySchema = z.object({ @@ -349,12 +268,9 @@ export const getServerSideProps: GetServerSideProps<{ let balance = 0 - walletAddressesResponse.result.walletAddresses.map((pp) => { - pp.url = replaceWalletAddressProtocol(pp.url) - }) - walletAddressesResponse.result.wmWalletAddresses.map((pp) => { + walletAddressesResponse.result.map((pp) => { pp.url = replaceWalletAddressProtocol(pp.url) - balance += Number(pp.incomingBalance) + balance += Number(pp.incomingBalance) - Number(pp.outgoingBalance) }) return { diff --git a/packages/wallet/frontend/src/pages/account/create.tsx b/packages/wallet/frontend/src/pages/account/create.tsx index 800432a27..57d4da591 100644 --- a/packages/wallet/frontend/src/pages/account/create.tsx +++ b/packages/wallet/frontend/src/pages/account/create.tsx @@ -28,7 +28,7 @@ const CreateAccountPage: NextPageWithLayout = ({ const { isUserFirstTime, setRunOnboarding, stepIndex, setStepIndex } = useOnboardingContext() const defaultValue = { - asset: assets.find((asset) => asset.label === 'EUR') + asset: assets.find((asset) => asset.label === 'USD') } const createAccountForm = useZodForm({ @@ -138,7 +138,7 @@ export const getServerSideProps: GetServerSideProps<{ } const assets = response.result - ?.filter((asset) => asset.scale <= 2) + ?.filter((asset) => asset.scale <= 9 ) ?.map((asset) => ({ value: asset.id, label: asset.code diff --git a/packages/wallet/frontend/src/pages/index.tsx b/packages/wallet/frontend/src/pages/index.tsx index 7568e8c7b..522a1e11f 100644 --- a/packages/wallet/frontend/src/pages/index.tsx +++ b/packages/wallet/frontend/src/pages/index.tsx @@ -107,7 +107,7 @@ const HomePage: NextPageWithLayout = ({ accounts, user }) => { ))}
diff --git a/packages/wallet/frontend/src/pages/transfer/request.tsx b/packages/wallet/frontend/src/pages/transfer/request.tsx index 6550fc8c2..23a0b3fdf 100644 --- a/packages/wallet/frontend/src/pages/transfer/request.tsx +++ b/packages/wallet/frontend/src/pages/transfer/request.tsx @@ -104,7 +104,7 @@ const RequestPage: NextPageWithLayout = ({ accounts }) => { return } - const walletAddresses = walletAddressesResponse.result.walletAddresses.map( + const walletAddresses = walletAddressesResponse.result.map( (walletAddress) => ({ label: `${walletAddress.publicName} (${replaceWalletAddressProtocol(walletAddress.url)})`, value: walletAddress.id, diff --git a/packages/wallet/frontend/src/pages/transfer/send.tsx b/packages/wallet/frontend/src/pages/transfer/send.tsx index 39eea66d5..76a2261c4 100644 --- a/packages/wallet/frontend/src/pages/transfer/send.tsx +++ b/packages/wallet/frontend/src/pages/transfer/send.tsx @@ -113,7 +113,7 @@ const SendPage: NextPageWithLayout = ({ accounts }) => { return } - const walletAddresses = walletAddressesResponse.result.walletAddresses.map( + const walletAddresses = walletAddressesResponse.result.map( (walletAddress) => ({ label: `${walletAddress.publicName} (${replaceWalletAddressProtocol(walletAddress.url)})`, value: walletAddress.id diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index 638104a64..5fba4e0a4 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -45,8 +45,10 @@ export const formatAmount = (args: FormatAmountArgs): FormattedAmount => { maximumFractionDigits: assetScale, minimumFractionDigits: assetScale }) + //TODO make this work properly + const numberValue = Number(value) / Math.pow(10, assetScale); - const amount = formatter.format(Number(`${value}e-${assetScale}`)) + const amount = formatter.format(numberValue) const symbol = getCurrencySymbol(assetCode) return { From ee0bb17db6f555162c977faebd8960f65f14f235 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 27 Jun 2024 12:03:17 +0300 Subject: [PATCH 02/58] Format --- .../wallet/backend/src/account/service.ts | 5 +- packages/wallet/backend/src/app.ts | 2 +- packages/wallet/backend/src/rafiki/service.ts | 3 +- .../wallet/backend/src/rapyd/controller.ts | 2 +- .../wallet/backend/src/transaction/service.ts | 19 ++++--- packages/wallet/backend/src/user/service.ts | 4 +- .../backend/src/walletAddress/controller.ts | 2 +- .../backend/src/walletAddress/service.ts | 23 +++------ .../backend/src/walletAddress/validation.ts | 2 +- .../tests/walletAddress/controller.test.ts | 4 +- .../tests/walletAddress/service.test.ts | 50 ++++++++++--------- .../components/cards/WalletAddressCard.tsx | 17 +++---- .../frontend/src/lib/api/walletAddress.ts | 2 +- .../src/pages/account/[accountId].tsx | 12 ++--- .../frontend/src/pages/account/create.tsx | 2 +- packages/wallet/frontend/src/utils/helpers.ts | 2 +- 16 files changed, 77 insertions(+), 74 deletions(-) diff --git a/packages/wallet/backend/src/account/service.ts b/packages/wallet/backend/src/account/service.ts index fabd0ccd3..96ed86a4d 100644 --- a/packages/wallet/backend/src/account/service.ts +++ b/packages/wallet/backend/src/account/service.ts @@ -218,7 +218,10 @@ export class AccountService implements IAccountService { ) } - async getVirtualAccountBalance(userId: string, assetCode: string): Promise { + async getVirtualAccountBalance( + userId: string, + assetCode: string + ): Promise { const account = await Account.query() .where('userId', userId) .where('assetCode', assetCode) diff --git a/packages/wallet/backend/src/app.ts b/packages/wallet/backend/src/app.ts index 2a4bed3dc..47a8628b5 100644 --- a/packages/wallet/backend/src/app.ts +++ b/packages/wallet/backend/src/app.ts @@ -347,7 +347,7 @@ export class App { return false }) .then((trx) => { - const newTimestamp = new Date(); + const newTimestamp = new Date() if (trx) { process.nextTick(() => this.keepBalancesSynced(newTimestamp)) } else { diff --git a/packages/wallet/backend/src/rafiki/service.ts b/packages/wallet/backend/src/rafiki/service.ts index 9032751b6..ff31d1be2 100644 --- a/packages/wallet/backend/src/rafiki/service.ts +++ b/packages/wallet/backend/src/rafiki/service.ts @@ -82,7 +82,7 @@ export class RafikiService implements IRafikiService { private logger: Logger, private rafikiClient: RafikiClient, private transactionService: TransactionService, - private walletAddressService: WalletAddressService, + private walletAddressService: WalletAddressService ) {} public async onWebHook(wh: WebHook): Promise { @@ -339,7 +339,6 @@ export class RafikiService implements IRafikiService { const sentAmount = this.parseAmount(wh.data.sentAmount as AmountJSON) - const source_ewallet = await this.getRapydWalletId(walletAddress) const releaseResult = await this.rapydClient.releaseLiquidity({ diff --git a/packages/wallet/backend/src/rapyd/controller.ts b/packages/wallet/backend/src/rapyd/controller.ts index 88d939711..7e52be218 100644 --- a/packages/wallet/backend/src/rapyd/controller.ts +++ b/packages/wallet/backend/src/rapyd/controller.ts @@ -96,7 +96,7 @@ export class RapydController implements IRapydController { accountId: defaultAccount.id, walletAddressName, publicName: 'Default Payment Pointer', - userId: id, + userId: id }) } diff --git a/packages/wallet/backend/src/transaction/service.ts b/packages/wallet/backend/src/transaction/service.ts index 2699a4069..cb64b76ac 100644 --- a/packages/wallet/backend/src/transaction/service.ts +++ b/packages/wallet/backend/src/transaction/service.ts @@ -1,5 +1,10 @@ import { Transaction, TransactionType } from './model' -import { OrderByDirection, Page, PartialModelObject, TransactionOrKnex } from 'objection' +import { + OrderByDirection, + Page, + PartialModelObject, + TransactionOrKnex +} from 'objection' import { AccountService } from '@/account/service' import { Logger } from 'winston' import { PaginationQueryParams } from '@/shared/types' @@ -172,11 +177,13 @@ export class TransactionService implements ITransactionService { trx?: TransactionOrKnex ) { //TODO updatedAt instead of createdAt? - const transactions = await Transaction.query(trx).where({ - walletAddressId, - type, - status: 'COMPLETED' - }).andWhere('createdAt', '>', since); + const transactions = await Transaction.query(trx) + .where({ + walletAddressId, + type, + status: 'COMPLETED' + }) + .andWhere('createdAt', '>', since) const ids = transactions.map(({ id }) => id) const sumResult = (await Transaction.query(trx) diff --git a/packages/wallet/backend/src/user/service.ts b/packages/wallet/backend/src/user/service.ts index 10070152f..ed4269a30 100644 --- a/packages/wallet/backend/src/user/service.ts +++ b/packages/wallet/backend/src/user/service.ts @@ -149,14 +149,14 @@ export class UserService implements IUserService { accountId: walletInfo.defaultAccount.id, walletAddressName: typedArray[0].toString(16), publicName: 'Default Payment Pointer', - userId: walletInfo.createdUser.id, + userId: walletInfo.createdUser.id }) const boutiqueWallet = await this.walletAddressService.create({ accountId: boutiqueInfo.defaultAccount.id, walletAddressName: 'boutique', publicName: 'Default Payment Pointer', - userId: boutiqueInfo.createdUser.id, + userId: boutiqueInfo.createdUser.id }) await this.walletAddressKeyService.registerKey({ diff --git a/packages/wallet/backend/src/walletAddress/controller.ts b/packages/wallet/backend/src/walletAddress/controller.ts index ddcedd18d..314e7c53b 100644 --- a/packages/wallet/backend/src/walletAddress/controller.ts +++ b/packages/wallet/backend/src/walletAddress/controller.ts @@ -36,7 +36,7 @@ export class WalletAddressController implements IWalletAddressController { userId, accountId, walletAddressName, - publicName, + publicName }) res.status(200).json(toSuccessResponse(walletAddress)) } catch (e) { diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index 294880331..2c47bc25c 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -68,7 +68,7 @@ export const createWalletAddressIfFalsy = async ({ userId, accountId, walletAddressName: getRandomValues(new Uint32Array(1))[0].toString(16), - publicName, + publicName }) return newWalletAddress @@ -82,8 +82,7 @@ export class WalletAddressService implements IWalletAddressService { private transactionService: TransactionService, private rapydClient: RapydClient, private logger: Logger - ) { - } + ) {} async create(args: CreateWalletAddressArgs): Promise { const account = await this.accountService.findAccountById( @@ -279,9 +278,7 @@ export class WalletAddressService implements IWalletAddressService { ) } - this.logger.debug( - `Passed first throw` - ) + this.logger.debug(`Passed first throw`) // 10000000 is 0.01 i.e. one cent in asset scale 9 // One cent is the lowest number that can be represented in asset scale 2 by Rapyd @@ -299,9 +296,7 @@ export class WalletAddressService implements IWalletAddressService { ) } - this.logger.debug( - `Passed second throw` - ) + this.logger.debug(`Passed second throw`) let destination = walletAddress.account.user.rapydWalletId let source = this.env.RAPYD_SETTLEMENT_EWALLET @@ -325,9 +320,7 @@ export class WalletAddressService implements IWalletAddressService { debt: raw('?? + ?', ['debt', amount]) }) - this.logger.debug( - `Early return` - ) + this.logger.debug(`Early return`) return } @@ -338,10 +331,8 @@ export class WalletAddressService implements IWalletAddressService { ) } - this.logger.debug( - `Passed third throw` - ) - + this.logger.debug(`Passed third throw`) + const updatedField: keyof Pick< PartialModelObject, 'incomingBalance' | 'outgoingBalance' diff --git a/packages/wallet/backend/src/walletAddress/validation.ts b/packages/wallet/backend/src/walletAddress/validation.ts index 0f032d615..7c63933c4 100644 --- a/packages/wallet/backend/src/walletAddress/validation.ts +++ b/packages/wallet/backend/src/walletAddress/validation.ts @@ -44,7 +44,7 @@ export const walletAddressSchema = z.object({ publicName: z .string() .trim() - .min(3, { message: 'Public name must be at least 3 characters long' }), + .min(3, { message: 'Public name must be at least 3 characters long' }) }) }) diff --git a/packages/wallet/backend/tests/walletAddress/controller.test.ts b/packages/wallet/backend/tests/walletAddress/controller.test.ts index ca96f2f20..bdff93e83 100644 --- a/packages/wallet/backend/tests/walletAddress/controller.test.ts +++ b/packages/wallet/backend/tests/walletAddress/controller.test.ts @@ -135,7 +135,7 @@ describe('Wallet Address', () => { } req.body = { walletAddressName: faker.lorem.slug(), - publicName: faker.lorem.words({ min: 2, max: 2 }), + publicName: faker.lorem.words({ min: 2, max: 2 }) } await walletAddressController.create(req, res, next) expect(res.statusCode).toBe(200) @@ -155,7 +155,7 @@ describe('Wallet Address', () => { } req.body = { walletAddressName: faker.lorem.slug(), - publicName: faker.lorem.words({ min: 2, max: 2 }), + publicName: faker.lorem.words({ min: 2, max: 2 }) } await walletAddressController.create(req, res, (err) => { next() diff --git a/packages/wallet/backend/tests/walletAddress/service.test.ts b/packages/wallet/backend/tests/walletAddress/service.test.ts index 9df161475..5381007a4 100644 --- a/packages/wallet/backend/tests/walletAddress/service.test.ts +++ b/packages/wallet/backend/tests/walletAddress/service.test.ts @@ -29,7 +29,7 @@ describe('Wallet Address Service', () => { const prepareWADependencies = async ( paymentPointerName: string, - isAccountAssigned = true, + isAccountAssigned = true ) => { let extraAcc = {} as Account if (!isAccountAssigned) @@ -57,7 +57,7 @@ describe('Wallet Address Service', () => { accountId: isAccountAssigned ? account.id : extraAcc.id, id: faker.string.uuid(), assetCode: undefined, - assetScale: 9, + assetScale: 9 }) return { @@ -138,7 +138,7 @@ describe('Wallet Address Service', () => { userId, accountId: account.id, walletAddressName: 'my-wallet', - publicName: 'My Wallet', + publicName: 'My Wallet' }) expect(result).toHaveProperty('publicName') expect(result).toHaveProperty('accountId') @@ -155,7 +155,7 @@ describe('Wallet Address Service', () => { userId, accountId: account.id, walletAddressName: 'my-wallet', - publicName: 'My Wallet', + publicName: 'My Wallet' }) expect(result).toHaveProperty('publicName') expect(result).toHaveProperty('accountId') @@ -173,7 +173,7 @@ describe('Wallet Address Service', () => { userId, accountId: account.id, walletAddressName: 'my-work', - publicName: 'My Work', + publicName: 'My Work' }) ).rejects.toThrowError( /This payment pointer already exists. Please choose another name./ @@ -323,25 +323,29 @@ describe('Wallet Address Service', () => { describe('Sum By Wallet AddressId Since', () => { it('should complete without errors for zero sum', async () => { - await prepareWADependencies('my-wallet', true); - - await expect(waService.keepBalancesSynced(new Date(0))).resolves.toBeUndefined(); - }); - + await prepareWADependencies('my-wallet', true) + + await expect( + waService.keepBalancesSynced(new Date(0)) + ).resolves.toBeUndefined() + }) + it('should complete without errors for non-zero sum', async () => { - prepareWSDepsMock(1000n); - - await prepareWADependencies('my-wallet', true); - - await expect(waService.keepBalancesSynced(new Date(0))).resolves.toBeUndefined(); - }); - + prepareWSDepsMock(1000n) + + await prepareWADependencies('my-wallet', true) + + await expect( + waService.keepBalancesSynced(new Date(0)) + ).resolves.toBeUndefined() + }) + it('should throw missing assetCode error', async () => { - await prepareWADependencies('my-wallet', true); - - await expect(waService.keepBalancesSynced(new Date(0))).rejects.toThrowError( - /Error while processing payment pointers/ - ); - }); + await prepareWADependencies('my-wallet', true) + + await expect( + waService.keepBalancesSynced(new Date(0)) + ).rejects.toThrowError(/Error while processing payment pointers/) + }) }) }) diff --git a/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx b/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx index 151e4cb91..372fe1747 100644 --- a/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx +++ b/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx @@ -67,15 +67,14 @@ export const WalletAddressCard = ({
{walletAddress.url}
- - - View - - + + View + + = ({

{formattedAmounts.amountScale2.amount}

-

+

{formattedAmounts.amountScale9.amount}

@@ -129,14 +129,14 @@ const AccountPage: NextPageWithLayout = ({ id="walletAddress" onClick={() => { if (isUserFirstTime) { - setRunOnboarding(false); + setRunOnboarding(false) } openDialog( - ); + ) }} className="group flex aspect-square h-24 w-24 flex-col items-center justify-center -space-y-1 rounded-lg border border-green-5 bg-white shadow-md hover:border-green-6" > @@ -154,14 +154,14 @@ const AccountPage: NextPageWithLayout = ({ id="fund" onClick={() => { if (isUserFirstTime) { - setRunOnboarding(false); + setRunOnboarding(false) } openDialog( - ); + ) }} className="group flex aspect-square h-24 w-24 flex-col items-center justify-center rounded-lg border border-green-5 bg-white shadow-md hover:border-green-6" > @@ -231,7 +231,7 @@ const AccountPage: NextPageWithLayout = ({ - ) + ) } const querySchema = z.object({ diff --git a/packages/wallet/frontend/src/pages/account/create.tsx b/packages/wallet/frontend/src/pages/account/create.tsx index 57d4da591..b62099332 100644 --- a/packages/wallet/frontend/src/pages/account/create.tsx +++ b/packages/wallet/frontend/src/pages/account/create.tsx @@ -138,7 +138,7 @@ export const getServerSideProps: GetServerSideProps<{ } const assets = response.result - ?.filter((asset) => asset.scale <= 9 ) + ?.filter((asset) => asset.scale <= 9) ?.map((asset) => ({ value: asset.id, label: asset.code diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index 5fba4e0a4..ab7a2273a 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -46,7 +46,7 @@ export const formatAmount = (args: FormatAmountArgs): FormattedAmount => { minimumFractionDigits: assetScale }) //TODO make this work properly - const numberValue = Number(value) / Math.pow(10, assetScale); + const numberValue = Number(value) / Math.pow(10, assetScale) const amount = formatter.format(numberValue) const symbol = getCurrencySymbol(assetCode) From da749f55cb0a1f11c417dd854c8fd258f76111f7 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 27 Jun 2024 13:26:37 +0300 Subject: [PATCH 03/58] Add Rapyd threshold as env var --- docker/dev/docker-compose.yml | 1 + docker/prod/.env.example | 2 +- docker/prod/docker-compose.yml | 1 + packages/wallet/backend/src/config/env.ts | 1 + .../wallet/backend/src/walletAddress/service.ts | 15 ++++----------- 5 files changed, 8 insertions(+), 12 deletions(-) diff --git a/docker/dev/docker-compose.yml b/docker/dev/docker-compose.yml index 670d3975f..870932fdf 100644 --- a/docker/dev/docker-compose.yml +++ b/docker/dev/docker-compose.yml @@ -54,6 +54,7 @@ services: RATE_API_KEY: ${RATE_API_KEY} BASE_ASSET_SCALE: 2 MAX_ASSET_SCALE: 9 + RAPYD_THRESHOLD: 10000000 # 0.01 DEBT_THRESHOLD: 5 REDIS_URL: redis://redis:6379/0 restart: always diff --git a/docker/prod/.env.example b/docker/prod/.env.example index 9d6b62958..78ccb7b20 100644 --- a/docker/prod/.env.example +++ b/docker/prod/.env.example @@ -33,7 +33,7 @@ WALLET_BACKEND_AUTH_DOMAIN= WALLET_BACKEND_RATE_API_KEY= WALLET_BACKEND_BASE_ASSET_SCALE= WALLET_BACKEND_MAX_ASSET_SCALE= -WALLET_BACKEND_WM_THRESHOLD= +WALLET_BACKEND_RAPYD_THRESHOLD= WALLET_BACKEND_DEBT_THRESHOLD= # BOUTIQUE diff --git a/docker/prod/docker-compose.yml b/docker/prod/docker-compose.yml index 581c38d6e..c1724997b 100644 --- a/docker/prod/docker-compose.yml +++ b/docker/prod/docker-compose.yml @@ -67,6 +67,7 @@ services: RATE_API_KEY: ${WALLET_BACKEND_RATE_API_KEY} BASE_ASSET_SCALE: ${WALLET_BACKEND_BASE_ASSET_SCALE} MAX_ASSET_SCALE: ${WALLET_BACKEND_MAX_ASSET_SCALE} + RAPYD_THRESHOLD: ${WALLET_BACKEND_RAPYD_THRESHOLD} DEBT_THRESHOLD: ${WALLET_BACKEND_DEBT_THRESHOLD} REDIS_URL: ${WALLET_BACKEND_REDIS_URL} networks: diff --git a/packages/wallet/backend/src/config/env.ts b/packages/wallet/backend/src/config/env.ts index 2fbe35270..4c25a4a69 100644 --- a/packages/wallet/backend/src/config/env.ts +++ b/packages/wallet/backend/src/config/env.ts @@ -34,6 +34,7 @@ const envSchema = z.object({ .transform((value) => value === 'true'), BASE_ASSET_SCALE: z.coerce.number().nonnegative().default(2), MAX_ASSET_SCALE: z.coerce.number().nonnegative().default(9), + RAPYD_THRESHOLD: z.coerce.bigint().nonnegative().default(10_000_000n), // $0.01 in asset scale 9 DEBT_THRESHOLD: z.coerce.number().multipleOf(0.01).nonnegative().default(5.0), // $5.00 DEFAULT_WALLET_ACCOUNT: z .object({ diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index 2c47bc25c..96e221bdc 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -280,12 +280,9 @@ export class WalletAddressService implements IWalletAddressService { this.logger.debug(`Passed first throw`) - // 10000000 is 0.01 i.e. one cent in asset scale 9 - // One cent is the lowest number that can be represented in asset scale 2 by Rapyd - const rapydMinRepresentation = 10000000n const amount = Number( ( - Number(balance * rapydMinRepresentation) * + Number(balance * this.env.RAPYD_THRESHOLD) * 10 ** -walletAddress.assetScale ).toPrecision(2) ) @@ -340,7 +337,7 @@ export class WalletAddressService implements IWalletAddressService { const updatePart: PartialModelObject = { [updatedField]: raw('?? - ?', [ updatedField, - rapydMinRepresentation * balance + this.env.RAPYD_THRESHOLD * balance ]) } @@ -400,14 +397,10 @@ export class WalletAddressService implements IWalletAddressService { outgoingBalance: raw('?? + ?', ['outgoingBalance', outgoing.sum]) }) - // 10000000 is 0.01 i.e. one cent in asset scale 9 - // One cent is the lowest number that can be represented in asset scale 2 by Rapyd - const rapydMinRepresentation = 10000000n - const incomingBalance = - tmpWalletAddress.incomingBalance / rapydMinRepresentation + tmpWalletAddress.incomingBalance / this.env.RAPYD_THRESHOLD const outgoingBalance = - tmpWalletAddress.outgoingBalance / rapydMinRepresentation + tmpWalletAddress.outgoingBalance / this.env.RAPYD_THRESHOLD this.logger.debug( `Incoming balance: ${incomingBalance}. Outgoing balance: ${outgoingBalance}` From 261ce75b02b4fb3a46ad0aecec82f2f265ca2c81 Mon Sep 17 00:00:00 2001 From: Tymmmy <117268143+Tymmmy@users.noreply.github.com> Date: Thu, 27 Jun 2024 15:15:11 +0300 Subject: [PATCH 04/58] Frontend fixes for WM PPs --- .../components/cards/WalletAddressCard.tsx | 8 - .../src/components/onboarding/Onboarding.tsx | 6 +- .../frontend/src/lib/api/walletAddress.ts | 8 +- .../src/pages/account/[accountId].tsx | 255 ++++++++---------- .../frontend/src/pages/account/create.tsx | 4 +- packages/wallet/frontend/src/pages/index.tsx | 2 +- .../wallet/shared/src/types/walletAddress.ts | 5 - 7 files changed, 115 insertions(+), 173 deletions(-) diff --git a/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx b/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx index 372fe1747..e8e166f25 100644 --- a/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx +++ b/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx @@ -14,7 +14,6 @@ import { PencilSquare } from '../icons/Pencil' import { Trash } from '../icons/Trash' import { EditWalletAddressDialog } from '../dialogs/EditWalletAddressDialog' import { CopyButton } from '@/ui/CopyButton' -import { formatAmount } from '@/utils/helpers' import { WalletAddressResponse } from '@wallet/shared/src' type WalletAddressCardProps = { @@ -25,13 +24,6 @@ type WalletAddressCardProps = { type WalletAddressCardButtonProps = ButtonOrLinkProps & { ['aria-label']: string } -const formattedAmount = (walletAddress: WalletAddressResponse) => { - return formatAmount({ - value: String(walletAddress.incomingBalance) || '', - assetCode: walletAddress.assetCode || '', - assetScale: walletAddress.assetScale || 2 - }) -} const WalletAddressCardButton = forwardRef< HTMLButtonElement | HTMLAnchorElement, diff --git a/packages/wallet/frontend/src/components/onboarding/Onboarding.tsx b/packages/wallet/frontend/src/components/onboarding/Onboarding.tsx index fd95d8c72..8b9a9ac6f 100644 --- a/packages/wallet/frontend/src/components/onboarding/Onboarding.tsx +++ b/packages/wallet/frontend/src/components/onboarding/Onboarding.tsx @@ -44,7 +44,7 @@ export const ONBOARDING_STEPS: StepWithIcon[] = [ // 2 target: '#createAccountForm', content: - 'All accounts need a name, so please add a name for your new USD account.', + 'All accounts need a name, so please add a name for your new EUR account.', placement: 'center', disableOverlayClose: true, Icon: Person @@ -203,8 +203,8 @@ export const ONBOARDING_STEPS: StepWithIcon[] = [ }, { // 21 - target: '#usdAccount', - content: 'Go inside your USD account.', + target: '#eurAccount', + content: 'Go inside your EUR account.', disableOverlayClose: true, spotlightClicks: true, Icon: Euro diff --git a/packages/wallet/frontend/src/lib/api/walletAddress.ts b/packages/wallet/frontend/src/lib/api/walletAddress.ts index 96dd36bbb..b9bf282a7 100644 --- a/packages/wallet/frontend/src/lib/api/walletAddress.ts +++ b/packages/wallet/frontend/src/lib/api/walletAddress.ts @@ -5,11 +5,7 @@ import { type ErrorResponse, type SuccessResponse } from '../httpClient' -import { - ListWalletAddressesResponse, - WalletAddressResponse -} from '@wallet/shared/src' -import { WalletAddressOP } from '@wallet/shared' +import { WalletAddressOP, WalletAddressResponse } from '@wallet/shared/src' export const createWalletAddressSchema = z.object({ walletAddressName: z.string().toLowerCase().min(3, { @@ -53,7 +49,7 @@ type GetWalletAddressArgs = { accountId: string; walletAddressId: string } type GetWalletAddressResult = SuccessResponse type GetWalletAddressResponse = GetWalletAddressResult | ErrorResponse -type ListWalletAddressResult = SuccessResponse +type ListWalletAddressResult = SuccessResponse type ListWalletAddressResponse = ListWalletAddressResult | ErrorResponse type ListAllWalletAddressResult = SuccessResponse diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index ac34b0f58..9c346b819 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -27,19 +27,16 @@ import { useEffect } from 'react' import { z } from 'zod' import { useSnapshot } from 'valtio' import { balanceState } from '@/lib/balance' -import { BackButton } from '@/components/BackButton' -import { Tab } from '@headlessui/react' -import { cx } from 'class-variance-authority' import { PageHeader } from '@/components/PageHeader' -import { ListWalletAddressesResponse } from '@wallet/shared/src' +import { WalletAddressResponse } from '@wallet/shared/src' type AccountPageProps = InferGetServerSidePropsType const AccountPage: NextPageWithLayout = ({ account, - allWalletAddresses, + allWalletAddresses //TODO add this to account.balance - balance + // balance }) => { const [openDialog, closeDialog] = useDialog() const { accountsSnapshot } = useSnapshot(balanceState) @@ -81,155 +78,117 @@ const AccountPage: NextPageWithLayout = ({ // eslint-disable-next-line react-hooks/exhaustive-deps }, []) - //TODO center Account tab? return ( <> - - -
- - {({ selected }) => ( -
- Account -
-
- )} - -
- - -
- -
-

Balance

-

- {formattedAmounts.amountScale2.amount} +

+

Balance

+
+ {formattedAmounts.amountScale2.amount} +
+
+ {formattedAmounts.amountScale9.amount} +
+
+
+
+
-
-
- - { - if (isUserFirstTime) { - setRunOnboarding(false) - } - openDialog( - - ) - }} - className="group flex aspect-square h-24 w-24 flex-col items-center justify-center rounded-lg border border-green-5 bg-white shadow-md hover:border-green-6" - > - - - Add money - - - - openDialog( - - ) + + { + if (isUserFirstTime) { + setRunOnboarding(false) + } + openDialog( + + ) + }} + className="group flex aspect-square h-24 w-24 flex-col items-center justify-center rounded-lg border border-green-5 bg-white shadow-md hover:border-green-6" + > + + + Add money + + + + openDialog( + + ) + } + className="group flex aspect-square h-24 w-24 flex-col items-center justify-center rounded-lg border border-green-5 bg-white shadow-md hover:border-green-6" + > + + + Withdraw + + + + + + Exchange + + +
+
+

+ Account +

+
+
+ {account.name} + + {formattedAmounts.amountScale2.symbol} + +
+
+ {allWalletAddresses.length > 0 ? ( + allWalletAddresses.map((walletAddress, index) => ( + - - - Withdraw - - - - - - Exchange - - + /> + )) + ) : ( +
+ No payment pointers found for this account.
-
-

- Account -

-
-
- {account.name} - - {formattedAmounts.amountScale2.symbol} - -
-
- {allWalletAddresses.length > 0 ? ( - allWalletAddresses.map((walletAddress, index) => ( - - )) - ) : ( -
- No payment pointers found for this account. -
- )} -
-
- - + )} +
+
) } @@ -240,7 +199,7 @@ const querySchema = z.object({ export const getServerSideProps: GetServerSideProps<{ account: Account - allWalletAddresses: ListWalletAddressesResponse + allWalletAddresses: WalletAddressResponse[] balance: FormattedAmount }> = async (ctx) => { const result = querySchema.safeParse(ctx.query) diff --git a/packages/wallet/frontend/src/pages/account/create.tsx b/packages/wallet/frontend/src/pages/account/create.tsx index b62099332..31e4efd70 100644 --- a/packages/wallet/frontend/src/pages/account/create.tsx +++ b/packages/wallet/frontend/src/pages/account/create.tsx @@ -18,7 +18,7 @@ import { Controller } from 'react-hook-form' import { NextPageWithLayout } from '@/lib/types/app' import { useOnboardingContext } from '@/lib/context/onboarding' import { useEffect } from 'react' -import { createAccountSchema } from '@wallet/shared' +import { createAccountSchema } from '@wallet/shared/src' type CreateAccountProps = InferGetServerSidePropsType const CreateAccountPage: NextPageWithLayout = ({ @@ -28,7 +28,7 @@ const CreateAccountPage: NextPageWithLayout = ({ const { isUserFirstTime, setRunOnboarding, stepIndex, setStepIndex } = useOnboardingContext() const defaultValue = { - asset: assets.find((asset) => asset.label === 'USD') + asset: assets.find((asset) => asset.label === 'EUR') } const createAccountForm = useZodForm({ diff --git a/packages/wallet/frontend/src/pages/index.tsx b/packages/wallet/frontend/src/pages/index.tsx index 522a1e11f..7568e8c7b 100644 --- a/packages/wallet/frontend/src/pages/index.tsx +++ b/packages/wallet/frontend/src/pages/index.tsx @@ -107,7 +107,7 @@ const HomePage: NextPageWithLayout = ({ accounts, user }) => { ))}
diff --git a/packages/wallet/shared/src/types/walletAddress.ts b/packages/wallet/shared/src/types/walletAddress.ts index 6a54a6a5e..14c9aa1ad 100644 --- a/packages/wallet/shared/src/types/walletAddress.ts +++ b/packages/wallet/shared/src/types/walletAddress.ts @@ -16,11 +16,6 @@ export interface WalletAddressResponse extends IWalletAddressResponse { keys: WalletAddressKeyResponse[] } -export interface ListWalletAddressesResponse { - wmWalletAddresses: Array - walletAddresses: Array -} - export type WalletAddressOP = AssetOP & { id: string publicName: string From a06af493cf655579474a22cd6d60fa30f42c4cfb Mon Sep 17 00:00:00 2001 From: Tymmmy <117268143+Tymmmy@users.noreply.github.com> Date: Thu, 27 Jun 2024 15:17:19 +0300 Subject: [PATCH 05/58] Update [accountId].tsx --- packages/wallet/frontend/src/pages/account/[accountId].tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index 9c346b819..614a2dfe6 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -81,7 +81,7 @@ const AccountPage: NextPageWithLayout = ({ return ( <> -
+

Balance

{formattedAmounts.amountScale2.amount} From 2078190afb5a668d0a0a029ea6114b5e551e6fb0 Mon Sep 17 00:00:00 2001 From: Tymmmy <117268143+Tymmmy@users.noreply.github.com> Date: Thu, 27 Jun 2024 16:06:36 +0300 Subject: [PATCH 06/58] Update [accountId].tsx --- .../wallet/frontend/src/pages/account/[accountId].tsx | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index 614a2dfe6..a428edac4 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -160,15 +160,9 @@ const AccountPage: NextPageWithLayout = ({

- Account + Payment Pointers

-
- {account.name} - - {formattedAmounts.amountScale2.symbol} - -
{allWalletAddresses.length > 0 ? ( allWalletAddresses.map((walletAddress, index) => ( From c14b68641f710f11840e25ad0bc246341cfbb5d8 Mon Sep 17 00:00:00 2001 From: Rico Gonzalez <101926344+rico191013@users.noreply.github.com> Date: Thu, 27 Jun 2024 18:03:57 +0300 Subject: [PATCH 07/58] fix: conflicts of build has been resolved (#1428) fix conflicts --- packages/wallet/backend/src/walletAddress/model.ts | 2 +- packages/wallet/backend/src/walletAddressKeys/controller.ts | 2 +- packages/wallet/backend/src/walletAddressKeys/model.ts | 2 +- .../frontend/src/components/cards/WalletAddressCard.tsx | 2 +- .../src/components/dialogs/EditWalletAddressDialog.tsx | 2 +- .../wallet/frontend/src/components/settings/DeveloperKeys.tsx | 4 ++-- packages/wallet/frontend/src/lib/api/account.ts | 2 +- packages/wallet/frontend/src/lib/api/walletAddress.ts | 2 +- packages/wallet/frontend/src/pages/account/[accountId].tsx | 2 +- packages/wallet/frontend/src/pages/account/create.tsx | 2 +- packages/wallet/shared/src/types/index.ts | 1 + packages/wallet/shared/src/types/walletAddress.ts | 2 +- .../src/types/{WalletAddressKey.ts => walletAddressKey.ts} | 0 13 files changed, 13 insertions(+), 12 deletions(-) rename packages/wallet/shared/src/types/{WalletAddressKey.ts => walletAddressKey.ts} (100%) diff --git a/packages/wallet/backend/src/walletAddress/model.ts b/packages/wallet/backend/src/walletAddress/model.ts index 39bbdcfe7..4f0d20d59 100644 --- a/packages/wallet/backend/src/walletAddress/model.ts +++ b/packages/wallet/backend/src/walletAddress/model.ts @@ -3,7 +3,7 @@ import { Account } from '@/account/model' import { Transaction } from '@/transaction/model' import { WalletAddressKeys } from '@/walletAddressKeys/model' import { BaseModel } from '@shared/backend' -import { IWalletAddressResponse } from '@wallet/shared/src' +import { IWalletAddressResponse } from '@wallet/shared' export class WalletAddress extends BaseModel implements IWalletAddressResponse { static tableName = 'walletAddresses' diff --git a/packages/wallet/backend/src/walletAddressKeys/controller.ts b/packages/wallet/backend/src/walletAddressKeys/controller.ts index b71e76a41..4d8b82527 100644 --- a/packages/wallet/backend/src/walletAddressKeys/controller.ts +++ b/packages/wallet/backend/src/walletAddressKeys/controller.ts @@ -7,7 +7,7 @@ import { uploadWalletAddressKey } from './validation' import { Controller, toSuccessResponse } from '@shared/backend' -import { WalletAddressKeyResponse } from '@wallet/shared/src/types/WalletAddressKey' +import { WalletAddressKeyResponse } from '@wallet/shared' interface IWalletAddressKeyController { registerKey: Controller diff --git a/packages/wallet/backend/src/walletAddressKeys/model.ts b/packages/wallet/backend/src/walletAddressKeys/model.ts index a202535ab..3f69e74cc 100644 --- a/packages/wallet/backend/src/walletAddressKeys/model.ts +++ b/packages/wallet/backend/src/walletAddressKeys/model.ts @@ -1,7 +1,7 @@ import { Model } from 'objection' import { WalletAddress } from '@/walletAddress/model' import { BaseModel } from '@shared/backend' -import { WalletAddressKeyResponse } from '@wallet/shared/src/types/WalletAddressKey' +import { WalletAddressKeyResponse } from '@wallet/shared' export class WalletAddressKeys extends BaseModel diff --git a/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx b/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx index e8e166f25..cf077ca45 100644 --- a/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx +++ b/packages/wallet/frontend/src/components/cards/WalletAddressCard.tsx @@ -14,7 +14,7 @@ import { PencilSquare } from '../icons/Pencil' import { Trash } from '../icons/Trash' import { EditWalletAddressDialog } from '../dialogs/EditWalletAddressDialog' import { CopyButton } from '@/ui/CopyButton' -import { WalletAddressResponse } from '@wallet/shared/src' +import { WalletAddressResponse } from '@wallet/shared' type WalletAddressCardProps = { walletAddress: WalletAddressResponse diff --git a/packages/wallet/frontend/src/components/dialogs/EditWalletAddressDialog.tsx b/packages/wallet/frontend/src/components/dialogs/EditWalletAddressDialog.tsx index 167263c82..4a4ac027e 100644 --- a/packages/wallet/frontend/src/components/dialogs/EditWalletAddressDialog.tsx +++ b/packages/wallet/frontend/src/components/dialogs/EditWalletAddressDialog.tsx @@ -14,7 +14,7 @@ import { getObjectKeys } from '@/utils/helpers' import { OPEN_PAYMENTS_HOST } from '@/utils/constants' import { useDialog } from '@/lib/hooks/useDialog' import { SuccessDialog } from './SuccessDialog' -import { WalletAddressResponse } from '@wallet/shared/src' +import { WalletAddressResponse } from '@wallet/shared' type EditWalletAddressDialogProps = Pick & { walletAddress: WalletAddressResponse diff --git a/packages/wallet/frontend/src/components/settings/DeveloperKeys.tsx b/packages/wallet/frontend/src/components/settings/DeveloperKeys.tsx index 3f33840fb..253a08c17 100644 --- a/packages/wallet/frontend/src/components/settings/DeveloperKeys.tsx +++ b/packages/wallet/frontend/src/components/settings/DeveloperKeys.tsx @@ -20,8 +20,8 @@ import { ConfirmationDialog } from '../dialogs/ConfirmationDialog' import { GenerateKeysDialog } from '../dialogs/GenerateKeysDialog' import { UploadPublicKeyDialog } from '../dialogs/UploadPublicKeyDialog' import { useOnboardingContext } from '@/lib/context/onboarding' -import { WalletAddressResponse } from '@wallet/shared/src' -import { WalletAddressKeyResponse } from '@wallet/shared/src/types/WalletAddressKey' +import { WalletAddressResponse } from '@wallet/shared' +import { WalletAddressKeyResponse } from '@wallet/shared' type WalletAddressContextType = { walletAddress: WalletAddressResponse diff --git a/packages/wallet/frontend/src/lib/api/account.ts b/packages/wallet/frontend/src/lib/api/account.ts index a437e5694..2117f264f 100644 --- a/packages/wallet/frontend/src/lib/api/account.ts +++ b/packages/wallet/frontend/src/lib/api/account.ts @@ -12,7 +12,7 @@ import { withdrawFundsSchema, exchangeAssetSchema } from '@wallet/shared' -import { WalletAddressResponse } from '@wallet/shared/src' +import { WalletAddressResponse } from '@wallet/shared' export type Account = { id: string diff --git a/packages/wallet/frontend/src/lib/api/walletAddress.ts b/packages/wallet/frontend/src/lib/api/walletAddress.ts index b9bf282a7..5ca73e2c8 100644 --- a/packages/wallet/frontend/src/lib/api/walletAddress.ts +++ b/packages/wallet/frontend/src/lib/api/walletAddress.ts @@ -5,7 +5,7 @@ import { type ErrorResponse, type SuccessResponse } from '../httpClient' -import { WalletAddressOP, WalletAddressResponse } from '@wallet/shared/src' +import { WalletAddressOP, WalletAddressResponse } from '@wallet/shared' export const createWalletAddressSchema = z.object({ walletAddressName: z.string().toLowerCase().min(3, { diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index a428edac4..537f88e3e 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -28,7 +28,7 @@ import { z } from 'zod' import { useSnapshot } from 'valtio' import { balanceState } from '@/lib/balance' import { PageHeader } from '@/components/PageHeader' -import { WalletAddressResponse } from '@wallet/shared/src' +import { WalletAddressResponse } from '@wallet/shared' type AccountPageProps = InferGetServerSidePropsType diff --git a/packages/wallet/frontend/src/pages/account/create.tsx b/packages/wallet/frontend/src/pages/account/create.tsx index 31e4efd70..70ab5b88b 100644 --- a/packages/wallet/frontend/src/pages/account/create.tsx +++ b/packages/wallet/frontend/src/pages/account/create.tsx @@ -18,7 +18,7 @@ import { Controller } from 'react-hook-form' import { NextPageWithLayout } from '@/lib/types/app' import { useOnboardingContext } from '@/lib/context/onboarding' import { useEffect } from 'react' -import { createAccountSchema } from '@wallet/shared/src' +import { createAccountSchema } from '@wallet/shared' type CreateAccountProps = InferGetServerSidePropsType const CreateAccountPage: NextPageWithLayout = ({ diff --git a/packages/wallet/shared/src/types/index.ts b/packages/wallet/shared/src/types/index.ts index fa2b95864..6bb8ab7f7 100644 --- a/packages/wallet/shared/src/types/index.ts +++ b/packages/wallet/shared/src/types/index.ts @@ -4,3 +4,4 @@ export * from './rate' export * from './transaction' export * from './grant' export * from './walletAddress' +export * from './walletAddressKey' diff --git a/packages/wallet/shared/src/types/walletAddress.ts b/packages/wallet/shared/src/types/walletAddress.ts index 14c9aa1ad..addb1d224 100644 --- a/packages/wallet/shared/src/types/walletAddress.ts +++ b/packages/wallet/shared/src/types/walletAddress.ts @@ -1,5 +1,5 @@ import { AssetOP } from './asset' -import { WalletAddressKeyResponse } from './WalletAddressKey' +import { WalletAddressKeyResponse } from './walletAddressKey' export interface IWalletAddressResponse { id: string diff --git a/packages/wallet/shared/src/types/WalletAddressKey.ts b/packages/wallet/shared/src/types/walletAddressKey.ts similarity index 100% rename from packages/wallet/shared/src/types/WalletAddressKey.ts rename to packages/wallet/shared/src/types/walletAddressKey.ts From bb35ecf18480e187601ad25d3c356db5a6e36212 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 9 Jul 2024 13:24:43 +0300 Subject: [PATCH 08/58] Remove unused function --- packages/wallet/backend/src/account/service.ts | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/packages/wallet/backend/src/account/service.ts b/packages/wallet/backend/src/account/service.ts index 96ed86a4d..86c606ad7 100644 --- a/packages/wallet/backend/src/account/service.ts +++ b/packages/wallet/backend/src/account/service.ts @@ -218,22 +218,6 @@ export class AccountService implements IAccountService { ) } - async getVirtualAccountBalance( - userId: string, - assetCode: string - ): Promise { - const account = await Account.query() - .where('userId', userId) - .where('assetCode', assetCode) - .first() - - if (!account) { - throw new NotFound() - } - - return account.balance - } - public async fundAccount(args: FundAccountArgs): Promise { const existingAccount = await Account.query() .where('userId', args.userId) From c01d1a6a2c6cd16ab13c82dea643980ff9113d01 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 10 Jul 2024 17:37:31 +0300 Subject: [PATCH 09/58] Remove unused import --- packages/wallet/frontend/src/lib/api/walletAddress.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/wallet/frontend/src/lib/api/walletAddress.ts b/packages/wallet/frontend/src/lib/api/walletAddress.ts index 0839c4040..13493af4f 100644 --- a/packages/wallet/frontend/src/lib/api/walletAddress.ts +++ b/packages/wallet/frontend/src/lib/api/walletAddress.ts @@ -6,7 +6,6 @@ import { type SuccessResponse } from '../httpClient' import { - ListWalletAddressesResponse, WalletAddressResponse, WalletAddressOP } from '@wallet/shared' From b3429ac5961cf0d357dc237dc518801ce5a8ddf3 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 11 Jul 2024 13:00:38 +0300 Subject: [PATCH 10/58] Fix wallet backend tests --- .../wallet/backend/src/walletAddress/service.ts | 9 --------- .../backend/tests/walletAddress/service.test.ts | 17 +++++++++++------ 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index 96e221bdc..ca6ab724a 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -278,8 +278,6 @@ export class WalletAddressService implements IWalletAddressService { ) } - this.logger.debug(`Passed first throw`) - const amount = Number( ( Number(balance * this.env.RAPYD_THRESHOLD) * @@ -293,8 +291,6 @@ export class WalletAddressService implements IWalletAddressService { ) } - this.logger.debug(`Passed second throw`) - let destination = walletAddress.account.user.rapydWalletId let source = this.env.RAPYD_SETTLEMENT_EWALLET @@ -316,8 +312,6 @@ export class WalletAddressService implements IWalletAddressService { await walletAddress.$relatedQuery('account', trx).patch({ debt: raw('?? + ?', ['debt', amount]) }) - - this.logger.debug(`Early return`) return } @@ -328,8 +322,6 @@ export class WalletAddressService implements IWalletAddressService { ) } - this.logger.debug(`Passed third throw`) - const updatedField: keyof Pick< PartialModelObject, 'incomingBalance' | 'outgoingBalance' @@ -354,7 +346,6 @@ export class WalletAddressService implements IWalletAddressService { walletAddress.$query(trx).update(updatePart) ]) - //TODO remove this after testing this.logger.debug( `Proccesed asset scale 9 transactions for payment pointer ${walletAddress.url}. Type: ${type} | Amount: ${amount}` ) diff --git a/packages/wallet/backend/tests/walletAddress/service.test.ts b/packages/wallet/backend/tests/walletAddress/service.test.ts index 5381007a4..1630fb3f2 100644 --- a/packages/wallet/backend/tests/walletAddress/service.test.ts +++ b/packages/wallet/backend/tests/walletAddress/service.test.ts @@ -29,7 +29,9 @@ describe('Wallet Address Service', () => { const prepareWADependencies = async ( paymentPointerName: string, - isAccountAssigned = true + isAccountAssigned = true, + assetCode?: string, + assetScale?: number, ) => { let extraAcc = {} as Account if (!isAccountAssigned) @@ -56,8 +58,8 @@ describe('Wallet Address Service', () => { publicName: faker.string.alpha(10), accountId: isAccountAssigned ? account.id : extraAcc.id, id: faker.string.uuid(), - assetCode: undefined, - assetScale: 9 + assetCode: assetCode || undefined, + assetScale: assetScale || undefined }) return { @@ -323,7 +325,9 @@ describe('Wallet Address Service', () => { describe('Sum By Wallet AddressId Since', () => { it('should complete without errors for zero sum', async () => { - await prepareWADependencies('my-wallet', true) + await prepareWADependencies('my-wallet', true, + 'USD', + 9) await expect( waService.keepBalancesSynced(new Date(0)) @@ -333,8 +337,9 @@ describe('Wallet Address Service', () => { it('should complete without errors for non-zero sum', async () => { prepareWSDepsMock(1000n) - await prepareWADependencies('my-wallet', true) - + await prepareWADependencies('my-wallet', true, + 'USD', + 9) await expect( waService.keepBalancesSynced(new Date(0)) ).resolves.toBeUndefined() From 07a1ea33c25820ac1e70008ad8e9defc5c5ffaf9 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 11 Jul 2024 13:05:39 +0300 Subject: [PATCH 11/58] Run prettier --- .../wallet/backend/tests/walletAddress/service.test.ts | 10 +++------- packages/wallet/frontend/src/lib/api/walletAddress.ts | 5 +---- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/packages/wallet/backend/tests/walletAddress/service.test.ts b/packages/wallet/backend/tests/walletAddress/service.test.ts index 1630fb3f2..be8af0cde 100644 --- a/packages/wallet/backend/tests/walletAddress/service.test.ts +++ b/packages/wallet/backend/tests/walletAddress/service.test.ts @@ -31,7 +31,7 @@ describe('Wallet Address Service', () => { paymentPointerName: string, isAccountAssigned = true, assetCode?: string, - assetScale?: number, + assetScale?: number ) => { let extraAcc = {} as Account if (!isAccountAssigned) @@ -325,9 +325,7 @@ describe('Wallet Address Service', () => { describe('Sum By Wallet AddressId Since', () => { it('should complete without errors for zero sum', async () => { - await prepareWADependencies('my-wallet', true, - 'USD', - 9) + await prepareWADependencies('my-wallet', true, 'USD', 9) await expect( waService.keepBalancesSynced(new Date(0)) @@ -337,9 +335,7 @@ describe('Wallet Address Service', () => { it('should complete without errors for non-zero sum', async () => { prepareWSDepsMock(1000n) - await prepareWADependencies('my-wallet', true, - 'USD', - 9) + await prepareWADependencies('my-wallet', true, 'USD', 9) await expect( waService.keepBalancesSynced(new Date(0)) ).resolves.toBeUndefined() diff --git a/packages/wallet/frontend/src/lib/api/walletAddress.ts b/packages/wallet/frontend/src/lib/api/walletAddress.ts index 13493af4f..ffc81bd5d 100644 --- a/packages/wallet/frontend/src/lib/api/walletAddress.ts +++ b/packages/wallet/frontend/src/lib/api/walletAddress.ts @@ -5,10 +5,7 @@ import { type ErrorResponse, type SuccessResponse } from '../httpClient' -import { - WalletAddressResponse, - WalletAddressOP -} from '@wallet/shared' +import { WalletAddressResponse, WalletAddressOP } from '@wallet/shared' export const createWalletAddressSchema = z.object({ walletAddressName: z.string().toLowerCase().min(3, { From 9eeeec94f8f953bd4c78a429fb90958b56224ff4 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 16 Jul 2024 13:14:25 +0300 Subject: [PATCH 12/58] Fix frontend formatting of asset scale --- packages/wallet/backend/src/account/service.ts | 6 ++++-- .../wallet/frontend/src/components/cards/AccountCard.tsx | 3 ++- packages/wallet/frontend/src/pages/account/[accountId].tsx | 7 +++++-- packages/wallet/frontend/src/utils/helpers.ts | 7 +++---- 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/packages/wallet/backend/src/account/service.ts b/packages/wallet/backend/src/account/service.ts index 86c606ad7..0b5f128d4 100644 --- a/packages/wallet/backend/src/account/service.ts +++ b/packages/wallet/backend/src/account/service.ts @@ -6,6 +6,7 @@ import { transformBalance } from '@/utils/helpers' import { Transaction } from '@/transaction/model' import { Amount } from '@/rafiki/service' import { Conflict, NotFound } from '@shared/backend' +import { Env } from '@/config/env' type CreateAccountArgs = { userId: string @@ -38,7 +39,8 @@ interface IAccountService { export class AccountService implements IAccountService { constructor( private rapydClient: RapydClient, - private rafikiClient: RafikiClient + private rafikiClient: RafikiClient, + private env: Env ) {} public async createAccount(args: CreateAccountArgs): Promise { @@ -244,7 +246,7 @@ export class AccountService implements IAccountService { accountId: existingAccount.id, paymentId: transactions[transactions.length - 1].id, assetCode: existingAccount.assetCode, - value: transformBalance(args.amount, asset.scale), + value: transformBalance(args.amount, this.env.MAX_ASSET_SCALE || asset.scale), type: 'INCOMING', status: 'COMPLETED', description: 'Fund account' diff --git a/packages/wallet/frontend/src/components/cards/AccountCard.tsx b/packages/wallet/frontend/src/components/cards/AccountCard.tsx index b8a81c2e3..adb4adefd 100644 --- a/packages/wallet/frontend/src/components/cards/AccountCard.tsx +++ b/packages/wallet/frontend/src/components/cards/AccountCard.tsx @@ -19,10 +19,11 @@ export const AccountCard = ({ account, idOnboarding }: AccountCardProps) => { const snapshotAccount = accountsSnapshot.find( (item) => item.assetCode === account.assetCode ) + const baseAssetScale = 2; return formatAmount({ value: snapshotAccount?.balance || account.balance, assetCode: account.assetCode, - assetScale: account.assetScale + assetScale: baseAssetScale }) }, [account, accountsSnapshot]) diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index 537f88e3e..c6969f62d 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -47,16 +47,19 @@ const AccountPage: NextPageWithLayout = ({ const value = snapshotAccount?.balance || account.balance + const baseAssetScale = 2; + const maxAssetScale = 9; + const amountScale2 = formatAmount({ value: value, assetCode: account.assetCode, - assetScale: account.assetScale + assetScale: baseAssetScale }) const amountScale9 = formatAmount({ value: value, assetCode: account.assetCode, - assetScale: 9 + assetScale: maxAssetScale }) return { diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index d180fa2ad..3e9af6f0a 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -45,10 +45,9 @@ export const formatAmount = (args: FormatAmountArgs): FormattedAmount => { maximumFractionDigits: assetScale, minimumFractionDigits: assetScale }) - //TODO make this work properly - const numberValue = Number(value) / Math.pow(10, assetScale) - - const amount = formatter.format(numberValue) + // All assets will have asset scale 9 by default so we treat the amounts as such when formatting + const maxAssetScale = 9; + const amount = formatter.format(Number(`${value}e-${maxAssetScale}`)) const symbol = getCurrencySymbol(assetCode) return { From 22c77a5ebfe8f89d49a9c5fee1be7024f26c41fc Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 16 Jul 2024 13:25:36 +0300 Subject: [PATCH 13/58] Run prettier --- packages/wallet/backend/src/account/service.ts | 5 ++++- .../wallet/frontend/src/components/cards/AccountCard.tsx | 2 +- packages/wallet/frontend/src/pages/account/[accountId].tsx | 6 +++--- packages/wallet/frontend/src/utils/helpers.ts | 2 +- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/wallet/backend/src/account/service.ts b/packages/wallet/backend/src/account/service.ts index 0b5f128d4..e52897a48 100644 --- a/packages/wallet/backend/src/account/service.ts +++ b/packages/wallet/backend/src/account/service.ts @@ -246,7 +246,10 @@ export class AccountService implements IAccountService { accountId: existingAccount.id, paymentId: transactions[transactions.length - 1].id, assetCode: existingAccount.assetCode, - value: transformBalance(args.amount, this.env.MAX_ASSET_SCALE || asset.scale), + value: transformBalance( + args.amount, + this.env.MAX_ASSET_SCALE || asset.scale + ), type: 'INCOMING', status: 'COMPLETED', description: 'Fund account' diff --git a/packages/wallet/frontend/src/components/cards/AccountCard.tsx b/packages/wallet/frontend/src/components/cards/AccountCard.tsx index adb4adefd..6a2ebe1d2 100644 --- a/packages/wallet/frontend/src/components/cards/AccountCard.tsx +++ b/packages/wallet/frontend/src/components/cards/AccountCard.tsx @@ -19,7 +19,7 @@ export const AccountCard = ({ account, idOnboarding }: AccountCardProps) => { const snapshotAccount = accountsSnapshot.find( (item) => item.assetCode === account.assetCode ) - const baseAssetScale = 2; + const baseAssetScale = 2 return formatAmount({ value: snapshotAccount?.balance || account.balance, assetCode: account.assetCode, diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index c6969f62d..e9ac75864 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -47,9 +47,9 @@ const AccountPage: NextPageWithLayout = ({ const value = snapshotAccount?.balance || account.balance - const baseAssetScale = 2; - const maxAssetScale = 9; - + const baseAssetScale = 2 + const maxAssetScale = 9 + const amountScale2 = formatAmount({ value: value, assetCode: account.assetCode, diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index 3e9af6f0a..10b82c078 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -46,7 +46,7 @@ export const formatAmount = (args: FormatAmountArgs): FormattedAmount => { minimumFractionDigits: assetScale }) // All assets will have asset scale 9 by default so we treat the amounts as such when formatting - const maxAssetScale = 9; + const maxAssetScale = 9 const amount = formatter.format(Number(`${value}e-${maxAssetScale}`)) const symbol = getCurrencySymbol(assetCode) From 4876690df3a916efbfb876172f4431a2a844f00f Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 16 Jul 2024 13:36:49 +0300 Subject: [PATCH 14/58] Run prettier --- packages/wallet/shared/src/types/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/wallet/shared/src/types/index.ts b/packages/wallet/shared/src/types/index.ts index 4cbee4ebf..b7ed26a8a 100644 --- a/packages/wallet/shared/src/types/index.ts +++ b/packages/wallet/shared/src/types/index.ts @@ -7,4 +7,4 @@ export * from './transaction' export * from './grant' export * from './walletAddress' export * from './walletAddressKey' -export * from './user' \ No newline at end of file +export * from './user' From 4caaaa4cc9a8b7c31b2160d0f04d804872ccfc95 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 16 Jul 2024 18:04:04 +0300 Subject: [PATCH 15/58] Final fix for displaying in diffrerent asset scales --- .../src/components/cards/AccountCard.tsx | 11 +++++++- .../src/pages/account/[accountId].tsx | 27 ++++++++++--------- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/packages/wallet/frontend/src/components/cards/AccountCard.tsx b/packages/wallet/frontend/src/components/cards/AccountCard.tsx index 6a2ebe1d2..b1ba13659 100644 --- a/packages/wallet/frontend/src/components/cards/AccountCard.tsx +++ b/packages/wallet/frontend/src/components/cards/AccountCard.tsx @@ -20,8 +20,17 @@ export const AccountCard = ({ account, idOnboarding }: AccountCardProps) => { (item) => item.assetCode === account.assetCode ) const baseAssetScale = 2 + const maxAssetScale = 9 + + const snapshotBalance = snapshotAccount + ? Number(snapshotAccount.balance) + : 0 + const accountBalance = + Number(account.balance) * Math.pow(10, maxAssetScale - account.assetScale) + const value = (snapshotBalance || accountBalance).toString() + return formatAmount({ - value: snapshotAccount?.balance || account.balance, + value, assetCode: account.assetCode, assetScale: baseAssetScale }) diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index e9ac75864..5376850a2 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -34,9 +34,8 @@ type AccountPageProps = InferGetServerSidePropsType const AccountPage: NextPageWithLayout = ({ account, - allWalletAddresses - //TODO add this to account.balance - // balance + allWalletAddresses, + balance }) => { const [openDialog, closeDialog] = useDialog() const { accountsSnapshot } = useSnapshot(balanceState) @@ -45,19 +44,25 @@ const AccountPage: NextPageWithLayout = ({ (item) => item.assetCode === account.assetCode ) - const value = snapshotAccount?.balance || account.balance - const baseAssetScale = 2 const maxAssetScale = 9 + const snapshotBalance = snapshotAccount + ? Number(snapshotAccount.balance) + : 0 + const accountBalance = + Number(account.balance) * Math.pow(10, maxAssetScale - account.assetScale) + + // `balance` represents incoming amount - outgoing amount in asset scale 9 + const value = ((snapshotBalance || accountBalance) + balance).toString() const amountScale2 = formatAmount({ - value: value, + value, assetCode: account.assetCode, assetScale: baseAssetScale }) const amountScale9 = formatAmount({ - value: value, + value, assetCode: account.assetCode, assetScale: maxAssetScale }) @@ -197,7 +202,7 @@ const querySchema = z.object({ export const getServerSideProps: GetServerSideProps<{ account: Account allWalletAddresses: WalletAddressResponse[] - balance: FormattedAmount + balance: number }> = async (ctx) => { const result = querySchema.safeParse(ctx.query) if (!result.success) { @@ -233,11 +238,7 @@ export const getServerSideProps: GetServerSideProps<{ props: { account: accountResponse.result, allWalletAddresses: walletAddressesResponse.result, - balance: formatAmount({ - value: balance.toString(), - assetCode: accountResponse.result.assetCode, - assetScale: 9 - }) + balance } } } From 83ed0c516e16359c7e77dbddf2a880846f59ad49 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 16 Jul 2024 18:13:21 +0300 Subject: [PATCH 16/58] Remove unused import --- packages/wallet/frontend/src/pages/account/[accountId].tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index 5376850a2..010973008 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -14,7 +14,6 @@ import { useDialog } from '@/lib/hooks/useDialog' import { NextPageWithLayout } from '@/lib/types/app' import { Link } from '@/ui/Link' import { - FormattedAmount, formatAmount, replaceWalletAddressProtocol } from '@/utils/helpers' From b2b14cec705386e21e276752d6a7927c137f345f Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 16 Jul 2024 18:15:59 +0300 Subject: [PATCH 17/58] Run prettier --- packages/wallet/frontend/src/pages/account/[accountId].tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index 010973008..ea0061c98 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -13,10 +13,7 @@ import { useOnboardingContext } from '@/lib/context/onboarding' import { useDialog } from '@/lib/hooks/useDialog' import { NextPageWithLayout } from '@/lib/types/app' import { Link } from '@/ui/Link' -import { - formatAmount, - replaceWalletAddressProtocol -} from '@/utils/helpers' +import { formatAmount, replaceWalletAddressProtocol } from '@/utils/helpers' import type { GetServerSideProps, InferGetServerSidePropsType From 2626bfc202e5abe3345fdac569e23c8a93cc6582 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 16 Jul 2024 18:31:21 +0300 Subject: [PATCH 18/58] Add balance to useMemo deps --- packages/wallet/frontend/src/pages/account/[accountId].tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index ea0061c98..65e15f40b 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -67,7 +67,7 @@ const AccountPage: NextPageWithLayout = ({ amountScale2: amountScale2, amountScale9: amountScale9 } - }, [account, accountsSnapshot]) + }, [account, accountsSnapshot, balance]) const { isUserFirstTime, setRunOnboarding, setStepIndex, stepIndex } = useOnboardingContext() From e52bd160b9f71d76f38b38b543016d463e69e970 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 17 Jul 2024 21:34:51 +0300 Subject: [PATCH 19/58] Fix display send and request amounts --- .../frontend/src/pages/transfer/request.tsx | 17 +++++++++++++++-- .../wallet/frontend/src/pages/transfer/send.tsx | 17 +++++++++++++++-- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/packages/wallet/frontend/src/pages/transfer/request.tsx b/packages/wallet/frontend/src/pages/transfer/request.tsx index b16cff452..7c1a2c1f0 100644 --- a/packages/wallet/frontend/src/pages/transfer/request.tsx +++ b/packages/wallet/frontend/src/pages/transfer/request.tsx @@ -67,10 +67,23 @@ const RequestPage: NextPageWithLayout = ({ accounts }) => { item.assetCode === selectedAccount.assetCode && item.assetScale === selectedAccount.assetScale ) + + const baseAssetScale = 2 + const maxAssetScale = 9 + + const snapshotBalance = snapshotAccount + ? Number(snapshotAccount.balance) + : 0 + const accountBalance = + Number(selectedAccount.balance) * + Math.pow(10, maxAssetScale - selectedAccount.assetScale) + + const value = (snapshotBalance || accountBalance).toString() + return formatAmount({ - value: snapshotAccount?.balance || selectedAccount.balance, + value, assetCode: selectedAccount.assetCode, - assetScale: selectedAccount.assetScale + assetScale: baseAssetScale }).amount }, [accountsSnapshot, selectedAccount]) diff --git a/packages/wallet/frontend/src/pages/transfer/send.tsx b/packages/wallet/frontend/src/pages/transfer/send.tsx index b1577fa2c..7cb4a8a15 100644 --- a/packages/wallet/frontend/src/pages/transfer/send.tsx +++ b/packages/wallet/frontend/src/pages/transfer/send.tsx @@ -66,10 +66,23 @@ const SendPage: NextPageWithLayout = ({ accounts }) => { item.assetCode === selectedAccount.assetCode && item.assetScale === selectedAccount.assetScale ) + + const baseAssetScale = 2 + const maxAssetScale = 9 + + const snapshotBalance = snapshotAccount + ? Number(snapshotAccount.balance) + : 0 + const accountBalance = + Number(selectedAccount.balance) * + Math.pow(10, maxAssetScale - selectedAccount.assetScale) + + const value = (snapshotBalance || accountBalance).toString() + return formatAmount({ - value: snapshotAccount?.balance || selectedAccount.balance, + value, assetCode: selectedAccount.assetCode, - assetScale: selectedAccount.assetScale + assetScale: baseAssetScale }).amount }, [accountsSnapshot, selectedAccount]) From 6c5d9a39fe6df8e7d74626c307edbe5122f872df Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 1 Aug 2024 18:49:57 +0300 Subject: [PATCH 20/58] Fix quote values --- .../src/components/dialogs/QuoteDialog.tsx | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx index e561d1a86..7d98e7ac6 100644 --- a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx +++ b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx @@ -23,14 +23,24 @@ export const QuoteDialog = ({ }: QuoteDialogProps) => { const { setRunOnboarding, stepIndex, setStepIndex, isUserFirstTime } = useOnboardingContext() + + //const baseAssetScale = 2 + const maxAssetScale = 9 + + const receiveValue = + (Number(quote.receiveAmount.value) * Math.pow(10, maxAssetScale - quote.receiveAmount.assetScale)).toString() + + const debitValue = + (Number(quote.debitAmount.value) * Math.pow(10, maxAssetScale - quote.debitAmount.assetScale)).toString() + const receiveAmount = formatAmount({ - value: quote.receiveAmount.value, + value: receiveValue, assetCode: quote.receiveAmount.assetCode, assetScale: quote.receiveAmount.assetScale }) const debitAmount = formatAmount({ - value: quote.debitAmount.value, + value: debitValue, assetCode: quote.debitAmount.assetCode, assetScale: quote.debitAmount.assetScale }) From 4c0de7469053a6261693155740170fc84815374a Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 1 Aug 2024 18:51:07 +0300 Subject: [PATCH 21/58] Remove comment --- packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx index 7d98e7ac6..7fccade80 100644 --- a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx +++ b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx @@ -24,7 +24,6 @@ export const QuoteDialog = ({ const { setRunOnboarding, stepIndex, setStepIndex, isUserFirstTime } = useOnboardingContext() - //const baseAssetScale = 2 const maxAssetScale = 9 const receiveValue = From 1768d9e2b1035b6325863dc248490ed4c5fd226e Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 1 Aug 2024 19:04:55 +0300 Subject: [PATCH 22/58] Prettier --- .../src/components/dialogs/QuoteDialog.tsx | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx index 7fccade80..e70726f35 100644 --- a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx +++ b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx @@ -26,11 +26,15 @@ export const QuoteDialog = ({ const maxAssetScale = 9 - const receiveValue = - (Number(quote.receiveAmount.value) * Math.pow(10, maxAssetScale - quote.receiveAmount.assetScale)).toString() - - const debitValue = - (Number(quote.debitAmount.value) * Math.pow(10, maxAssetScale - quote.debitAmount.assetScale)).toString() + const receiveValue = ( + Number(quote.receiveAmount.value) * + Math.pow(10, maxAssetScale - quote.receiveAmount.assetScale) + ).toString() + + const debitValue = ( + Number(quote.debitAmount.value) * + Math.pow(10, maxAssetScale - quote.debitAmount.assetScale) + ).toString() const receiveAmount = formatAmount({ value: receiveValue, From 3aa2ce8570e6a4f4f860f3b37e92c01d71de9f7a Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 1 Aug 2024 20:25:33 +0300 Subject: [PATCH 23/58] Add simple migration - WIP --- .../20240801155211_update_wallet_addresses.js | 16 + .../src/rafiki/auth/generated/graphql.ts | 324 ++- .../src/rafiki/backend/generated/graphql.ts | 1938 ++++++++++------- 3 files changed, 1320 insertions(+), 958 deletions(-) create mode 100644 packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js diff --git a/packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js b/packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js new file mode 100644 index 000000000..e9eec76fe --- /dev/null +++ b/packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js @@ -0,0 +1,16 @@ +/** + * @param { import("knex").Knex } knex + * @returns { Promise } + */ +exports.up = async function (knex) { + await knex('walletAddresses').update({ assetScale: 9 }); + }; + +/** + * @param { import("knex").Knex } knex + * @returns { Promise } + */ +exports.down = async function (knex) { +await knex('walletAddresses').update({ assetScale: 2 }); +}; + \ No newline at end of file diff --git a/packages/wallet/backend/src/rafiki/auth/generated/graphql.ts b/packages/wallet/backend/src/rafiki/auth/generated/graphql.ts index 9372ebe6e..69ae8ef6b 100644 --- a/packages/wallet/backend/src/rafiki/auth/generated/graphql.ts +++ b/packages/wallet/backend/src/rafiki/auth/generated/graphql.ts @@ -1,78 +1,91 @@ -export type Maybe = T | null; -export type InputMaybe = T | undefined; -export type Exact = { [K in keyof T]: T[K] }; -export type MakeOptional = Omit & { [SubKey in K]?: Maybe }; -export type MakeMaybe = Omit & { [SubKey in K]: Maybe }; -export type MakeEmpty = { [_ in K]?: never }; -export type Incremental = T | { [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never }; +export type Maybe = T | null +export type InputMaybe = T | undefined +export type Exact = { + [K in keyof T]: T[K] +} +export type MakeOptional = Omit & { + [SubKey in K]?: Maybe +} +export type MakeMaybe = Omit & { + [SubKey in K]: Maybe +} +export type MakeEmpty< + T extends { [key: string]: unknown }, + K extends keyof T +> = { [_ in K]?: never } +export type Incremental = + | T + | { + [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never + } /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { - ID: { input: string; output: string; } - String: { input: string; output: string; } - Boolean: { input: boolean; output: boolean; } - Int: { input: number; output: number; } - Float: { input: number; output: number; } - BigInt: { input: bigint; output: bigint; } - UInt8: { input: number; output: number; } -}; + ID: { input: string; output: string } + String: { input: string; output: string } + Boolean: { input: boolean; output: boolean } + Int: { input: number; output: number } + Float: { input: number; output: number } + BigInt: { input: bigint; output: bigint } + UInt8: { input: number; output: number } +} export type Access = Model & { - __typename?: 'Access'; + __typename?: 'Access' /** Access action (create, read, list or complete) */ - actions: Array>; + actions: Array> /** Date-time of creation */ - createdAt: Scalars['String']['output']; + createdAt: Scalars['String']['output'] /** Access id */ - id: Scalars['ID']['output']; + id: Scalars['ID']['output'] /** Wallet address of a sub-resource (incoming payment, outgoing payment, or quote) */ - identifier?: Maybe; + identifier?: Maybe /** Payment limits */ - limits?: Maybe; + limits?: Maybe /** Access type (incoming payment, outgoing payment, or quote) */ - type: Scalars['String']['output']; -}; + type: Scalars['String']['output'] +} export type FilterFinalizationReason = { - in?: InputMaybe>; - notIn?: InputMaybe>; -}; + in?: InputMaybe> + notIn?: InputMaybe> +} export type FilterGrantState = { - in?: InputMaybe>; - notIn?: InputMaybe>; -}; + in?: InputMaybe> + notIn?: InputMaybe> +} export type FilterString = { - in?: InputMaybe>; -}; + in?: InputMaybe> +} export type Grant = Model & { - __typename?: 'Grant'; + __typename?: 'Grant' /** Access details */ - access: Array; + access: Array /** Wallet address of the grantee's account */ - client: Scalars['String']['output']; + client: Scalars['String']['output'] /** Date-time of creation */ - createdAt: Scalars['String']['output']; + createdAt: Scalars['String']['output'] /** Reason a grant was finalized */ - finalizationReason?: Maybe; + finalizationReason?: Maybe /** Grant id */ - id: Scalars['ID']['output']; + id: Scalars['ID']['output'] /** State of the grant */ - state: GrantState; -}; + state: GrantState +} export type GrantEdge = { - __typename?: 'GrantEdge'; - cursor: Scalars['String']['output']; - node: Grant; -}; + __typename?: 'GrantEdge' + cursor: Scalars['String']['output'] + node: Grant +} export type GrantFilter = { - finalizationReason?: InputMaybe; - identifier?: InputMaybe; - state?: InputMaybe; -}; + finalizationReason?: InputMaybe + identifier?: InputMaybe + state?: InputMaybe +} export enum GrantFinalization { /** grant was issued */ @@ -95,91 +108,88 @@ export enum GrantState { } export type GrantsConnection = { - __typename?: 'GrantsConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'GrantsConnection' + edges: Array + pageInfo: PageInfo +} export type LimitData = { - __typename?: 'LimitData'; + __typename?: 'LimitData' /** Amount to debit */ - debitAmount?: Maybe; + debitAmount?: Maybe /** Interval between payments */ - interval?: Maybe; + interval?: Maybe /** Amount to receive */ - receiveAmount?: Maybe; + receiveAmount?: Maybe /** Wallet address URL of the receiver */ - receiver?: Maybe; -}; + receiver?: Maybe +} export type Model = { - createdAt: Scalars['String']['output']; - id: Scalars['ID']['output']; -}; + createdAt: Scalars['String']['output'] + id: Scalars['ID']['output'] +} export type Mutation = { - __typename?: 'Mutation'; + __typename?: 'Mutation' /** Revoke Grant */ - revokeGrant: RevokeGrantMutationResponse; -}; - + revokeGrant: RevokeGrantMutationResponse +} export type MutationRevokeGrantArgs = { - input: RevokeGrantInput; -}; + input: RevokeGrantInput +} export type PageInfo = { - __typename?: 'PageInfo'; + __typename?: 'PageInfo' /** Paginating forwards: the cursor to continue. */ - endCursor?: Maybe; + endCursor?: Maybe /** Paginating forwards: Are there more pages? */ - hasNextPage: Scalars['Boolean']['output']; + hasNextPage: Scalars['Boolean']['output'] /** Paginating backwards: Are there more pages? */ - hasPreviousPage: Scalars['Boolean']['output']; + hasPreviousPage: Scalars['Boolean']['output'] /** Paginating backwards: the cursor to continue. */ - startCursor?: Maybe; -}; + startCursor?: Maybe +} export type PaymentAmount = { - __typename?: 'PaymentAmount'; + __typename?: 'PaymentAmount' /** [ISO 4217 currency code](https://en.wikipedia.org/wiki/ISO_4217), e.g. `USD` */ - assetCode: Scalars['String']['output']; + assetCode: Scalars['String']['output'] /** Difference in orders of magnitude between the standard unit of an asset and a corresponding fractional unit */ - assetScale: Scalars['UInt8']['output']; - value: Scalars['BigInt']['output']; -}; + assetScale: Scalars['UInt8']['output'] + value: Scalars['BigInt']['output'] +} export type Query = { - __typename?: 'Query'; + __typename?: 'Query' /** Fetch a grant */ - grant: Grant; + grant: Grant /** Fetch a page of grants. */ - grants: GrantsConnection; -}; - + grants: GrantsConnection +} export type QueryGrantArgs = { - id: Scalars['ID']['input']; -}; - + id: Scalars['ID']['input'] +} export type QueryGrantsArgs = { - after?: InputMaybe; - before?: InputMaybe; - filter?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; + after?: InputMaybe + before?: InputMaybe + filter?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type RevokeGrantInput = { - grantId: Scalars['String']['input']; -}; + grantId: Scalars['String']['input'] +} export type RevokeGrantMutationResponse = { - __typename?: 'RevokeGrantMutationResponse'; - id: Scalars['ID']['output']; -}; + __typename?: 'RevokeGrantMutationResponse' + id: Scalars['ID']['output'] +} export enum SortOrder { /** Choose ascending order for results. */ @@ -189,26 +199,110 @@ export enum SortOrder { } export type GetGrantsQueryVariables = Exact<{ - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - filter?: InputMaybe; -}>; - - -export type GetGrantsQuery = { __typename?: 'Query', grants: { __typename?: 'GrantsConnection', edges: Array<{ __typename?: 'GrantEdge', cursor: string, node: { __typename?: 'Grant', id: string, client: string, state: GrantState, finalizationReason?: GrantFinalization | null, createdAt: string, access: Array<{ __typename?: 'Access', id: string, identifier?: string | null, createdAt: string, actions: Array, type: string, limits?: { __typename?: 'LimitData', receiver?: string | null, interval?: string | null, debitAmount?: { __typename?: 'PaymentAmount', value: bigint, assetCode: string, assetScale: number } | null, receiveAmount?: { __typename?: 'PaymentAmount', value: bigint, assetCode: string, assetScale: number } | null } | null }> } }>, pageInfo: { __typename?: 'PageInfo', endCursor?: string | null, hasNextPage: boolean, hasPreviousPage: boolean, startCursor?: string | null } } }; + after?: InputMaybe + before?: InputMaybe + first?: InputMaybe + last?: InputMaybe + filter?: InputMaybe +}> + +export type GetGrantsQuery = { + __typename?: 'Query' + grants: { + __typename?: 'GrantsConnection' + edges: Array<{ + __typename?: 'GrantEdge' + cursor: string + node: { + __typename?: 'Grant' + id: string + client: string + state: GrantState + finalizationReason?: GrantFinalization | null + createdAt: string + access: Array<{ + __typename?: 'Access' + id: string + identifier?: string | null + createdAt: string + actions: Array + type: string + limits?: { + __typename?: 'LimitData' + receiver?: string | null + interval?: string | null + debitAmount?: { + __typename?: 'PaymentAmount' + value: bigint + assetCode: string + assetScale: number + } | null + receiveAmount?: { + __typename?: 'PaymentAmount' + value: bigint + assetCode: string + assetScale: number + } | null + } | null + }> + } + }> + pageInfo: { + __typename?: 'PageInfo' + endCursor?: string | null + hasNextPage: boolean + hasPreviousPage: boolean + startCursor?: string | null + } + } +} export type GetGrantQueryVariables = Exact<{ - grantId: Scalars['ID']['input']; -}>; - - -export type GetGrantQuery = { __typename?: 'Query', grant: { __typename?: 'Grant', id: string, client: string, state: GrantState, finalizationReason?: GrantFinalization | null, createdAt: string, access: Array<{ __typename?: 'Access', id: string, identifier?: string | null, createdAt: string, actions: Array, type: string, limits?: { __typename?: 'LimitData', receiver?: string | null, interval?: string | null, debitAmount?: { __typename?: 'PaymentAmount', value: bigint, assetCode: string, assetScale: number } | null, receiveAmount?: { __typename?: 'PaymentAmount', value: bigint, assetCode: string, assetScale: number } | null } | null }> } }; + grantId: Scalars['ID']['input'] +}> + +export type GetGrantQuery = { + __typename?: 'Query' + grant: { + __typename?: 'Grant' + id: string + client: string + state: GrantState + finalizationReason?: GrantFinalization | null + createdAt: string + access: Array<{ + __typename?: 'Access' + id: string + identifier?: string | null + createdAt: string + actions: Array + type: string + limits?: { + __typename?: 'LimitData' + receiver?: string | null + interval?: string | null + debitAmount?: { + __typename?: 'PaymentAmount' + value: bigint + assetCode: string + assetScale: number + } | null + receiveAmount?: { + __typename?: 'PaymentAmount' + value: bigint + assetCode: string + assetScale: number + } | null + } | null + }> + } +} export type RevokeGrantMutationVariables = Exact<{ - grantId: Scalars['String']['input']; -}>; + grantId: Scalars['String']['input'] +}> - -export type RevokeGrantMutation = { __typename?: 'Mutation', revokeGrant: { __typename?: 'RevokeGrantMutationResponse', id: string } }; +export type RevokeGrantMutation = { + __typename?: 'Mutation' + revokeGrant: { __typename?: 'RevokeGrantMutationResponse'; id: string } +} diff --git a/packages/wallet/backend/src/rafiki/backend/generated/graphql.ts b/packages/wallet/backend/src/rafiki/backend/generated/graphql.ts index a232bdd35..373d44c84 100644 --- a/packages/wallet/backend/src/rafiki/backend/generated/graphql.ts +++ b/packages/wallet/backend/src/rafiki/backend/generated/graphql.ts @@ -1,333 +1,345 @@ -export type Maybe = T | null; -export type InputMaybe = T | undefined; -export type Exact = { [K in keyof T]: T[K] }; -export type MakeOptional = Omit & { [SubKey in K]?: Maybe }; -export type MakeMaybe = Omit & { [SubKey in K]: Maybe }; -export type MakeEmpty = { [_ in K]?: never }; -export type Incremental = T | { [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never }; +export type Maybe = T | null +export type InputMaybe = T | undefined +export type Exact = { + [K in keyof T]: T[K] +} +export type MakeOptional = Omit & { + [SubKey in K]?: Maybe +} +export type MakeMaybe = Omit & { + [SubKey in K]: Maybe +} +export type MakeEmpty< + T extends { [key: string]: unknown }, + K extends keyof T +> = { [_ in K]?: never } +export type Incremental = + | T + | { + [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never + } /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { - ID: { input: string; output: string; } - String: { input: string; output: string; } - Boolean: { input: boolean; output: boolean; } - Int: { input: number; output: number; } - Float: { input: number; output: number; } - BigInt: { input: bigint; output: bigint; } - JSONObject: { input: any; output: any; } - UInt8: { input: number; output: number; } -}; + ID: { input: string; output: string } + String: { input: string; output: string } + Boolean: { input: boolean; output: boolean } + Int: { input: number; output: number } + Float: { input: number; output: number } + BigInt: { input: bigint; output: bigint } + JSONObject: { input: any; output: any } + UInt8: { input: number; output: number } +} export type AdditionalProperty = { - __typename?: 'AdditionalProperty'; - key: Scalars['String']['output']; - value: Scalars['String']['output']; - visibleInOpenPayments: Scalars['Boolean']['output']; -}; + __typename?: 'AdditionalProperty' + key: Scalars['String']['output'] + value: Scalars['String']['output'] + visibleInOpenPayments: Scalars['Boolean']['output'] +} export type AdditionalPropertyInput = { - key: Scalars['String']['input']; - value: Scalars['String']['input']; - visibleInOpenPayments: Scalars['Boolean']['input']; -}; + key: Scalars['String']['input'] + value: Scalars['String']['input'] + visibleInOpenPayments: Scalars['Boolean']['input'] +} export enum Alg { EdDsa = 'EdDSA' } export type Amount = { - __typename?: 'Amount'; + __typename?: 'Amount' /** [ISO 4217 currency code](https://en.wikipedia.org/wiki/ISO_4217), e.g. `USD` */ - assetCode: Scalars['String']['output']; + assetCode: Scalars['String']['output'] /** Difference in orders of magnitude between the standard unit of an asset and a corresponding fractional unit */ - assetScale: Scalars['UInt8']['output']; - value: Scalars['BigInt']['output']; -}; + assetScale: Scalars['UInt8']['output'] + value: Scalars['BigInt']['output'] +} export type AmountInput = { /** [ISO 4217 currency code](https://en.wikipedia.org/wiki/ISO_4217), e.g. `USD` */ - assetCode: Scalars['String']['input']; + assetCode: Scalars['String']['input'] /** Difference in orders of magnitude between the standard unit of an asset and a corresponding fractional unit */ - assetScale: Scalars['UInt8']['input']; - value: Scalars['BigInt']['input']; -}; + assetScale: Scalars['UInt8']['input'] + value: Scalars['BigInt']['input'] +} export type Asset = Model & { - __typename?: 'Asset'; + __typename?: 'Asset' /** [ISO 4217 currency code](https://en.wikipedia.org/wiki/ISO_4217), e.g. `USD` */ - code: Scalars['String']['output']; + code: Scalars['String']['output'] /** Date-time of creation */ - createdAt: Scalars['String']['output']; + createdAt: Scalars['String']['output'] /** Fetch a page of asset fees */ - fees?: Maybe; + fees?: Maybe /** Asset id */ - id: Scalars['ID']['output']; + id: Scalars['ID']['output'] /** Available liquidity */ - liquidity?: Maybe; + liquidity?: Maybe /** Account Servicing Entity will be notified via a webhook event if liquidity falls below this value */ - liquidityThreshold?: Maybe; + liquidityThreshold?: Maybe /** The receiving fee structure for the asset */ - receivingFee?: Maybe; + receivingFee?: Maybe /** Difference in orders of magnitude between the standard unit of an asset and a corresponding fractional unit */ - scale: Scalars['UInt8']['output']; + scale: Scalars['UInt8']['output'] /** The sending fee structure for the asset */ - sendingFee?: Maybe; + sendingFee?: Maybe /** Minimum amount of liquidity that can be withdrawn from the asset */ - withdrawalThreshold?: Maybe; -}; - + withdrawalThreshold?: Maybe +} export type AssetFeesArgs = { - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; + after?: InputMaybe + before?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type AssetEdge = { - __typename?: 'AssetEdge'; - cursor: Scalars['String']['output']; - node: Asset; -}; + __typename?: 'AssetEdge' + cursor: Scalars['String']['output'] + node: Asset +} export type AssetMutationResponse = { - __typename?: 'AssetMutationResponse'; - asset?: Maybe; -}; + __typename?: 'AssetMutationResponse' + asset?: Maybe +} export type AssetsConnection = { - __typename?: 'AssetsConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'AssetsConnection' + edges: Array + pageInfo: PageInfo +} export type BasePayment = { - client?: Maybe; - createdAt: Scalars['String']['output']; - id: Scalars['ID']['output']; - metadata?: Maybe; - walletAddressId: Scalars['ID']['output']; -}; + client?: Maybe + createdAt: Scalars['String']['output'] + id: Scalars['ID']['output'] + metadata?: Maybe + walletAddressId: Scalars['ID']['output'] +} export type CancelOutgoingPaymentInput = { /** Outgoing payment id */ - id: Scalars['ID']['input']; + id: Scalars['ID']['input'] /** Reason why this Outgoing Payment has been cancelled. This value will be publicly visible in the metadata field if this outgoing payment is requested through Open Payments. */ - reason?: InputMaybe; -}; + reason?: InputMaybe +} export type CreateAssetInput = { /** [ISO 4217 currency code](https://en.wikipedia.org/wiki/ISO_4217), e.g. `USD` */ - code: Scalars['String']['input']; + code: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Account Servicing Entity will be notified via a webhook event if liquidity falls below this value */ - liquidityThreshold?: InputMaybe; + liquidityThreshold?: InputMaybe /** Difference in orders of magnitude between the standard unit of an asset and a corresponding fractional unit */ - scale: Scalars['UInt8']['input']; + scale: Scalars['UInt8']['input'] /** Minimum amount of liquidity that can be withdrawn from the asset */ - withdrawalThreshold?: InputMaybe; -}; + withdrawalThreshold?: InputMaybe +} export type CreateAssetLiquidityWithdrawalInput = { /** Amount of withdrawal. */ - amount: Scalars['BigInt']['input']; + amount: Scalars['BigInt']['input'] /** The id of the asset to create the withdrawal for. */ - assetId: Scalars['String']['input']; + assetId: Scalars['String']['input'] /** The id of the withdrawal. */ - id: Scalars['String']['input']; + id: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; + idempotencyKey: Scalars['String']['input'] /** This is the interval in seconds after a pending transfer's created at which it may be posted or voided. Zero denotes a no timeout single-phase posted transfer. */ - timeoutSeconds: Scalars['BigInt']['input']; -}; + timeoutSeconds: Scalars['BigInt']['input'] +} export type CreateIncomingPaymentInput = { /** Expiration date-time */ - expiresAt?: InputMaybe; + expiresAt?: InputMaybe /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Maximum amount to be received */ - incomingAmount?: InputMaybe; + incomingAmount?: InputMaybe /** Additional metadata associated with the incoming payment. */ - metadata?: InputMaybe; + metadata?: InputMaybe /** Id of the wallet address under which the incoming payment will be created */ - walletAddressId: Scalars['String']['input']; -}; + walletAddressId: Scalars['String']['input'] +} export type CreateIncomingPaymentWithdrawalInput = { /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; + idempotencyKey: Scalars['String']['input'] /** The id of the incoming payment to withdraw from. */ - incomingPaymentId: Scalars['String']['input']; + incomingPaymentId: Scalars['String']['input'] /** This is the interval in seconds after a pending transfer's created at which it may be posted or voided. Zero denotes a no timeout single-phase posted transfer. */ - timeoutSeconds: Scalars['BigInt']['input']; -}; + timeoutSeconds: Scalars['BigInt']['input'] +} export type CreateOrUpdatePeerByUrlInput = { /** Asset id of peering relationship */ - assetId: Scalars['String']['input']; + assetId: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Account Servicing Entity will be notified via a webhook event if peer liquidity falls below this value */ - liquidityThreshold?: InputMaybe; + liquidityThreshold?: InputMaybe /** Amount of liquidity to deposit for peer */ - liquidityToDeposit?: InputMaybe; + liquidityToDeposit?: InputMaybe /** Maximum packet amount that the peer accepts */ - maxPacketAmount?: InputMaybe; + maxPacketAmount?: InputMaybe /** Peer's internal name for overriding auto-peer's default naming */ - name?: InputMaybe; + name?: InputMaybe /** Peer's URL address at which the peer accepts auto-peering requests */ - peerUrl: Scalars['String']['input']; -}; + peerUrl: Scalars['String']['input'] +} export type CreateOrUpdatePeerByUrlMutationResponse = { - __typename?: 'CreateOrUpdatePeerByUrlMutationResponse'; - peer?: Maybe; -}; + __typename?: 'CreateOrUpdatePeerByUrlMutationResponse' + peer?: Maybe +} export type CreateOutgoingPaymentFromIncomingPaymentInput = { /** Amount to send (fixed send) */ - debitAmount: AmountInput; + debitAmount: AmountInput /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Incoming payment url to create the outgoing payment from */ - incomingPayment: Scalars['String']['input']; + incomingPayment: Scalars['String']['input'] /** Additional metadata associated with the outgoing payment. */ - metadata?: InputMaybe; + metadata?: InputMaybe /** Id of the wallet address under which the outgoing payment will be created */ - walletAddressId: Scalars['String']['input']; -}; + walletAddressId: Scalars['String']['input'] +} export type CreateOutgoingPaymentInput = { /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Additional metadata associated with the outgoing payment. */ - metadata?: InputMaybe; + metadata?: InputMaybe /** Id of the corresponding quote for that outgoing payment */ - quoteId: Scalars['String']['input']; + quoteId: Scalars['String']['input'] /** Id of the wallet address under which the outgoing payment will be created */ - walletAddressId: Scalars['String']['input']; -}; + walletAddressId: Scalars['String']['input'] +} export type CreateOutgoingPaymentWithdrawalInput = { /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; + idempotencyKey: Scalars['String']['input'] /** The id of the outgoing payment to withdraw from. */ - outgoingPaymentId: Scalars['String']['input']; + outgoingPaymentId: Scalars['String']['input'] /** This is the interval in seconds after a pending transfer's created at which it may be posted or voided. Zero denotes a no timeout single-phase posted transfer. */ - timeoutSeconds: Scalars['BigInt']['input']; -}; + timeoutSeconds: Scalars['BigInt']['input'] +} export type CreatePeerInput = { /** Asset id of peering relationship */ - assetId: Scalars['String']['input']; + assetId: Scalars['String']['input'] /** Peering connection details */ - http: HttpInput; + http: HttpInput /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Initial amount of liquidity to deposit for peer */ - initialLiquidity?: InputMaybe; + initialLiquidity?: InputMaybe /** Account Servicing Entity will be notified via a webhook event if peer liquidity falls below this value */ - liquidityThreshold?: InputMaybe; + liquidityThreshold?: InputMaybe /** Maximum packet amount that the peer accepts */ - maxPacketAmount?: InputMaybe; + maxPacketAmount?: InputMaybe /** Peer's internal name */ - name?: InputMaybe; + name?: InputMaybe /** Peer's ILP address */ - staticIlpAddress: Scalars['String']['input']; -}; + staticIlpAddress: Scalars['String']['input'] +} export type CreatePeerLiquidityWithdrawalInput = { /** Amount of withdrawal. */ - amount: Scalars['BigInt']['input']; + amount: Scalars['BigInt']['input'] /** The id of the withdrawal. */ - id: Scalars['String']['input']; + id: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; + idempotencyKey: Scalars['String']['input'] /** The id of the peer to create the withdrawal for. */ - peerId: Scalars['String']['input']; + peerId: Scalars['String']['input'] /** This is the interval in seconds after a pending transfer's created at which it may be posted or voided. Zero denotes a no timeout single-phase posted transfer. */ - timeoutSeconds: Scalars['BigInt']['input']; -}; + timeoutSeconds: Scalars['BigInt']['input'] +} export type CreatePeerMutationResponse = { - __typename?: 'CreatePeerMutationResponse'; - peer?: Maybe; -}; + __typename?: 'CreatePeerMutationResponse' + peer?: Maybe +} export type CreateQuoteInput = { /** Amount to send (fixed send) */ - debitAmount?: InputMaybe; + debitAmount?: InputMaybe /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Amount to receive (fixed receive) */ - receiveAmount?: InputMaybe; + receiveAmount?: InputMaybe /** Wallet address URL of the receiver */ - receiver: Scalars['String']['input']; + receiver: Scalars['String']['input'] /** Id of the wallet address under which the quote will be created */ - walletAddressId: Scalars['String']['input']; -}; + walletAddressId: Scalars['String']['input'] +} export type CreateReceiverInput = { /** Expiration date-time */ - expiresAt?: InputMaybe; + expiresAt?: InputMaybe /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Maximum amount to be received */ - incomingAmount?: InputMaybe; + incomingAmount?: InputMaybe /** Additional metadata associated with the incoming payment. */ - metadata?: InputMaybe; + metadata?: InputMaybe /** Receiving wallet address URL */ - walletAddressUrl: Scalars['String']['input']; -}; + walletAddressUrl: Scalars['String']['input'] +} export type CreateReceiverResponse = { - __typename?: 'CreateReceiverResponse'; - receiver?: Maybe; -}; + __typename?: 'CreateReceiverResponse' + receiver?: Maybe +} export type CreateWalletAddressInput = { /** Additional properties associated with the [walletAddress]. */ - additionalProperties?: InputMaybe>; + additionalProperties?: InputMaybe> /** Asset of the wallet address */ - assetId: Scalars['String']['input']; + assetId: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Public name associated with the wallet address */ - publicName?: InputMaybe; + publicName?: InputMaybe /** Wallet Address URL */ - url: Scalars['String']['input']; -}; + url: Scalars['String']['input'] +} export type CreateWalletAddressKeyInput = { /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Public key */ - jwk: JwkInput; - walletAddressId: Scalars['String']['input']; -}; + jwk: JwkInput + walletAddressId: Scalars['String']['input'] +} export type CreateWalletAddressKeyMutationResponse = { - __typename?: 'CreateWalletAddressKeyMutationResponse'; - walletAddressKey?: Maybe; -}; + __typename?: 'CreateWalletAddressKeyMutationResponse' + walletAddressKey?: Maybe +} export type CreateWalletAddressMutationResponse = { - __typename?: 'CreateWalletAddressMutationResponse'; - walletAddress?: Maybe; -}; + __typename?: 'CreateWalletAddressMutationResponse' + walletAddress?: Maybe +} export type CreateWalletAddressWithdrawalInput = { /** The id of the withdrawal. */ - id: Scalars['String']['input']; + id: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; + idempotencyKey: Scalars['String']['input'] /** This is the interval in seconds after a pending transfer's created at which it may be posted or voided. Zero denotes a no timeout single-phase posted transfer. */ - timeoutSeconds: Scalars['BigInt']['input']; + timeoutSeconds: Scalars['BigInt']['input'] /** The id of the Open Payments wallet address to create the withdrawal for. */ - walletAddressId: Scalars['String']['input']; -}; + walletAddressId: Scalars['String']['input'] +} export enum Crv { Ed25519 = 'Ed25519' @@ -335,91 +347,91 @@ export enum Crv { export type DeleteAssetInput = { /** Asset id */ - id: Scalars['ID']['input']; + id: Scalars['ID']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; -}; + idempotencyKey?: InputMaybe +} export type DeleteAssetMutationResponse = { - __typename?: 'DeleteAssetMutationResponse'; - asset?: Maybe; -}; + __typename?: 'DeleteAssetMutationResponse' + asset?: Maybe +} export type DeletePeerInput = { - id: Scalars['ID']['input']; + id: Scalars['ID']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; -}; + idempotencyKey?: InputMaybe +} export type DeletePeerMutationResponse = { - __typename?: 'DeletePeerMutationResponse'; - success: Scalars['Boolean']['output']; -}; + __typename?: 'DeletePeerMutationResponse' + success: Scalars['Boolean']['output'] +} export type DepositAssetLiquidityInput = { /** Amount of liquidity to deposit. */ - amount: Scalars['BigInt']['input']; + amount: Scalars['BigInt']['input'] /** The id of the asset to deposit liquidity. */ - assetId: Scalars['String']['input']; + assetId: Scalars['String']['input'] /** The id of the transfer. */ - id: Scalars['String']['input']; + id: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; -}; + idempotencyKey: Scalars['String']['input'] +} export type DepositEventLiquidityInput = { /** The id of the event to deposit into. */ - eventId: Scalars['String']['input']; + eventId: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; -}; + idempotencyKey: Scalars['String']['input'] +} export type DepositOutgoingPaymentLiquidityInput = { /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; + idempotencyKey: Scalars['String']['input'] /** The id of the outgoing payment to deposit into. */ - outgoingPaymentId: Scalars['String']['input']; -}; + outgoingPaymentId: Scalars['String']['input'] +} export type DepositPeerLiquidityInput = { /** Amount of liquidity to deposit. */ - amount: Scalars['BigInt']['input']; + amount: Scalars['BigInt']['input'] /** The id of the transfer. */ - id: Scalars['String']['input']; + id: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; + idempotencyKey: Scalars['String']['input'] /** The id of the peer to deposit liquidity. */ - peerId: Scalars['String']['input']; -}; + peerId: Scalars['String']['input'] +} export type Fee = Model & { - __typename?: 'Fee'; + __typename?: 'Fee' /** Asset id associated with the fee */ - assetId: Scalars['ID']['output']; + assetId: Scalars['ID']['output'] /** Basis points fee. 1 basis point = 0.01%, 100 basis points = 1%, 10000 basis points = 100% */ - basisPoints: Scalars['Int']['output']; + basisPoints: Scalars['Int']['output'] /** Date-time of creation */ - createdAt: Scalars['String']['output']; + createdAt: Scalars['String']['output'] /** Fixed fee */ - fixed: Scalars['BigInt']['output']; + fixed: Scalars['BigInt']['output'] /** Fee id */ - id: Scalars['ID']['output']; + id: Scalars['ID']['output'] /** Type of fee (sending or receiving) */ - type: FeeType; -}; + type: FeeType +} export type FeeDetails = { /** Basis points fee. Should be between 0 and 10000 (inclusive). 1 basis point = 0.01%, 100 basis points = 1%, 10000 basis points = 100% */ - basisPoints: Scalars['Int']['input']; + basisPoints: Scalars['Int']['input'] /** A flat fee */ - fixed: Scalars['BigInt']['input']; -}; + fixed: Scalars['BigInt']['input'] +} export type FeeEdge = { - __typename?: 'FeeEdge'; - cursor: Scalars['String']['output']; - node: Fee; -}; + __typename?: 'FeeEdge' + cursor: Scalars['String']['output'] + node: Fee +} export enum FeeType { /** Receiver pays the fees */ @@ -429,88 +441,89 @@ export enum FeeType { } export type FeesConnection = { - __typename?: 'FeesConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'FeesConnection' + edges: Array + pageInfo: PageInfo +} export type FilterString = { - in: Array; -}; + in: Array +} export type Http = { - __typename?: 'Http'; + __typename?: 'Http' /** Outgoing connection details */ - outgoing: HttpOutgoing; -}; + outgoing: HttpOutgoing +} export type HttpIncomingInput = { /** Array of auth tokens accepted by this Rafiki instance */ - authTokens: Array; -}; + authTokens: Array +} export type HttpInput = { /** Incoming connection details */ - incoming?: InputMaybe; + incoming?: InputMaybe /** Outgoing connection details */ - outgoing: HttpOutgoingInput; -}; + outgoing: HttpOutgoingInput +} export type HttpOutgoing = { - __typename?: 'HttpOutgoing'; + __typename?: 'HttpOutgoing' /** Auth token to present at the peering Rafiki instance */ - authToken: Scalars['String']['output']; + authToken: Scalars['String']['output'] /** Peer's connection endpoint */ - endpoint: Scalars['String']['output']; -}; + endpoint: Scalars['String']['output'] +} export type HttpOutgoingInput = { /** Auth token to present at the peering Rafiki instance */ - authToken: Scalars['String']['input']; + authToken: Scalars['String']['input'] /** Peer's connection endpoint */ - endpoint: Scalars['String']['input']; -}; + endpoint: Scalars['String']['input'] +} -export type IncomingPayment = BasePayment & Model & { - __typename?: 'IncomingPayment'; - /** Information about the wallet address of the Open Payments client that created the incoming payment. */ - client?: Maybe; - /** Date-time of creation */ - createdAt: Scalars['String']['output']; - /** Date-time of expiry. After this time, the incoming payment will not accept further payments made to it. */ - expiresAt: Scalars['String']['output']; - /** Incoming Payment id */ - id: Scalars['ID']['output']; - /** The maximum amount that should be paid into the wallet address under this incoming payment. */ - incomingAmount?: Maybe; - /** Available liquidity */ - liquidity?: Maybe; - /** Additional metadata associated with the incoming payment. */ - metadata?: Maybe; - /** The total amount that has been paid into the wallet address under this incoming payment. */ - receivedAmount: Amount; - /** Incoming payment state */ - state: IncomingPaymentState; - /** Id of the wallet address under which this incoming payment was created. */ - walletAddressId: Scalars['ID']['output']; -}; +export type IncomingPayment = BasePayment & + Model & { + __typename?: 'IncomingPayment' + /** Information about the wallet address of the Open Payments client that created the incoming payment. */ + client?: Maybe + /** Date-time of creation */ + createdAt: Scalars['String']['output'] + /** Date-time of expiry. After this time, the incoming payment will not accept further payments made to it. */ + expiresAt: Scalars['String']['output'] + /** Incoming Payment id */ + id: Scalars['ID']['output'] + /** The maximum amount that should be paid into the wallet address under this incoming payment. */ + incomingAmount?: Maybe + /** Available liquidity */ + liquidity?: Maybe + /** Additional metadata associated with the incoming payment. */ + metadata?: Maybe + /** The total amount that has been paid into the wallet address under this incoming payment. */ + receivedAmount: Amount + /** Incoming payment state */ + state: IncomingPaymentState + /** Id of the wallet address under which this incoming payment was created. */ + walletAddressId: Scalars['ID']['output'] + } export type IncomingPaymentConnection = { - __typename?: 'IncomingPaymentConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'IncomingPaymentConnection' + edges: Array + pageInfo: PageInfo +} export type IncomingPaymentEdge = { - __typename?: 'IncomingPaymentEdge'; - cursor: Scalars['String']['output']; - node: IncomingPayment; -}; + __typename?: 'IncomingPaymentEdge' + cursor: Scalars['String']['output'] + node: IncomingPayment +} export type IncomingPaymentResponse = { - __typename?: 'IncomingPaymentResponse'; - payment?: Maybe; -}; + __typename?: 'IncomingPaymentResponse' + payment?: Maybe +} export enum IncomingPaymentState { /** The payment is either auto-completed once the received amount equals the expected `incomingAmount`, or it is completed manually via an API call. */ @@ -524,31 +537,31 @@ export enum IncomingPaymentState { } export type Jwk = { - __typename?: 'Jwk'; + __typename?: 'Jwk' /** Cryptographic algorithm family used with the key. The only allowed value is `EdDSA`. */ - alg: Alg; + alg: Alg /** Curve that the key pair is derived from. The only allowed value is `Ed25519`. */ - crv: Crv; + crv: Crv /** Key id */ - kid: Scalars['String']['output']; + kid: Scalars['String']['output'] /** Key type. The only allowed value is `OKP`. */ - kty: Kty; + kty: Kty /** Base64 url-encoded public key. */ - x: Scalars['String']['output']; -}; + x: Scalars['String']['output'] +} export type JwkInput = { /** Cryptographic algorithm family used with the key. The only allowed value is `EdDSA`. */ - alg: Alg; + alg: Alg /** Curve that the key pair is derived from. The only allowed value is `Ed25519`. */ - crv: Crv; + crv: Crv /** Key id */ - kid: Scalars['String']['input']; + kid: Scalars['String']['input'] /** Key type. The only allowed value is `OKP`. */ - kty: Kty; + kty: Kty /** Base64 url-encoded public key. */ - x: Scalars['String']['input']; -}; + x: Scalars['String']['input'] +} export enum Kty { Okp = 'OKP' @@ -570,288 +583,258 @@ export enum LiquidityError { } export type LiquidityMutationResponse = { - __typename?: 'LiquidityMutationResponse'; - success: Scalars['Boolean']['output']; -}; + __typename?: 'LiquidityMutationResponse' + success: Scalars['Boolean']['output'] +} export type Model = { - createdAt: Scalars['String']['output']; - id: Scalars['ID']['output']; -}; + createdAt: Scalars['String']['output'] + id: Scalars['ID']['output'] +} export type Mutation = { - __typename?: 'Mutation'; + __typename?: 'Mutation' /** Cancel Outgoing Payment */ - cancelOutgoingPayment: OutgoingPaymentResponse; + cancelOutgoingPayment: OutgoingPaymentResponse /** Create an asset */ - createAsset: AssetMutationResponse; + createAsset: AssetMutationResponse /** Withdraw asset liquidity */ - createAssetLiquidityWithdrawal?: Maybe; + createAssetLiquidityWithdrawal?: Maybe /** Create an internal Open Payments Incoming Payment. The receiver has a wallet address on this Rafiki instance. */ - createIncomingPayment: IncomingPaymentResponse; + createIncomingPayment: IncomingPaymentResponse /** Withdraw incoming payment liquidity */ - createIncomingPaymentWithdrawal?: Maybe; + createIncomingPaymentWithdrawal?: Maybe /** Create a peer using a URL */ - createOrUpdatePeerByUrl: CreateOrUpdatePeerByUrlMutationResponse; + createOrUpdatePeerByUrl: CreateOrUpdatePeerByUrlMutationResponse /** Create an Open Payments Outgoing Payment */ - createOutgoingPayment: OutgoingPaymentResponse; + createOutgoingPayment: OutgoingPaymentResponse /** Create an Open Payments Outgoing Payment from an incoming payment */ - createOutgoingPaymentFromIncomingPayment: OutgoingPaymentResponse; + createOutgoingPaymentFromIncomingPayment: OutgoingPaymentResponse /** Withdraw outgoing payment liquidity */ - createOutgoingPaymentWithdrawal?: Maybe; + createOutgoingPaymentWithdrawal?: Maybe /** Create a peer */ - createPeer: CreatePeerMutationResponse; + createPeer: CreatePeerMutationResponse /** Withdraw peer liquidity */ - createPeerLiquidityWithdrawal?: Maybe; + createPeerLiquidityWithdrawal?: Maybe /** Create an Open Payments Quote */ - createQuote: QuoteResponse; + createQuote: QuoteResponse /** Create an internal or external Open Payments Incoming Payment. The receiver has a wallet address on either this or another Open Payments resource server. */ - createReceiver: CreateReceiverResponse; + createReceiver: CreateReceiverResponse /** Create a wallet address */ - createWalletAddress: CreateWalletAddressMutationResponse; + createWalletAddress: CreateWalletAddressMutationResponse /** Add a public key to a wallet address that is used to verify Open Payments requests. */ - createWalletAddressKey?: Maybe; + createWalletAddressKey?: Maybe /** Withdraw liquidity from a wallet address received via Web Monetization. */ - createWalletAddressWithdrawal?: Maybe; + createWalletAddressWithdrawal?: Maybe /** Delete an asset */ - deleteAsset: DeleteAssetMutationResponse; + deleteAsset: DeleteAssetMutationResponse /** Delete a peer */ - deletePeer: DeletePeerMutationResponse; + deletePeer: DeletePeerMutationResponse /** Deposit asset liquidity */ - depositAssetLiquidity?: Maybe; + depositAssetLiquidity?: Maybe /** * Deposit webhook event liquidity * @deprecated Use `depositOutgoingPaymentLiquidity` */ - depositEventLiquidity?: Maybe; + depositEventLiquidity?: Maybe /** Deposit outgoing payment liquidity */ - depositOutgoingPaymentLiquidity?: Maybe; + depositOutgoingPaymentLiquidity?: Maybe /** Deposit peer liquidity */ - depositPeerLiquidity?: Maybe; + depositPeerLiquidity?: Maybe /** Post liquidity withdrawal. Withdrawals are two-phase commits and are committed via this mutation. */ - postLiquidityWithdrawal?: Maybe; + postLiquidityWithdrawal?: Maybe /** Revoke a public key associated with a wallet address. Open Payment requests using this key for request signatures will be denied going forward. */ - revokeWalletAddressKey?: Maybe; + revokeWalletAddressKey?: Maybe /** Set the fee on an asset */ - setFee: SetFeeResponse; + setFee: SetFeeResponse /** If automatic withdrawal of funds received via Web Monetization by the wallet address are disabled, this mutation can be used to trigger up to n withdrawal events. */ - triggerWalletAddressEvents: TriggerWalletAddressEventsMutationResponse; + triggerWalletAddressEvents: TriggerWalletAddressEventsMutationResponse /** Update an asset */ - updateAsset: AssetMutationResponse; + updateAsset: AssetMutationResponse /** Update a peer */ - updatePeer: UpdatePeerMutationResponse; + updatePeer: UpdatePeerMutationResponse /** Update a wallet address */ - updateWalletAddress: UpdateWalletAddressMutationResponse; + updateWalletAddress: UpdateWalletAddressMutationResponse /** Void liquidity withdrawal. Withdrawals are two-phase commits and are rolled back via this mutation. */ - voidLiquidityWithdrawal?: Maybe; + voidLiquidityWithdrawal?: Maybe /** * Withdraw webhook event liquidity * @deprecated Use `createOutgoingPaymentWithdrawal, createIncomingPaymentWithdrawal, or createWalletAddressWithdrawal` */ - withdrawEventLiquidity?: Maybe; -}; - + withdrawEventLiquidity?: Maybe +} export type MutationCancelOutgoingPaymentArgs = { - input: CancelOutgoingPaymentInput; -}; - + input: CancelOutgoingPaymentInput +} export type MutationCreateAssetArgs = { - input: CreateAssetInput; -}; - + input: CreateAssetInput +} export type MutationCreateAssetLiquidityWithdrawalArgs = { - input: CreateAssetLiquidityWithdrawalInput; -}; - + input: CreateAssetLiquidityWithdrawalInput +} export type MutationCreateIncomingPaymentArgs = { - input: CreateIncomingPaymentInput; -}; - + input: CreateIncomingPaymentInput +} export type MutationCreateIncomingPaymentWithdrawalArgs = { - input: CreateIncomingPaymentWithdrawalInput; -}; - + input: CreateIncomingPaymentWithdrawalInput +} export type MutationCreateOrUpdatePeerByUrlArgs = { - input: CreateOrUpdatePeerByUrlInput; -}; - + input: CreateOrUpdatePeerByUrlInput +} export type MutationCreateOutgoingPaymentArgs = { - input: CreateOutgoingPaymentInput; -}; - + input: CreateOutgoingPaymentInput +} export type MutationCreateOutgoingPaymentFromIncomingPaymentArgs = { - input: CreateOutgoingPaymentFromIncomingPaymentInput; -}; - + input: CreateOutgoingPaymentFromIncomingPaymentInput +} export type MutationCreateOutgoingPaymentWithdrawalArgs = { - input: CreateOutgoingPaymentWithdrawalInput; -}; - + input: CreateOutgoingPaymentWithdrawalInput +} export type MutationCreatePeerArgs = { - input: CreatePeerInput; -}; - + input: CreatePeerInput +} export type MutationCreatePeerLiquidityWithdrawalArgs = { - input: CreatePeerLiquidityWithdrawalInput; -}; - + input: CreatePeerLiquidityWithdrawalInput +} export type MutationCreateQuoteArgs = { - input: CreateQuoteInput; -}; - + input: CreateQuoteInput +} export type MutationCreateReceiverArgs = { - input: CreateReceiverInput; -}; - + input: CreateReceiverInput +} export type MutationCreateWalletAddressArgs = { - input: CreateWalletAddressInput; -}; - + input: CreateWalletAddressInput +} export type MutationCreateWalletAddressKeyArgs = { - input: CreateWalletAddressKeyInput; -}; - + input: CreateWalletAddressKeyInput +} export type MutationCreateWalletAddressWithdrawalArgs = { - input: CreateWalletAddressWithdrawalInput; -}; - + input: CreateWalletAddressWithdrawalInput +} export type MutationDeleteAssetArgs = { - input: DeleteAssetInput; -}; - + input: DeleteAssetInput +} export type MutationDeletePeerArgs = { - input: DeletePeerInput; -}; - + input: DeletePeerInput +} export type MutationDepositAssetLiquidityArgs = { - input: DepositAssetLiquidityInput; -}; - + input: DepositAssetLiquidityInput +} export type MutationDepositEventLiquidityArgs = { - input: DepositEventLiquidityInput; -}; - + input: DepositEventLiquidityInput +} export type MutationDepositOutgoingPaymentLiquidityArgs = { - input: DepositOutgoingPaymentLiquidityInput; -}; - + input: DepositOutgoingPaymentLiquidityInput +} export type MutationDepositPeerLiquidityArgs = { - input: DepositPeerLiquidityInput; -}; - + input: DepositPeerLiquidityInput +} export type MutationPostLiquidityWithdrawalArgs = { - input: PostLiquidityWithdrawalInput; -}; - + input: PostLiquidityWithdrawalInput +} export type MutationRevokeWalletAddressKeyArgs = { - input: RevokeWalletAddressKeyInput; -}; - + input: RevokeWalletAddressKeyInput +} export type MutationSetFeeArgs = { - input: SetFeeInput; -}; - + input: SetFeeInput +} export type MutationTriggerWalletAddressEventsArgs = { - input: TriggerWalletAddressEventsInput; -}; - + input: TriggerWalletAddressEventsInput +} export type MutationUpdateAssetArgs = { - input: UpdateAssetInput; -}; - + input: UpdateAssetInput +} export type MutationUpdatePeerArgs = { - input: UpdatePeerInput; -}; - + input: UpdatePeerInput +} export type MutationUpdateWalletAddressArgs = { - input: UpdateWalletAddressInput; -}; - + input: UpdateWalletAddressInput +} export type MutationVoidLiquidityWithdrawalArgs = { - input: VoidLiquidityWithdrawalInput; -}; - + input: VoidLiquidityWithdrawalInput +} export type MutationWithdrawEventLiquidityArgs = { - input: WithdrawEventLiquidityInput; -}; + input: WithdrawEventLiquidityInput +} -export type OutgoingPayment = BasePayment & Model & { - __typename?: 'OutgoingPayment'; - /** Information about the wallet address of the Open Payments client that created the outgoing payment. */ - client?: Maybe; - /** Date-time of creation */ - createdAt: Scalars['String']['output']; - /** Amount to send (fixed send) */ - debitAmount: Amount; - error?: Maybe; - /** Outgoing payment id */ - id: Scalars['ID']['output']; - /** Available liquidity */ - liquidity?: Maybe; - /** Additional metadata associated with the outgoing payment. */ - metadata?: Maybe; - /** Quote for this outgoing payment */ - quote?: Maybe; - /** Amount to receive (fixed receive) */ - receiveAmount: Amount; - /** Wallet address URL of the receiver */ - receiver: Scalars['String']['output']; - /** Amount already sent */ - sentAmount: Amount; - /** Outgoing payment state */ - state: OutgoingPaymentState; - stateAttempts: Scalars['Int']['output']; - /** Id of the wallet address under which this outgoing payment was created */ - walletAddressId: Scalars['ID']['output']; -}; +export type OutgoingPayment = BasePayment & + Model & { + __typename?: 'OutgoingPayment' + /** Information about the wallet address of the Open Payments client that created the outgoing payment. */ + client?: Maybe + /** Date-time of creation */ + createdAt: Scalars['String']['output'] + /** Amount to send (fixed send) */ + debitAmount: Amount + error?: Maybe + /** Outgoing payment id */ + id: Scalars['ID']['output'] + /** Available liquidity */ + liquidity?: Maybe + /** Additional metadata associated with the outgoing payment. */ + metadata?: Maybe + /** Quote for this outgoing payment */ + quote?: Maybe + /** Amount to receive (fixed receive) */ + receiveAmount: Amount + /** Wallet address URL of the receiver */ + receiver: Scalars['String']['output'] + /** Amount already sent */ + sentAmount: Amount + /** Outgoing payment state */ + state: OutgoingPaymentState + stateAttempts: Scalars['Int']['output'] + /** Id of the wallet address under which this outgoing payment was created */ + walletAddressId: Scalars['ID']['output'] + } export type OutgoingPaymentConnection = { - __typename?: 'OutgoingPaymentConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'OutgoingPaymentConnection' + edges: Array + pageInfo: PageInfo +} export type OutgoingPaymentEdge = { - __typename?: 'OutgoingPaymentEdge'; - cursor: Scalars['String']['output']; - node: OutgoingPayment; -}; + __typename?: 'OutgoingPaymentEdge' + cursor: Scalars['String']['output'] + node: OutgoingPayment +} export type OutgoingPaymentResponse = { - __typename?: 'OutgoingPaymentResponse'; - payment?: Maybe; -}; + __typename?: 'OutgoingPaymentResponse' + payment?: Maybe +} export enum OutgoingPaymentState { /** Payment cancelled */ @@ -867,53 +850,54 @@ export enum OutgoingPaymentState { } export type PageInfo = { - __typename?: 'PageInfo'; + __typename?: 'PageInfo' /** Paginating forwards: the cursor to continue. */ - endCursor?: Maybe; + endCursor?: Maybe /** Paginating forwards: Are there more pages? */ - hasNextPage: Scalars['Boolean']['output']; + hasNextPage: Scalars['Boolean']['output'] /** Paginating backwards: Are there more pages? */ - hasPreviousPage: Scalars['Boolean']['output']; + hasPreviousPage: Scalars['Boolean']['output'] /** Paginating backwards: the cursor to continue. */ - startCursor?: Maybe; -}; + startCursor?: Maybe +} -export type Payment = BasePayment & Model & { - __typename?: 'Payment'; - /** Information about the wallet address of the Open Payments client that created the payment. */ - client?: Maybe; - /** Date-time of creation */ - createdAt: Scalars['String']['output']; - /** Payment id */ - id: Scalars['ID']['output']; - /** Available liquidity */ - liquidity?: Maybe; - /** Additional metadata associated with the payment. */ - metadata?: Maybe; - /** Either the IncomingPaymentState or OutgoingPaymentState according to type */ - state: Scalars['String']['output']; - /** Type of payment */ - type: PaymentType; - /** Id of the wallet address under which this payment was created */ - walletAddressId: Scalars['ID']['output']; -}; +export type Payment = BasePayment & + Model & { + __typename?: 'Payment' + /** Information about the wallet address of the Open Payments client that created the payment. */ + client?: Maybe + /** Date-time of creation */ + createdAt: Scalars['String']['output'] + /** Payment id */ + id: Scalars['ID']['output'] + /** Available liquidity */ + liquidity?: Maybe + /** Additional metadata associated with the payment. */ + metadata?: Maybe + /** Either the IncomingPaymentState or OutgoingPaymentState according to type */ + state: Scalars['String']['output'] + /** Type of payment */ + type: PaymentType + /** Id of the wallet address under which this payment was created */ + walletAddressId: Scalars['ID']['output'] + } export type PaymentConnection = { - __typename?: 'PaymentConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'PaymentConnection' + edges: Array + pageInfo: PageInfo +} export type PaymentEdge = { - __typename?: 'PaymentEdge'; - cursor: Scalars['String']['output']; - node: Payment; -}; + __typename?: 'PaymentEdge' + cursor: Scalars['String']['output'] + node: Payment +} export type PaymentFilter = { - type?: InputMaybe; - walletAddressId?: InputMaybe; -}; + type?: InputMaybe + walletAddressId?: InputMaybe +} export enum PaymentType { Incoming = 'INCOMING', @@ -921,248 +905,236 @@ export enum PaymentType { } export type Peer = Model & { - __typename?: 'Peer'; + __typename?: 'Peer' /** Asset of peering relationship */ - asset: Asset; + asset: Asset /** Date-time of creation */ - createdAt: Scalars['String']['output']; + createdAt: Scalars['String']['output'] /** Peering connection details */ - http: Http; + http: Http /** Peer id */ - id: Scalars['ID']['output']; + id: Scalars['ID']['output'] /** Available liquidity */ - liquidity?: Maybe; + liquidity?: Maybe /** Account Servicing Entity will be notified via a webhook event if peer liquidity falls below this value */ - liquidityThreshold?: Maybe; + liquidityThreshold?: Maybe /** Maximum packet amount that the peer accepts */ - maxPacketAmount?: Maybe; + maxPacketAmount?: Maybe /** Peer's public name */ - name?: Maybe; + name?: Maybe /** Peer's ILP address */ - staticIlpAddress: Scalars['String']['output']; -}; + staticIlpAddress: Scalars['String']['output'] +} export type PeerEdge = { - __typename?: 'PeerEdge'; - cursor: Scalars['String']['output']; - node: Peer; -}; + __typename?: 'PeerEdge' + cursor: Scalars['String']['output'] + node: Peer +} export type PeersConnection = { - __typename?: 'PeersConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'PeersConnection' + edges: Array + pageInfo: PageInfo +} export type PostLiquidityWithdrawalInput = { /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; + idempotencyKey: Scalars['String']['input'] /** The id of the liquidity withdrawal to post. */ - withdrawalId: Scalars['String']['input']; -}; + withdrawalId: Scalars['String']['input'] +} export type Query = { - __typename?: 'Query'; + __typename?: 'Query' /** Fetch an asset */ - asset?: Maybe; + asset?: Maybe /** Fetch a page of assets. */ - assets: AssetsConnection; + assets: AssetsConnection /** Fetch an Open Payments incoming payment */ - incomingPayment?: Maybe; + incomingPayment?: Maybe /** Fetch an Open Payments outgoing payment */ - outgoingPayment?: Maybe; + outgoingPayment?: Maybe /** Fetch a page of combined payments */ - payments: PaymentConnection; + payments: PaymentConnection /** Fetch a peer */ - peer?: Maybe; + peer?: Maybe /** Fetch a page of peers. */ - peers: PeersConnection; + peers: PeersConnection /** Fetch an Open Payments quote */ - quote?: Maybe; + quote?: Maybe /** Get an local or remote Open Payments Incoming Payment. The receiver has a wallet address on either this or another Open Payments resource server. */ - receiver?: Maybe; + receiver?: Maybe /** Fetch a wallet address. */ - walletAddress?: Maybe; + walletAddress?: Maybe /** Fetch a page of wallet addresses. */ - walletAddresses: WalletAddressesConnection; + walletAddresses: WalletAddressesConnection /** Fetch a page of webhook events */ - webhookEvents: WebhookEventsConnection; -}; - + webhookEvents: WebhookEventsConnection +} export type QueryAssetArgs = { - id: Scalars['String']['input']; -}; - + id: Scalars['String']['input'] +} export type QueryAssetsArgs = { - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; - + after?: InputMaybe + before?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type QueryIncomingPaymentArgs = { - id: Scalars['String']['input']; -}; - + id: Scalars['String']['input'] +} export type QueryOutgoingPaymentArgs = { - id: Scalars['String']['input']; -}; - + id: Scalars['String']['input'] +} export type QueryPaymentsArgs = { - after?: InputMaybe; - before?: InputMaybe; - filter?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; - + after?: InputMaybe + before?: InputMaybe + filter?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type QueryPeerArgs = { - id: Scalars['String']['input']; -}; - + id: Scalars['String']['input'] +} export type QueryPeersArgs = { - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; - + after?: InputMaybe + before?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type QueryQuoteArgs = { - id: Scalars['String']['input']; -}; - + id: Scalars['String']['input'] +} export type QueryReceiverArgs = { - id: Scalars['String']['input']; -}; - + id: Scalars['String']['input'] +} export type QueryWalletAddressArgs = { - id: Scalars['String']['input']; -}; - + id: Scalars['String']['input'] +} export type QueryWalletAddressesArgs = { - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; - + after?: InputMaybe + before?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type QueryWebhookEventsArgs = { - after?: InputMaybe; - before?: InputMaybe; - filter?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; + after?: InputMaybe + before?: InputMaybe + filter?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type Quote = { - __typename?: 'Quote'; + __typename?: 'Quote' /** Date-time of creation */ - createdAt: Scalars['String']['output']; + createdAt: Scalars['String']['output'] /** Amount to send (fixed send) */ - debitAmount: Amount; + debitAmount: Amount /** Date-time of expiration */ - expiresAt: Scalars['String']['output']; + expiresAt: Scalars['String']['output'] /** Upper bound of probed exchange rate */ - highEstimatedExchangeRate: Scalars['Float']['output']; + highEstimatedExchangeRate: Scalars['Float']['output'] /** Quote id */ - id: Scalars['ID']['output']; + id: Scalars['ID']['output'] /** Lower bound of probed exchange rate */ - lowEstimatedExchangeRate: Scalars['Float']['output']; + lowEstimatedExchangeRate: Scalars['Float']['output'] /** Maximum value per packet allowed on the possible routes */ - maxPacketAmount: Scalars['BigInt']['output']; + maxPacketAmount: Scalars['BigInt']['output'] /** Aggregate exchange rate the payment is guaranteed to meet */ - minExchangeRate: Scalars['Float']['output']; + minExchangeRate: Scalars['Float']['output'] /** Amount to receive (fixed receive) */ - receiveAmount: Amount; + receiveAmount: Amount /** Wallet address URL of the receiver */ - receiver: Scalars['String']['output']; + receiver: Scalars['String']['output'] /** Id of the wallet address under which this quote was created */ - walletAddressId: Scalars['ID']['output']; -}; + walletAddressId: Scalars['ID']['output'] +} export type QuoteConnection = { - __typename?: 'QuoteConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'QuoteConnection' + edges: Array + pageInfo: PageInfo +} export type QuoteEdge = { - __typename?: 'QuoteEdge'; - cursor: Scalars['String']['output']; - node: Quote; -}; + __typename?: 'QuoteEdge' + cursor: Scalars['String']['output'] + node: Quote +} export type QuoteResponse = { - __typename?: 'QuoteResponse'; - quote?: Maybe; -}; + __typename?: 'QuoteResponse' + quote?: Maybe +} export type Receiver = { - __typename?: 'Receiver'; + __typename?: 'Receiver' /** Describes whether the incoming payment has completed receiving funds. */ - completed: Scalars['Boolean']['output']; + completed: Scalars['Boolean']['output'] /** Date-time of creation */ - createdAt: Scalars['String']['output']; + createdAt: Scalars['String']['output'] /** Date-time of expiry. After this time, the incoming payment will accept further payments made to it. */ - expiresAt?: Maybe; + expiresAt?: Maybe /** Incoming payment URL */ - id: Scalars['String']['output']; + id: Scalars['String']['output'] /** The maximum amount that should be paid into the wallet address under this incoming payment. */ - incomingAmount?: Maybe; + incomingAmount?: Maybe /** Additional metadata associated with the incoming payment. */ - metadata?: Maybe; + metadata?: Maybe /** The total amount that has been paid into the wallet address under this incoming payment. */ - receivedAmount: Amount; + receivedAmount: Amount /** Date-time of last update */ - updatedAt: Scalars['String']['output']; + updatedAt: Scalars['String']['output'] /** Wallet address URL under which the incoming payment was created */ - walletAddressUrl: Scalars['String']['output']; -}; + walletAddressUrl: Scalars['String']['output'] +} export type RevokeWalletAddressKeyInput = { /** Internal id of key */ - id: Scalars['String']['input']; + id: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; -}; + idempotencyKey?: InputMaybe +} export type RevokeWalletAddressKeyMutationResponse = { - __typename?: 'RevokeWalletAddressKeyMutationResponse'; - walletAddressKey?: Maybe; -}; + __typename?: 'RevokeWalletAddressKeyMutationResponse' + walletAddressKey?: Maybe +} export type SetFeeInput = { /** Asset id to add the fee to */ - assetId: Scalars['ID']['input']; + assetId: Scalars['ID']['input'] /** Fee values */ - fee: FeeDetails; + fee: FeeDetails /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Type of fee (sending or receiving) */ - type: FeeType; -}; + type: FeeType +} export type SetFeeResponse = { - __typename?: 'SetFeeResponse'; - fee?: Maybe; -}; + __typename?: 'SetFeeResponse' + fee?: Maybe +} export enum SortOrder { /** Choose ascending order for results. */ @@ -1173,170 +1145,166 @@ export enum SortOrder { export type TriggerWalletAddressEventsInput = { /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Maximum number of events being triggered (n). */ - limit: Scalars['Int']['input']; -}; + limit: Scalars['Int']['input'] +} export type TriggerWalletAddressEventsMutationResponse = { - __typename?: 'TriggerWalletAddressEventsMutationResponse'; + __typename?: 'TriggerWalletAddressEventsMutationResponse' /** Number of events triggered */ - count?: Maybe; -}; + count?: Maybe +} export type UpdateAssetInput = { /** Asset id */ - id: Scalars['String']['input']; + id: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Account Servicing Entity will be notified via a webhook event if liquidity falls below this new value */ - liquidityThreshold?: InputMaybe; + liquidityThreshold?: InputMaybe /** New minimum amount of liquidity that can be withdrawn from the asset */ - withdrawalThreshold?: InputMaybe; -}; + withdrawalThreshold?: InputMaybe +} export type UpdatePeerInput = { /** New peering connection details */ - http?: InputMaybe; + http?: InputMaybe /** Peer id */ - id: Scalars['String']['input']; + id: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** Account Servicing Entity will be notified via a webhook event if peer liquidity falls below this new value */ - liquidityThreshold?: InputMaybe; + liquidityThreshold?: InputMaybe /** New maximum packet amount that the peer accepts */ - maxPacketAmount?: InputMaybe; + maxPacketAmount?: InputMaybe /** Peer's new public name */ - name?: InputMaybe; + name?: InputMaybe /** Peer's new ILP address */ - staticIlpAddress?: InputMaybe; -}; + staticIlpAddress?: InputMaybe +} export type UpdatePeerMutationResponse = { - __typename?: 'UpdatePeerMutationResponse'; - peer?: Maybe; -}; + __typename?: 'UpdatePeerMutationResponse' + peer?: Maybe +} export type UpdateWalletAddressInput = { /** List additional properties associated with this wallet address. */ - additionalProperties?: InputMaybe>; + additionalProperties?: InputMaybe> /** ID of wallet address to update */ - id: Scalars['ID']['input']; + id: Scalars['ID']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey?: InputMaybe; + idempotencyKey?: InputMaybe /** New public name for wallet address */ - publicName?: InputMaybe; + publicName?: InputMaybe /** New status to set the wallet address to */ - status?: InputMaybe; -}; + status?: InputMaybe +} export type UpdateWalletAddressMutationResponse = { - __typename?: 'UpdateWalletAddressMutationResponse'; - walletAddress?: Maybe; -}; + __typename?: 'UpdateWalletAddressMutationResponse' + walletAddress?: Maybe +} export type VoidLiquidityWithdrawalInput = { /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; + idempotencyKey: Scalars['String']['input'] /** The id of the liquidity withdrawal to void. */ - withdrawalId: Scalars['String']['input']; -}; + withdrawalId: Scalars['String']['input'] +} export type WalletAddress = Model & { - __typename?: 'WalletAddress'; + __typename?: 'WalletAddress' /** List additional properties associated with this wallet address. */ - additionalProperties?: Maybe>>; + additionalProperties?: Maybe>> /** Asset of the wallet address */ - asset: Asset; + asset: Asset /** Date-time of creation */ - createdAt: Scalars['String']['output']; + createdAt: Scalars['String']['output'] /** Wallet address id */ - id: Scalars['ID']['output']; + id: Scalars['ID']['output'] /** List of incoming payments received by this wallet address */ - incomingPayments?: Maybe; + incomingPayments?: Maybe /** Available liquidity */ - liquidity?: Maybe; + liquidity?: Maybe /** List of outgoing payments sent from this wallet address */ - outgoingPayments?: Maybe; + outgoingPayments?: Maybe /** Public name associated with the wallet address */ - publicName?: Maybe; + publicName?: Maybe /** List of quotes created at this wallet address */ - quotes?: Maybe; + quotes?: Maybe /** Status of the wallet address */ - status: WalletAddressStatus; + status: WalletAddressStatus /** Wallet Address URL */ - url: Scalars['String']['output']; + url: Scalars['String']['output'] /** List of keys associated with this wallet address */ - walletAddressKeys?: Maybe; -}; - + walletAddressKeys?: Maybe +} export type WalletAddressIncomingPaymentsArgs = { - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; - + after?: InputMaybe + before?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type WalletAddressOutgoingPaymentsArgs = { - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; - + after?: InputMaybe + before?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type WalletAddressQuotesArgs = { - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; - + after?: InputMaybe + before?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type WalletAddressWalletAddressKeysArgs = { - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - sortOrder?: InputMaybe; -}; + after?: InputMaybe + before?: InputMaybe + first?: InputMaybe + last?: InputMaybe + sortOrder?: InputMaybe +} export type WalletAddressEdge = { - __typename?: 'WalletAddressEdge'; - cursor: Scalars['String']['output']; - node: WalletAddress; -}; + __typename?: 'WalletAddressEdge' + cursor: Scalars['String']['output'] + node: WalletAddress +} export type WalletAddressKey = Model & { - __typename?: 'WalletAddressKey'; + __typename?: 'WalletAddressKey' /** Date-time of creation */ - createdAt: Scalars['String']['output']; + createdAt: Scalars['String']['output'] /** Internal id of key */ - id: Scalars['ID']['output']; + id: Scalars['ID']['output'] /** Public key */ - jwk: Jwk; + jwk: Jwk /** Indicator whether the key has been revoked */ - revoked: Scalars['Boolean']['output']; + revoked: Scalars['Boolean']['output'] /** Id of the wallet address to which this key belongs to */ - walletAddressId: Scalars['ID']['output']; -}; + walletAddressId: Scalars['ID']['output'] +} export type WalletAddressKeyConnection = { - __typename?: 'WalletAddressKeyConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'WalletAddressKeyConnection' + edges: Array + pageInfo: PageInfo +} export type WalletAddressKeyEdge = { - __typename?: 'WalletAddressKeyEdge'; - cursor: Scalars['String']['output']; - node: WalletAddressKey; -}; + __typename?: 'WalletAddressKeyEdge' + cursor: Scalars['String']['output'] + node: WalletAddressKey +} export enum WalletAddressStatus { /** Default status */ @@ -1346,167 +1314,451 @@ export enum WalletAddressStatus { } export type WalletAddressWithdrawal = { - __typename?: 'WalletAddressWithdrawal'; + __typename?: 'WalletAddressWithdrawal' /** Amount to withdraw */ - amount: Scalars['BigInt']['output']; + amount: Scalars['BigInt']['output'] /** Withdrawal Id */ - id: Scalars['ID']['output']; + id: Scalars['ID']['output'] /** Wallet address details */ - walletAddress: WalletAddress; -}; + walletAddress: WalletAddress +} export type WalletAddressWithdrawalMutationResponse = { - __typename?: 'WalletAddressWithdrawalMutationResponse'; - withdrawal?: Maybe; -}; + __typename?: 'WalletAddressWithdrawalMutationResponse' + withdrawal?: Maybe +} export type WalletAddressesConnection = { - __typename?: 'WalletAddressesConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'WalletAddressesConnection' + edges: Array + pageInfo: PageInfo +} export type WebhookEvent = Model & { - __typename?: 'WebhookEvent'; + __typename?: 'WebhookEvent' /** Date-time of creation */ - createdAt: Scalars['String']['output']; + createdAt: Scalars['String']['output'] /** Stringified JSON data */ - data: Scalars['JSONObject']['output']; + data: Scalars['JSONObject']['output'] /** Event id */ - id: Scalars['ID']['output']; + id: Scalars['ID']['output'] /** Type of event */ - type: Scalars['String']['output']; -}; + type: Scalars['String']['output'] +} export type WebhookEventFilter = { - type?: InputMaybe; -}; + type?: InputMaybe +} export type WebhookEventsConnection = { - __typename?: 'WebhookEventsConnection'; - edges: Array; - pageInfo: PageInfo; -}; + __typename?: 'WebhookEventsConnection' + edges: Array + pageInfo: PageInfo +} export type WebhookEventsEdge = { - __typename?: 'WebhookEventsEdge'; - cursor: Scalars['String']['output']; - node: WebhookEvent; -}; + __typename?: 'WebhookEventsEdge' + cursor: Scalars['String']['output'] + node: WebhookEvent +} export type WithdrawEventLiquidityInput = { /** The id of the event to withdraw from. */ - eventId: Scalars['String']['input']; + eventId: Scalars['String']['input'] /** Unique key to ensure duplicate or retried requests are processed only once. See [idempotence](https://en.wikipedia.org/wiki/Idempotence) */ - idempotencyKey: Scalars['String']['input']; -}; + idempotencyKey: Scalars['String']['input'] +} export type CreateAssetMutationVariables = Exact<{ - input: CreateAssetInput; -}>; - - -export type CreateAssetMutation = { __typename?: 'Mutation', createAsset: { __typename?: 'AssetMutationResponse', asset?: { __typename?: 'Asset', id: string, code: string, scale: number } | null } }; + input: CreateAssetInput +}> + +export type CreateAssetMutation = { + __typename?: 'Mutation' + createAsset: { + __typename?: 'AssetMutationResponse' + asset?: { + __typename?: 'Asset' + id: string + code: string + scale: number + } | null + } +} export type GetAssetsQueryVariables = Exact<{ - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; -}>; - - -export type GetAssetsQuery = { __typename?: 'Query', assets: { __typename?: 'AssetsConnection', edges: Array<{ __typename?: 'AssetEdge', cursor: string, node: { __typename?: 'Asset', code: string, createdAt: string, id: string, scale: number, withdrawalThreshold?: bigint | null } }>, pageInfo: { __typename?: 'PageInfo', endCursor?: string | null, hasNextPage: boolean, hasPreviousPage: boolean, startCursor?: string | null } } }; + after?: InputMaybe + before?: InputMaybe + first?: InputMaybe + last?: InputMaybe +}> + +export type GetAssetsQuery = { + __typename?: 'Query' + assets: { + __typename?: 'AssetsConnection' + edges: Array<{ + __typename?: 'AssetEdge' + cursor: string + node: { + __typename?: 'Asset' + code: string + createdAt: string + id: string + scale: number + withdrawalThreshold?: bigint | null + } + }> + pageInfo: { + __typename?: 'PageInfo' + endCursor?: string | null + hasNextPage: boolean + hasPreviousPage: boolean + startCursor?: string | null + } + } +} export type GetAssetQueryVariables = Exact<{ - id: Scalars['String']['input']; -}>; - - -export type GetAssetQuery = { __typename?: 'Query', asset?: { __typename?: 'Asset', code: string, createdAt: string, id: string, scale: number, withdrawalThreshold?: bigint | null } | null }; + id: Scalars['String']['input'] +}> + +export type GetAssetQuery = { + __typename?: 'Query' + asset?: { + __typename?: 'Asset' + code: string + createdAt: string + id: string + scale: number + withdrawalThreshold?: bigint | null + } | null +} export type CreateIncomingPaymentMutationVariables = Exact<{ - input: CreateIncomingPaymentInput; -}>; - - -export type CreateIncomingPaymentMutation = { __typename?: 'Mutation', createIncomingPayment: { __typename?: 'IncomingPaymentResponse', payment?: { __typename?: 'IncomingPayment', createdAt: string, metadata?: any | null, expiresAt: string, id: string, walletAddressId: string, state: IncomingPaymentState, incomingAmount?: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint } | null, receivedAmount: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint } } | null } }; + input: CreateIncomingPaymentInput +}> + +export type CreateIncomingPaymentMutation = { + __typename?: 'Mutation' + createIncomingPayment: { + __typename?: 'IncomingPaymentResponse' + payment?: { + __typename?: 'IncomingPayment' + createdAt: string + metadata?: any | null + expiresAt: string + id: string + walletAddressId: string + state: IncomingPaymentState + incomingAmount?: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } | null + receivedAmount: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } + } | null + } +} export type WithdrawLiquidityMutationVariables = Exact<{ - eventId: Scalars['String']['input']; - idempotencyKey: Scalars['String']['input']; -}>; - - -export type WithdrawLiquidityMutation = { __typename?: 'Mutation', withdrawEventLiquidity?: { __typename?: 'LiquidityMutationResponse', success: boolean } | null }; + eventId: Scalars['String']['input'] + idempotencyKey: Scalars['String']['input'] +}> + +export type WithdrawLiquidityMutation = { + __typename?: 'Mutation' + withdrawEventLiquidity?: { + __typename?: 'LiquidityMutationResponse' + success: boolean + } | null +} export type DepositLiquidityMutationVariables = Exact<{ - eventId: Scalars['String']['input']; - idempotencyKey: Scalars['String']['input']; -}>; - - -export type DepositLiquidityMutation = { __typename?: 'Mutation', depositEventLiquidity?: { __typename?: 'LiquidityMutationResponse', success: boolean } | null }; + eventId: Scalars['String']['input'] + idempotencyKey: Scalars['String']['input'] +}> + +export type DepositLiquidityMutation = { + __typename?: 'Mutation' + depositEventLiquidity?: { + __typename?: 'LiquidityMutationResponse' + success: boolean + } | null +} export type CreateOutgoingPaymentMutationVariables = Exact<{ - input: CreateOutgoingPaymentInput; -}>; - - -export type CreateOutgoingPaymentMutation = { __typename?: 'Mutation', createOutgoingPayment: { __typename?: 'OutgoingPaymentResponse', payment?: { __typename?: 'OutgoingPayment', createdAt: string, metadata?: any | null, error?: string | null, id: string, walletAddressId: string, receiver: string, state: OutgoingPaymentState, stateAttempts: number, quote?: { __typename?: 'Quote', createdAt: string, expiresAt: string, highEstimatedExchangeRate: number, id: string, lowEstimatedExchangeRate: number, maxPacketAmount: bigint, minExchangeRate: number, walletAddressId: string, receiver: string, receiveAmount: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint }, debitAmount: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint } } | null, receiveAmount: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint }, debitAmount: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint }, sentAmount: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint } } | null } }; + input: CreateOutgoingPaymentInput +}> + +export type CreateOutgoingPaymentMutation = { + __typename?: 'Mutation' + createOutgoingPayment: { + __typename?: 'OutgoingPaymentResponse' + payment?: { + __typename?: 'OutgoingPayment' + createdAt: string + metadata?: any | null + error?: string | null + id: string + walletAddressId: string + receiver: string + state: OutgoingPaymentState + stateAttempts: number + quote?: { + __typename?: 'Quote' + createdAt: string + expiresAt: string + highEstimatedExchangeRate: number + id: string + lowEstimatedExchangeRate: number + maxPacketAmount: bigint + minExchangeRate: number + walletAddressId: string + receiver: string + receiveAmount: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } + debitAmount: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } + } | null + receiveAmount: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } + debitAmount: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } + sentAmount: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } + } | null + } +} export type CreateQuoteMutationVariables = Exact<{ - input: CreateQuoteInput; -}>; - - -export type CreateQuoteMutation = { __typename?: 'Mutation', createQuote: { __typename?: 'QuoteResponse', quote?: { __typename?: 'Quote', createdAt: string, expiresAt: string, highEstimatedExchangeRate: number, id: string, lowEstimatedExchangeRate: number, maxPacketAmount: bigint, minExchangeRate: number, walletAddressId: string, receiver: string, receiveAmount: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint }, debitAmount: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint } } | null } }; + input: CreateQuoteInput +}> + +export type CreateQuoteMutation = { + __typename?: 'Mutation' + createQuote: { + __typename?: 'QuoteResponse' + quote?: { + __typename?: 'Quote' + createdAt: string + expiresAt: string + highEstimatedExchangeRate: number + id: string + lowEstimatedExchangeRate: number + maxPacketAmount: bigint + minExchangeRate: number + walletAddressId: string + receiver: string + receiveAmount: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } + debitAmount: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } + } | null + } +} export type GetQuoteQueryVariables = Exact<{ - quoteId: Scalars['String']['input']; -}>; - - -export type GetQuoteQuery = { __typename?: 'Query', quote?: { __typename?: 'Quote', id: string, walletAddressId: string, receiver: string, maxPacketAmount: bigint, minExchangeRate: number, lowEstimatedExchangeRate: number, highEstimatedExchangeRate: number, createdAt: string, expiresAt: string, debitAmount: { __typename?: 'Amount', value: bigint, assetCode: string, assetScale: number }, receiveAmount: { __typename?: 'Amount', value: bigint, assetCode: string, assetScale: number } } | null }; + quoteId: Scalars['String']['input'] +}> + +export type GetQuoteQuery = { + __typename?: 'Query' + quote?: { + __typename?: 'Quote' + id: string + walletAddressId: string + receiver: string + maxPacketAmount: bigint + minExchangeRate: number + lowEstimatedExchangeRate: number + highEstimatedExchangeRate: number + createdAt: string + expiresAt: string + debitAmount: { + __typename?: 'Amount' + value: bigint + assetCode: string + assetScale: number + } + receiveAmount: { + __typename?: 'Amount' + value: bigint + assetCode: string + assetScale: number + } + } | null +} export type CreateReceiverMutationVariables = Exact<{ - input: CreateReceiverInput; -}>; - - -export type CreateReceiverMutation = { __typename?: 'Mutation', createReceiver: { __typename?: 'CreateReceiverResponse', receiver?: { __typename?: 'Receiver', createdAt: string, metadata?: any | null, expiresAt?: string | null, id: string, walletAddressUrl: string, incomingAmount?: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint } | null, receivedAmount: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint } } | null } }; + input: CreateReceiverInput +}> + +export type CreateReceiverMutation = { + __typename?: 'Mutation' + createReceiver: { + __typename?: 'CreateReceiverResponse' + receiver?: { + __typename?: 'Receiver' + createdAt: string + metadata?: any | null + expiresAt?: string | null + id: string + walletAddressUrl: string + incomingAmount?: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } | null + receivedAmount: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } + } | null + } +} export type GetReceiverQueryVariables = Exact<{ - id: Scalars['String']['input']; -}>; - - -export type GetReceiverQuery = { __typename?: 'Query', receiver?: { __typename?: 'Receiver', completed: boolean, createdAt: string, expiresAt?: string | null, metadata?: any | null, id: string, walletAddressUrl: string, updatedAt: string, incomingAmount?: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint } | null, receivedAmount: { __typename?: 'Amount', assetCode: string, assetScale: number, value: bigint } } | null }; + id: Scalars['String']['input'] +}> + +export type GetReceiverQuery = { + __typename?: 'Query' + receiver?: { + __typename?: 'Receiver' + completed: boolean + createdAt: string + expiresAt?: string | null + metadata?: any | null + id: string + walletAddressUrl: string + updatedAt: string + incomingAmount?: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } | null + receivedAmount: { + __typename?: 'Amount' + assetCode: string + assetScale: number + value: bigint + } + } | null +} export type CreateWalletAddressKeyMutationVariables = Exact<{ - input: CreateWalletAddressKeyInput; -}>; - - -export type CreateWalletAddressKeyMutation = { __typename?: 'Mutation', createWalletAddressKey?: { __typename?: 'CreateWalletAddressKeyMutationResponse', walletAddressKey?: { __typename?: 'WalletAddressKey', id: string, walletAddressId: string, revoked: boolean, createdAt: string, jwk: { __typename?: 'Jwk', alg: Alg, crv: Crv, kid: string, kty: Kty, x: string } } | null } | null }; + input: CreateWalletAddressKeyInput +}> + +export type CreateWalletAddressKeyMutation = { + __typename?: 'Mutation' + createWalletAddressKey?: { + __typename?: 'CreateWalletAddressKeyMutationResponse' + walletAddressKey?: { + __typename?: 'WalletAddressKey' + id: string + walletAddressId: string + revoked: boolean + createdAt: string + jwk: { + __typename?: 'Jwk' + alg: Alg + crv: Crv + kid: string + kty: Kty + x: string + } + } | null + } | null +} export type RevokeWalletAddressKeyMutationVariables = Exact<{ - input: RevokeWalletAddressKeyInput; -}>; - - -export type RevokeWalletAddressKeyMutation = { __typename?: 'Mutation', revokeWalletAddressKey?: { __typename?: 'RevokeWalletAddressKeyMutationResponse', walletAddressKey?: { __typename?: 'WalletAddressKey', id: string, revoked: boolean, walletAddressId: string, createdAt: string } | null } | null }; + input: RevokeWalletAddressKeyInput +}> + +export type RevokeWalletAddressKeyMutation = { + __typename?: 'Mutation' + revokeWalletAddressKey?: { + __typename?: 'RevokeWalletAddressKeyMutationResponse' + walletAddressKey?: { + __typename?: 'WalletAddressKey' + id: string + revoked: boolean + walletAddressId: string + createdAt: string + } | null + } | null +} export type CreateWalletAddressMutationVariables = Exact<{ - input: CreateWalletAddressInput; -}>; - - -export type CreateWalletAddressMutation = { __typename?: 'Mutation', createWalletAddress: { __typename?: 'CreateWalletAddressMutationResponse', walletAddress?: { __typename?: 'WalletAddress', id: string, url: string, publicName?: string | null } | null } }; + input: CreateWalletAddressInput +}> + +export type CreateWalletAddressMutation = { + __typename?: 'Mutation' + createWalletAddress: { + __typename?: 'CreateWalletAddressMutationResponse' + walletAddress?: { + __typename?: 'WalletAddress' + id: string + url: string + publicName?: string | null + } | null + } +} export type UpdateWalletAddressMutationVariables = Exact<{ - input: UpdateWalletAddressInput; -}>; - - -export type UpdateWalletAddressMutation = { __typename?: 'Mutation', updateWalletAddress: { __typename?: 'UpdateWalletAddressMutationResponse', walletAddress?: { __typename?: 'WalletAddress', id: string, url: string, publicName?: string | null } | null } }; + input: UpdateWalletAddressInput +}> + +export type UpdateWalletAddressMutation = { + __typename?: 'Mutation' + updateWalletAddress: { + __typename?: 'UpdateWalletAddressMutationResponse' + walletAddress?: { + __typename?: 'WalletAddress' + id: string + url: string + publicName?: string | null + } | null + } +} From 70fb990faed1acae45c073f98a4dd7eb850c93f8 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 1 Aug 2024 20:27:05 +0300 Subject: [PATCH 24/58] Prettier --- .../20240801155211_update_wallet_addresses.js | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js b/packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js index e9eec76fe..501a5f765 100644 --- a/packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js +++ b/packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js @@ -3,14 +3,13 @@ * @returns { Promise } */ exports.up = async function (knex) { - await knex('walletAddresses').update({ assetScale: 9 }); - }; - + await knex('walletAddresses').update({ assetScale: 9 }) +} + /** * @param { import("knex").Knex } knex * @returns { Promise } */ exports.down = async function (knex) { -await knex('walletAddresses').update({ assetScale: 2 }); -}; - \ No newline at end of file + await knex('walletAddresses').update({ assetScale: 2 }) +} From e5f6cc8ffdea7793b7cad86eb648a9de5cead4e6 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Fri, 2 Aug 2024 11:56:27 +0300 Subject: [PATCH 25/58] Fix display of fee --- packages/wallet/frontend/src/utils/helpers.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index 10b82c078..c6d31d990 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -75,20 +75,32 @@ export const formatDate = ({ } export const getFee = (quote: QuoteResponse): FormattedAmount => { + const maxAssetScale = 9 + if (quote.fee) { + const feeValue = ( + Number(quote.fee.value) * + Math.pow(10, maxAssetScale - quote.fee.assetScale) + ).toString() + return formatAmount({ assetCode: quote.fee.assetCode, assetScale: quote.fee.assetScale, - value: quote.fee.value.toString() + value: feeValue }) } const fee = BigInt(quote.debitAmount.value) - BigInt(quote.receiveAmount.value) + + const feeValue = ( + Number(fee) * Math.pow(10, maxAssetScale - quote.debitAmount.assetScale) + ).toString() + return formatAmount({ assetCode: quote.debitAmount.assetCode, assetScale: quote.debitAmount.assetScale, - value: fee.toString() + value: feeValue }) } From 7c5eee5311eaa7e19f0701a4bfcab8701df477ac Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 7 Aug 2024 19:17:23 +0300 Subject: [PATCH 26/58] Update migrations + partial asset display fix --- packages/wallet/backend/knexfile.js | 13 +++++++ .../20240801155211_update_asset_scale.js | 36 +++++++++++++++++++ .../20240801155211_update_wallet_addresses.js | 15 -------- .../src/components/cards/AccountCard.tsx | 7 ++-- .../src/components/dialogs/QuoteDialog.tsx | 16 ++------- .../src/pages/account/[accountId].tsx | 11 +++--- .../wallet/frontend/src/pages/exchange.tsx | 11 +++++- .../frontend/src/pages/transfer/request.tsx | 9 ++--- .../frontend/src/pages/transfer/send.tsx | 10 ++---- packages/wallet/frontend/src/utils/helpers.ts | 26 +++++--------- 10 files changed, 83 insertions(+), 71 deletions(-) create mode 100644 packages/wallet/backend/migrations/20240801155211_update_asset_scale.js delete mode 100644 packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js diff --git a/packages/wallet/backend/knexfile.js b/packages/wallet/backend/knexfile.js index 8f481de7b..9d570044f 100644 --- a/packages/wallet/backend/knexfile.js +++ b/packages/wallet/backend/knexfile.js @@ -20,6 +20,19 @@ module.exports = { } }, + rafiki_backend: { + client: 'postgresql', + connection: { + user: 'postgres', + password: 'password', + database: 'rafiki_backend' + }, + pool: { + min: 2, + max: 10 + } + }, + testing: { client: 'postgresql', connection: { diff --git a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js new file mode 100644 index 000000000..5f4453b39 --- /dev/null +++ b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js @@ -0,0 +1,36 @@ +const Knex = require('knex'); +const knexConfig = require('../knexfile'); + +/** + * @param { import("knex").Knex } knex + * @returns { Promise } + */ +exports.up = async function (knex) { + // Create a new Knex instance for the rafiki_backend database + const rafikiKnex = Knex(knexConfig.rafiki_backend); + + try { + await rafikiKnex('assets').update({ scale: 9 }); + await knex('accounts').update({ assetScale: 9 }); + await knex('walletAddresses').update({ assetScale: 9 }); + } finally { + await rafikiKnex.destroy(); + } +}; + +/** + * @param { import("knex").Knex } knex + * @returns { Promise } + */ +exports.down = async function (knex) { + // Create a new Knex instance for the rafiki_backend database + const rafikiKnex = Knex(knexConfig.rafiki_backend); + + try { + await rafikiKnex('assets').update({ scale: 2 }); + await knex('accounts').update({ assetScale: 2 }); + await knex('walletAddresses').update({ assetScale: 2 }); + } finally { + await rafikiKnex.destroy(); + } +}; diff --git a/packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js b/packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js deleted file mode 100644 index 501a5f765..000000000 --- a/packages/wallet/backend/migrations/20240801155211_update_wallet_addresses.js +++ /dev/null @@ -1,15 +0,0 @@ -/** - * @param { import("knex").Knex } knex - * @returns { Promise } - */ -exports.up = async function (knex) { - await knex('walletAddresses').update({ assetScale: 9 }) -} - -/** - * @param { import("knex").Knex } knex - * @returns { Promise } - */ -exports.down = async function (knex) { - await knex('walletAddresses').update({ assetScale: 2 }) -} diff --git a/packages/wallet/frontend/src/components/cards/AccountCard.tsx b/packages/wallet/frontend/src/components/cards/AccountCard.tsx index b1ba13659..562cdd877 100644 --- a/packages/wallet/frontend/src/components/cards/AccountCard.tsx +++ b/packages/wallet/frontend/src/components/cards/AccountCard.tsx @@ -19,20 +19,19 @@ export const AccountCard = ({ account, idOnboarding }: AccountCardProps) => { const snapshotAccount = accountsSnapshot.find( (item) => item.assetCode === account.assetCode ) - const baseAssetScale = 2 - const maxAssetScale = 9 const snapshotBalance = snapshotAccount ? Number(snapshotAccount.balance) : 0 const accountBalance = - Number(account.balance) * Math.pow(10, maxAssetScale - account.assetScale) + Number(account.balance) const value = (snapshotBalance || accountBalance).toString() return formatAmount({ value, + displayScale: 2, assetCode: account.assetCode, - assetScale: baseAssetScale + assetScale: account.assetScale }) }, [account, accountsSnapshot]) diff --git a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx index e70726f35..4a17299db 100644 --- a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx +++ b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx @@ -24,26 +24,14 @@ export const QuoteDialog = ({ const { setRunOnboarding, stepIndex, setStepIndex, isUserFirstTime } = useOnboardingContext() - const maxAssetScale = 9 - - const receiveValue = ( - Number(quote.receiveAmount.value) * - Math.pow(10, maxAssetScale - quote.receiveAmount.assetScale) - ).toString() - - const debitValue = ( - Number(quote.debitAmount.value) * - Math.pow(10, maxAssetScale - quote.debitAmount.assetScale) - ).toString() - const receiveAmount = formatAmount({ - value: receiveValue, + value: quote.receiveAmount.value, assetCode: quote.receiveAmount.assetCode, assetScale: quote.receiveAmount.assetScale }) const debitAmount = formatAmount({ - value: debitValue, + value: quote.debitAmount.value, assetCode: quote.debitAmount.assetCode, assetScale: quote.debitAmount.assetScale }) diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index 65e15f40b..2081466a3 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -40,27 +40,26 @@ const AccountPage: NextPageWithLayout = ({ (item) => item.assetCode === account.assetCode ) - const baseAssetScale = 2 - const maxAssetScale = 9 - const snapshotBalance = snapshotAccount ? Number(snapshotAccount.balance) : 0 + const accountBalance = - Number(account.balance) * Math.pow(10, maxAssetScale - account.assetScale) + Number(account.balance) // `balance` represents incoming amount - outgoing amount in asset scale 9 const value = ((snapshotBalance || accountBalance) + balance).toString() const amountScale2 = formatAmount({ value, + displayScale: 2, assetCode: account.assetCode, - assetScale: baseAssetScale + assetScale: account.assetScale }) const amountScale9 = formatAmount({ value, assetCode: account.assetCode, - assetScale: maxAssetScale + assetScale: account.assetScale }) return { diff --git a/packages/wallet/frontend/src/pages/exchange.tsx b/packages/wallet/frontend/src/pages/exchange.tsx index 6313f61f0..d6ed04152 100644 --- a/packages/wallet/frontend/src/pages/exchange.tsx +++ b/packages/wallet/frontend/src/pages/exchange.tsx @@ -49,8 +49,17 @@ const ExchangeAssetPage: NextPageWithLayout = ({ const snapshotAccount = accountsSnapshot.find( (item) => item.assetCode === account.assetCode ) + + const snapshotBalance = snapshotAccount + ? Number(snapshotAccount.balance) + : 0 + const accountBalance = + Number(account.balance) + + const value = (snapshotBalance || accountBalance).toString() + return formatAmount({ - value: snapshotAccount?.balance || account.balance, + value, assetCode: account.assetCode, assetScale: account.assetScale }) diff --git a/packages/wallet/frontend/src/pages/transfer/request.tsx b/packages/wallet/frontend/src/pages/transfer/request.tsx index 7c1a2c1f0..548b62b87 100644 --- a/packages/wallet/frontend/src/pages/transfer/request.tsx +++ b/packages/wallet/frontend/src/pages/transfer/request.tsx @@ -68,22 +68,19 @@ const RequestPage: NextPageWithLayout = ({ accounts }) => { item.assetScale === selectedAccount.assetScale ) - const baseAssetScale = 2 - const maxAssetScale = 9 - const snapshotBalance = snapshotAccount ? Number(snapshotAccount.balance) : 0 const accountBalance = - Number(selectedAccount.balance) * - Math.pow(10, maxAssetScale - selectedAccount.assetScale) + Number(selectedAccount.balance) const value = (snapshotBalance || accountBalance).toString() return formatAmount({ value, + displayScale: 2, assetCode: selectedAccount.assetCode, - assetScale: baseAssetScale + assetScale: selectedAccount.assetScale }).amount }, [accountsSnapshot, selectedAccount]) diff --git a/packages/wallet/frontend/src/pages/transfer/send.tsx b/packages/wallet/frontend/src/pages/transfer/send.tsx index 7cb4a8a15..e25b0528f 100644 --- a/packages/wallet/frontend/src/pages/transfer/send.tsx +++ b/packages/wallet/frontend/src/pages/transfer/send.tsx @@ -67,22 +67,18 @@ const SendPage: NextPageWithLayout = ({ accounts }) => { item.assetScale === selectedAccount.assetScale ) - const baseAssetScale = 2 - const maxAssetScale = 9 - const snapshotBalance = snapshotAccount ? Number(snapshotAccount.balance) : 0 const accountBalance = - Number(selectedAccount.balance) * - Math.pow(10, maxAssetScale - selectedAccount.assetScale) - + Number(selectedAccount.balance) const value = (snapshotBalance || accountBalance).toString() return formatAmount({ value, + displayScale: 2, assetCode: selectedAccount.assetCode, - assetScale: baseAssetScale + assetScale: selectedAccount.assetScale }).amount }, [accountsSnapshot, selectedAccount]) diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index c6d31d990..c8db825a8 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -35,19 +35,19 @@ export const getCurrencySymbol = (assetCode: string): string => { type FormatAmountArgs = AssetOP & { value: string + displayScale?: number } export const formatAmount = (args: FormatAmountArgs): FormattedAmount => { - const { value, assetCode, assetScale } = args + const { value, displayScale = 9, assetCode, assetScale } = args const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: assetCode, - maximumFractionDigits: assetScale, - minimumFractionDigits: assetScale + maximumFractionDigits: displayScale, + minimumFractionDigits: displayScale }) - // All assets will have asset scale 9 by default so we treat the amounts as such when formatting - const maxAssetScale = 9 - const amount = formatter.format(Number(`${value}e-${maxAssetScale}`)) + + const amount = formatter.format(Number(`${value}e-${assetScale}`)) const symbol = getCurrencySymbol(assetCode) return { @@ -75,32 +75,22 @@ export const formatDate = ({ } export const getFee = (quote: QuoteResponse): FormattedAmount => { - const maxAssetScale = 9 if (quote.fee) { - const feeValue = ( - Number(quote.fee.value) * - Math.pow(10, maxAssetScale - quote.fee.assetScale) - ).toString() - return formatAmount({ assetCode: quote.fee.assetCode, assetScale: quote.fee.assetScale, - value: feeValue + value: quote.fee.value }) } const fee = BigInt(quote.debitAmount.value) - BigInt(quote.receiveAmount.value) - const feeValue = ( - Number(fee) * Math.pow(10, maxAssetScale - quote.debitAmount.assetScale) - ).toString() - return formatAmount({ assetCode: quote.debitAmount.assetCode, assetScale: quote.debitAmount.assetScale, - value: feeValue + value: fee.toString() }) } From 7cd87d4fcbf0009882dab07e38cf979508187abc Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 7 Aug 2024 19:21:38 +0300 Subject: [PATCH 27/58] Prettier --- .../20240801155211_update_asset_scale.js | 28 +++++++++---------- .../src/components/cards/AccountCard.tsx | 3 +- .../src/pages/account/[accountId].tsx | 3 +- .../wallet/frontend/src/pages/exchange.tsx | 3 +- .../src/pages/grant-interactions/index.tsx | 2 +- .../frontend/src/pages/transfer/request.tsx | 3 +- .../frontend/src/pages/transfer/send.tsx | 3 +- packages/wallet/frontend/src/utils/helpers.ts | 1 - 8 files changed, 20 insertions(+), 26 deletions(-) diff --git a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js index 5f4453b39..67950aa57 100644 --- a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js +++ b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js @@ -1,5 +1,5 @@ -const Knex = require('knex'); -const knexConfig = require('../knexfile'); +const Knex = require('knex') +const knexConfig = require('../knexfile') /** * @param { import("knex").Knex } knex @@ -7,16 +7,16 @@ const knexConfig = require('../knexfile'); */ exports.up = async function (knex) { // Create a new Knex instance for the rafiki_backend database - const rafikiKnex = Knex(knexConfig.rafiki_backend); + const rafikiKnex = Knex(knexConfig.rafiki_backend) try { - await rafikiKnex('assets').update({ scale: 9 }); - await knex('accounts').update({ assetScale: 9 }); - await knex('walletAddresses').update({ assetScale: 9 }); + await rafikiKnex('assets').update({ scale: 9 }) + await knex('accounts').update({ assetScale: 9 }) + await knex('walletAddresses').update({ assetScale: 9 }) } finally { - await rafikiKnex.destroy(); + await rafikiKnex.destroy() } -}; +} /** * @param { import("knex").Knex } knex @@ -24,13 +24,13 @@ exports.up = async function (knex) { */ exports.down = async function (knex) { // Create a new Knex instance for the rafiki_backend database - const rafikiKnex = Knex(knexConfig.rafiki_backend); + const rafikiKnex = Knex(knexConfig.rafiki_backend) try { - await rafikiKnex('assets').update({ scale: 2 }); - await knex('accounts').update({ assetScale: 2 }); - await knex('walletAddresses').update({ assetScale: 2 }); + await rafikiKnex('assets').update({ scale: 2 }) + await knex('accounts').update({ assetScale: 2 }) + await knex('walletAddresses').update({ assetScale: 2 }) } finally { - await rafikiKnex.destroy(); + await rafikiKnex.destroy() } -}; +} diff --git a/packages/wallet/frontend/src/components/cards/AccountCard.tsx b/packages/wallet/frontend/src/components/cards/AccountCard.tsx index 562cdd877..d70f5bbbc 100644 --- a/packages/wallet/frontend/src/components/cards/AccountCard.tsx +++ b/packages/wallet/frontend/src/components/cards/AccountCard.tsx @@ -23,8 +23,7 @@ export const AccountCard = ({ account, idOnboarding }: AccountCardProps) => { const snapshotBalance = snapshotAccount ? Number(snapshotAccount.balance) : 0 - const accountBalance = - Number(account.balance) + const accountBalance = Number(account.balance) const value = (snapshotBalance || accountBalance).toString() return formatAmount({ diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index 2081466a3..d55c5ec5a 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -44,8 +44,7 @@ const AccountPage: NextPageWithLayout = ({ ? Number(snapshotAccount.balance) : 0 - const accountBalance = - Number(account.balance) + const accountBalance = Number(account.balance) // `balance` represents incoming amount - outgoing amount in asset scale 9 const value = ((snapshotBalance || accountBalance) + balance).toString() diff --git a/packages/wallet/frontend/src/pages/exchange.tsx b/packages/wallet/frontend/src/pages/exchange.tsx index d6ed04152..5dba27767 100644 --- a/packages/wallet/frontend/src/pages/exchange.tsx +++ b/packages/wallet/frontend/src/pages/exchange.tsx @@ -53,8 +53,7 @@ const ExchangeAssetPage: NextPageWithLayout = ({ const snapshotBalance = snapshotAccount ? Number(snapshotAccount.balance) : 0 - const accountBalance = - Number(account.balance) + const accountBalance = Number(account.balance) const value = (snapshotBalance || accountBalance).toString() diff --git a/packages/wallet/frontend/src/pages/grant-interactions/index.tsx b/packages/wallet/frontend/src/pages/grant-interactions/index.tsx index 3087a2874..c66015ee7 100644 --- a/packages/wallet/frontend/src/pages/grant-interactions/index.tsx +++ b/packages/wallet/frontend/src/pages/grant-interactions/index.tsx @@ -175,7 +175,7 @@ export const getServerSideProps: GetServerSideProps<{ if (access.limits) { access.limits.receiver = access.limits.receiver ? replaceWalletAddressProtocol(access.limits.receiver) - : (access.limits.receiver ?? null) + : access.limits.receiver ?? null if (access.limits.debitAmount) { access.limits.debitAmount.formattedAmount = formatAmount({ diff --git a/packages/wallet/frontend/src/pages/transfer/request.tsx b/packages/wallet/frontend/src/pages/transfer/request.tsx index 548b62b87..8f24aa390 100644 --- a/packages/wallet/frontend/src/pages/transfer/request.tsx +++ b/packages/wallet/frontend/src/pages/transfer/request.tsx @@ -71,8 +71,7 @@ const RequestPage: NextPageWithLayout = ({ accounts }) => { const snapshotBalance = snapshotAccount ? Number(snapshotAccount.balance) : 0 - const accountBalance = - Number(selectedAccount.balance) + const accountBalance = Number(selectedAccount.balance) const value = (snapshotBalance || accountBalance).toString() diff --git a/packages/wallet/frontend/src/pages/transfer/send.tsx b/packages/wallet/frontend/src/pages/transfer/send.tsx index e25b0528f..f45022987 100644 --- a/packages/wallet/frontend/src/pages/transfer/send.tsx +++ b/packages/wallet/frontend/src/pages/transfer/send.tsx @@ -70,8 +70,7 @@ const SendPage: NextPageWithLayout = ({ accounts }) => { const snapshotBalance = snapshotAccount ? Number(snapshotAccount.balance) : 0 - const accountBalance = - Number(selectedAccount.balance) + const accountBalance = Number(selectedAccount.balance) const value = (snapshotBalance || accountBalance).toString() return formatAmount({ diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index c8db825a8..3e98b48de 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -75,7 +75,6 @@ export const formatDate = ({ } export const getFee = (quote: QuoteResponse): FormattedAmount => { - if (quote.fee) { return formatAmount({ assetCode: quote.fee.assetCode, From 3733fa630fb33faabff7b2c752c1de7c8fd9b6db Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 7 Aug 2024 19:30:41 +0300 Subject: [PATCH 28/58] Fix formatting? --- packages/wallet/frontend/src/pages/grant-interactions/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/wallet/frontend/src/pages/grant-interactions/index.tsx b/packages/wallet/frontend/src/pages/grant-interactions/index.tsx index c66015ee7..3087a2874 100644 --- a/packages/wallet/frontend/src/pages/grant-interactions/index.tsx +++ b/packages/wallet/frontend/src/pages/grant-interactions/index.tsx @@ -175,7 +175,7 @@ export const getServerSideProps: GetServerSideProps<{ if (access.limits) { access.limits.receiver = access.limits.receiver ? replaceWalletAddressProtocol(access.limits.receiver) - : access.limits.receiver ?? null + : (access.limits.receiver ?? null) if (access.limits.debitAmount) { access.limits.debitAmount.formattedAmount = formatAmount({ From ff4b64e39686bf05466c62114104ded9c7b0614e Mon Sep 17 00:00:00 2001 From: bsanduc Date: Fri, 9 Aug 2024 12:35:43 +0300 Subject: [PATCH 29/58] Try fix migration --- .../20240801155211_update_asset_scale.js | 49 ++++++++++++++----- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js index 67950aa57..5729644bb 100644 --- a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js +++ b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js @@ -6,16 +6,27 @@ const knexConfig = require('../knexfile') * @returns { Promise } */ exports.up = async function (knex) { - // Create a new Knex instance for the rafiki_backend database - const rafikiKnex = Knex(knexConfig.rafiki_backend) + if (process.env.NODE_ENV !== 'test') { + const rafikiKnex = Knex(knexConfig.rafiki_backend); + + try { + await rafikiKnex('assets').update({ scale: 9 }); + } finally { + await rafikiKnex.destroy(); + } + } + + const rafikiKnex = Knex(knexConfig.rafiki_backend); try { - await rafikiKnex('assets').update({ scale: 9 }) - await knex('accounts').update({ assetScale: 9 }) - await knex('walletAddresses').update({ assetScale: 9 }) + await rafikiKnex('assets').update({ scale: 9 }); + await knex('accounts').update({ assetScale: 9 }); + await knex('walletAddresses').update({ assetScale: 9 }); + } finally { - await rafikiKnex.destroy() + await rafikiKnex.destroy(); } + } /** @@ -23,14 +34,26 @@ exports.up = async function (knex) { * @returns { Promise } */ exports.down = async function (knex) { - // Create a new Knex instance for the rafiki_backend database - const rafikiKnex = Knex(knexConfig.rafiki_backend) + if (process.env.NODE_ENV !== 'test') { + const rafikiKnex = Knex(knexConfig.rafiki_backend); + + try { + await rafikiKnex('assets').update({ scale: 2 }); + } finally { + await rafikiKnex.destroy(); + } + } + + const rafikiKnex = Knex(knexConfig.rafiki_backend); try { - await rafikiKnex('assets').update({ scale: 2 }) - await knex('accounts').update({ assetScale: 2 }) - await knex('walletAddresses').update({ assetScale: 2 }) + await rafikiKnex('assets').update({ scale: 2 }); + await knex('accounts').update({ assetScale: 2 }); + await knex('walletAddresses').update({ assetScale: 2 }); + } finally { - await rafikiKnex.destroy() + await rafikiKnex.destroy(); } -} + + +}; From 2bad249a21d308f534a493b5dbed5908870bbb16 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Fri, 9 Aug 2024 12:37:11 +0300 Subject: [PATCH 30/58] Try fix migration - amend --- .../20240801155211_update_asset_scale.js | 25 +++---------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js index 5729644bb..1413bc3d5 100644 --- a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js +++ b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js @@ -16,16 +16,8 @@ exports.up = async function (knex) { } } - const rafikiKnex = Knex(knexConfig.rafiki_backend); - - try { - await rafikiKnex('assets').update({ scale: 9 }); - await knex('accounts').update({ assetScale: 9 }); - await knex('walletAddresses').update({ assetScale: 9 }); - - } finally { - await rafikiKnex.destroy(); - } + await knex('accounts').update({ assetScale: 9 }); + await knex('walletAddresses').update({ assetScale: 9 }); } @@ -43,17 +35,8 @@ exports.down = async function (knex) { await rafikiKnex.destroy(); } } - - const rafikiKnex = Knex(knexConfig.rafiki_backend); - - try { - await rafikiKnex('assets').update({ scale: 2 }); - await knex('accounts').update({ assetScale: 2 }); - await knex('walletAddresses').update({ assetScale: 2 }); - - } finally { - await rafikiKnex.destroy(); - } + await knex('accounts').update({ assetScale: 2 }); + await knex('walletAddresses').update({ assetScale: 2 }); }; From 6e6b7f4d68e12985cd0ad7a536d5fda1bd38ef48 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Fri, 9 Aug 2024 12:38:55 +0300 Subject: [PATCH 31/58] Prettier --- .../20240801155211_update_asset_scale.js | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js index 1413bc3d5..c26c8f23e 100644 --- a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js +++ b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js @@ -7,18 +7,17 @@ const knexConfig = require('../knexfile') */ exports.up = async function (knex) { if (process.env.NODE_ENV !== 'test') { - const rafikiKnex = Knex(knexConfig.rafiki_backend); + const rafikiKnex = Knex(knexConfig.rafiki_backend) try { - await rafikiKnex('assets').update({ scale: 9 }); + await rafikiKnex('assets').update({ scale: 9 }) } finally { - await rafikiKnex.destroy(); + await rafikiKnex.destroy() } } - await knex('accounts').update({ assetScale: 9 }); - await knex('walletAddresses').update({ assetScale: 9 }); - + await knex('accounts').update({ assetScale: 9 }) + await knex('walletAddresses').update({ assetScale: 9 }) } /** @@ -27,16 +26,14 @@ exports.up = async function (knex) { */ exports.down = async function (knex) { if (process.env.NODE_ENV !== 'test') { - const rafikiKnex = Knex(knexConfig.rafiki_backend); + const rafikiKnex = Knex(knexConfig.rafiki_backend) try { - await rafikiKnex('assets').update({ scale: 2 }); + await rafikiKnex('assets').update({ scale: 2 }) } finally { - await rafikiKnex.destroy(); + await rafikiKnex.destroy() } } - await knex('accounts').update({ assetScale: 2 }); - await knex('walletAddresses').update({ assetScale: 2 }); - - -}; + await knex('accounts').update({ assetScale: 2 }) + await knex('walletAddresses').update({ assetScale: 2 }) +} From 7e6c73bcfd25100d93bb838125fc7f7a7647aaec Mon Sep 17 00:00:00 2001 From: bsanduc Date: Fri, 9 Aug 2024 13:46:10 +0300 Subject: [PATCH 32/58] Update knex config --- packages/wallet/backend/knexfile.js | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/wallet/backend/knexfile.js b/packages/wallet/backend/knexfile.js index 9d570044f..41d70d884 100644 --- a/packages/wallet/backend/knexfile.js +++ b/packages/wallet/backend/knexfile.js @@ -23,6 +23,7 @@ module.exports = { rafiki_backend: { client: 'postgresql', connection: { + host: 'postgres', user: 'postgres', password: 'password', database: 'rafiki_backend' From 3d2189d568685a7ac49e319f247e90c83b42e439 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 13 Aug 2024 08:44:09 +0300 Subject: [PATCH 33/58] Update backend and migration --- .../20240801155211_update_asset_scale.js | 81 ++++++++++++++++++- .../wallet/backend/src/account/service.ts | 2 +- packages/wallet/backend/src/user/service.ts | 8 +- .../backend/src/walletAddress/service.ts | 2 +- 4 files changed, 85 insertions(+), 8 deletions(-) diff --git a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js index c26c8f23e..ea1e7d532 100644 --- a/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js +++ b/packages/wallet/backend/migrations/20240801155211_update_asset_scale.js @@ -10,14 +10,50 @@ exports.up = async function (knex) { const rafikiKnex = Knex(knexConfig.rafiki_backend) try { - await rafikiKnex('assets').update({ scale: 9 }) + const assets = await rafikiKnex('assets').distinct('code') + + for (const asset of assets) { + const { code } = asset + + const existingAssetWithScale9 = await rafikiKnex('assets') + .where({ code, scale: 9 }) + .first() + + if (existingAssetWithScale9) { + await knex('accounts') + .where({ assetCode: code, assetScale: 2 }) + .update({ + assetId: existingAssetWithScale9.id, + assetScale: 9 + }) + } else { + await rafikiKnex('assets') + .where({ code, scale: 2 }) + .update({ scale: 9 }) + } + } } finally { await rafikiKnex.destroy() } } - await knex('accounts').update({ assetScale: 9 }) + const walletAddresses = await knex('walletAddresses').select( + 'id', + 'accountId' + ) + for (const walletAddress of walletAddresses) { + const account = await knex('accounts') + .where('id', walletAddress.accountId) + .first() + if (account) { + await knex('walletAddresses') + .where('id', walletAddress.id) + .update({ assetCode: account.assetCode }) + } + } + await knex('walletAddresses').update({ assetScale: 9 }) + await knex('accounts').update({ assetScale: 9 }) } /** @@ -29,11 +65,48 @@ exports.down = async function (knex) { const rafikiKnex = Knex(knexConfig.rafiki_backend) try { - await rafikiKnex('assets').update({ scale: 2 }) + const assets = await rafikiKnex('assets').distinct('code') + + for (const asset of assets) { + const { code } = asset + + const existingAssetWithScale2 = await rafikiKnex('assets') + .where({ code, scale: 2 }) + .first() + + if (existingAssetWithScale2) { + await knex('accounts') + .where({ assetCode: code, assetScale: 9 }) + .update({ + assetId: existingAssetWithScale2.id, + assetScale: 2 + }) + } else { + await rafikiKnex('assets') + .where({ code, scale: 9 }) + .update({ scale: 2 }) + } + } } finally { await rafikiKnex.destroy() } } - await knex('accounts').update({ assetScale: 2 }) + + const walletAddresses = await knex('walletAddresses').select( + 'id', + 'accountId' + ) + for (const walletAddress of walletAddresses) { + const account = await knex('accounts') + .where('id', walletAddress.accountId) + .first() + if (account) { + await knex('walletAddresses') + .where('id', walletAddress.id) + .update({ assetCode: account.assetCode }) + } + } + await knex('walletAddresses').update({ assetScale: 2 }) + await knex('accounts').update({ assetScale: 2 }) } diff --git a/packages/wallet/backend/src/account/service.ts b/packages/wallet/backend/src/account/service.ts index e52897a48..c66800625 100644 --- a/packages/wallet/backend/src/account/service.ts +++ b/packages/wallet/backend/src/account/service.ts @@ -309,7 +309,7 @@ export class AccountService implements IAccountService { name = 'USD Account' ): Promise { const asset = (await this.rafikiClient.listAssets({ first: 100 })).find( - (asset) => asset.code === 'USD' && asset.scale === 2 + (asset) => asset.code === 'USD' && asset.scale === 9 ) if (!asset) { return diff --git a/packages/wallet/backend/src/user/service.ts b/packages/wallet/backend/src/user/service.ts index 49ad5f2c3..8406b4581 100644 --- a/packages/wallet/backend/src/user/service.ts +++ b/packages/wallet/backend/src/user/service.ts @@ -127,8 +127,12 @@ export class UserService implements IUserService { if (existingUser) return - const asset = await this.rafikiClient.getRafikiAsset('USD', 2) - if (!asset) await this.rafikiClient.createAsset('USD', 2) + const asset = await this.rafikiClient.getRafikiAsset( + 'USD', + this.env.MAX_ASSET_SCALE + ) + if (!asset) + await this.rafikiClient.createAsset('USD', this.env.MAX_ASSET_SCALE) const defaultWalletUser = this.env.DEFAULT_WALLET_ACCOUNT const defaultBoutiqueUser = this.env.DEFAULT_BOUTIQUE_ACCOUNT diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index ca6ab724a..ffbff9b00 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -126,7 +126,7 @@ export class WalletAddressService implements IWalletAddressService { publicName: args.publicName, accountId: args.accountId, id: rafikiWalletAddress.id, - assetCode: null, + assetCode: account.assetCode, assetScale: this.env.MAX_ASSET_SCALE }) } From 317d2a3fe3dd75669fe10b760d771002c6dfb050 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Mon, 19 Aug 2024 15:15:44 +0300 Subject: [PATCH 34/58] Update Rafiki service interaction with Rapyd --- packages/wallet/backend/src/config/env.ts | 2 +- packages/wallet/backend/src/rafiki/service.ts | 26 +++++++++---------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/packages/wallet/backend/src/config/env.ts b/packages/wallet/backend/src/config/env.ts index 4c25a4a69..766fc1504 100644 --- a/packages/wallet/backend/src/config/env.ts +++ b/packages/wallet/backend/src/config/env.ts @@ -34,7 +34,7 @@ const envSchema = z.object({ .transform((value) => value === 'true'), BASE_ASSET_SCALE: z.coerce.number().nonnegative().default(2), MAX_ASSET_SCALE: z.coerce.number().nonnegative().default(9), - RAPYD_THRESHOLD: z.coerce.bigint().nonnegative().default(10_000_000n), // $0.01 in asset scale 9 + RAPYD_THRESHOLD: z.coerce.bigint().nonnegative().default(100_000_000n), // $0.1 in asset scale 9 DEBT_THRESHOLD: z.coerce.number().multipleOf(0.01).nonnegative().default(5.0), // $5.00 DEFAULT_WALLET_ACCOUNT: z .object({ diff --git a/packages/wallet/backend/src/rafiki/service.ts b/packages/wallet/backend/src/rafiki/service.ts index ff31d1be2..ff7714213 100644 --- a/packages/wallet/backend/src/rafiki/service.ts +++ b/packages/wallet/backend/src/rafiki/service.ts @@ -164,9 +164,9 @@ export class RafikiService implements IRafikiService { return amount } - private amountToNumber(amount: Amount): number { + private amountToNumber(amount: Amount, assetScale: number = amount.assetScale): number { return +(Number(amount.value) * 10 ** -amount.assetScale).toFixed( - amount.assetScale + assetScale ) } @@ -187,9 +187,9 @@ export class RafikiService implements IRafikiService { } return } - + const transferResult = await this.rapydClient.transferLiquidity({ - amount: this.amountToNumber(amount), + amount: this.amountToNumber(amount, 2), currency: amount.assetCode, destination_ewallet: receiverWalletId, source_ewallet: this.env.RAPYD_SETTLEMENT_EWALLET @@ -222,7 +222,7 @@ export class RafikiService implements IRafikiService { this.logger.info( `Succesfully transfered ${this.amountToNumber( - amount + amount, 2 )} from settlement account ${ this.env.RAPYD_SETTLEMENT_EWALLET } into ${receiverWalletId} ` @@ -253,7 +253,7 @@ export class RafikiService implements IRafikiService { walletAddress ) const holdResult = await this.rapydClient.holdLiquidity({ - amount: this.amountToNumber(amount), + amount: this.amountToNumber(amount, 2), currency: amount.assetCode, ewallet: rapydWalletId }) @@ -269,7 +269,7 @@ export class RafikiService implements IRafikiService { this.logger.info( `Succesfully held ${this.amountToNumber( - amount + amount, 2 )} in ${rapydWalletId} on ${EventType.OutgoingPaymentCreated}` ) } @@ -285,13 +285,13 @@ export class RafikiService implements IRafikiService { } await this.rapydClient.releaseLiquidity({ - amount: this.amountToNumber(debitAmount), + amount: this.amountToNumber(debitAmount, 2), currency: debitAmount.assetCode, ewallet: source_ewallet }) await this.rapydClient.transferLiquidity({ - amount: this.amountToNumber(debitAmount), + amount: this.amountToNumber(debitAmount, 2), currency: debitAmount.assetCode, destination_ewallet: this.env.RAPYD_SETTLEMENT_EWALLET, source_ewallet @@ -322,7 +322,7 @@ export class RafikiService implements IRafikiService { this.logger.info( `Succesfully transfered ${this.amountToNumber( - debitAmount + debitAmount, 2 )} from ${source_ewallet} to settlement account on ${ EventType.OutgoingPaymentCompleted }` @@ -342,7 +342,7 @@ export class RafikiService implements IRafikiService { const source_ewallet = await this.getRapydWalletId(walletAddress) const releaseResult = await this.rapydClient.releaseLiquidity({ - amount: this.amountToNumber(debitAmount), + amount: this.amountToNumber(debitAmount, 2), currency: debitAmount.assetCode, ewallet: source_ewallet }) @@ -350,7 +350,7 @@ export class RafikiService implements IRafikiService { if (releaseResult.status?.status !== 'SUCCESS') { throw new Error( `Unable to release amount ${this.amountToNumber( - debitAmount + debitAmount, 2 )} from ${source_ewallet} on ${ EventType.OutgoingPaymentFailed } error message: ${releaseResult.status?.message || 'unknown'}` @@ -368,7 +368,7 @@ export class RafikiService implements IRafikiService { //* transfer eventual already sent money to the settlement account const transferResult = await this.rapydClient.transferLiquidity({ - amount: this.amountToNumber(sentAmount), + amount: this.amountToNumber(sentAmount, 2), currency: sentAmount.assetCode, destination_ewallet: this.env.RAPYD_SETTLEMENT_EWALLET, source_ewallet From e4501457ff114273ffd44d3ec505d6135e6b0075 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Mon, 19 Aug 2024 15:22:01 +0300 Subject: [PATCH 35/58] Prettier --- packages/wallet/backend/src/rafiki/service.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/packages/wallet/backend/src/rafiki/service.ts b/packages/wallet/backend/src/rafiki/service.ts index ff7714213..a2f83bcae 100644 --- a/packages/wallet/backend/src/rafiki/service.ts +++ b/packages/wallet/backend/src/rafiki/service.ts @@ -164,7 +164,10 @@ export class RafikiService implements IRafikiService { return amount } - private amountToNumber(amount: Amount, assetScale: number = amount.assetScale): number { + private amountToNumber( + amount: Amount, + assetScale: number = amount.assetScale + ): number { return +(Number(amount.value) * 10 ** -amount.assetScale).toFixed( assetScale ) @@ -187,7 +190,7 @@ export class RafikiService implements IRafikiService { } return } - + const transferResult = await this.rapydClient.transferLiquidity({ amount: this.amountToNumber(amount, 2), currency: amount.assetCode, @@ -222,7 +225,8 @@ export class RafikiService implements IRafikiService { this.logger.info( `Succesfully transfered ${this.amountToNumber( - amount, 2 + amount, + 2 )} from settlement account ${ this.env.RAPYD_SETTLEMENT_EWALLET } into ${receiverWalletId} ` @@ -269,7 +273,8 @@ export class RafikiService implements IRafikiService { this.logger.info( `Succesfully held ${this.amountToNumber( - amount, 2 + amount, + 2 )} in ${rapydWalletId} on ${EventType.OutgoingPaymentCreated}` ) } @@ -322,7 +327,8 @@ export class RafikiService implements IRafikiService { this.logger.info( `Succesfully transfered ${this.amountToNumber( - debitAmount, 2 + debitAmount, + 2 )} from ${source_ewallet} to settlement account on ${ EventType.OutgoingPaymentCompleted }` @@ -350,7 +356,8 @@ export class RafikiService implements IRafikiService { if (releaseResult.status?.status !== 'SUCCESS') { throw new Error( `Unable to release amount ${this.amountToNumber( - debitAmount, 2 + debitAmount, + 2 )} from ${source_ewallet} on ${ EventType.OutgoingPaymentFailed } error message: ${releaseResult.status?.message || 'unknown'}` From 7fdb4fe5f0daacbb19918ab0b56d2f80fab95d2a Mon Sep 17 00:00:00 2001 From: bsanduc Date: Mon, 19 Aug 2024 15:23:19 +0300 Subject: [PATCH 36/58] Increase Rapyd threshold --- docker/dev/docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/dev/docker-compose.yml b/docker/dev/docker-compose.yml index 7e338705f..a1904ff30 100644 --- a/docker/dev/docker-compose.yml +++ b/docker/dev/docker-compose.yml @@ -54,7 +54,7 @@ services: RATE_API_KEY: ${RATE_API_KEY} BASE_ASSET_SCALE: 2 MAX_ASSET_SCALE: 9 - RAPYD_THRESHOLD: 10000000 # 0.01 + RAPYD_THRESHOLD: 100000000 # 0.1 DEBT_THRESHOLD: 5 REDIS_URL: redis://redis:6379/0 restart: always From b78f24d77c2d668d79dfffc5b82bd25031082353 Mon Sep 17 00:00:00 2001 From: Tymmmy <117268143+Tymmmy@users.noreply.github.com> Date: Mon, 19 Aug 2024 15:49:29 +0300 Subject: [PATCH 37/58] remove asset scale imbalance transaction from list --- .../frontend/src/pages/transactions.tsx | 99 ++++++++++--------- .../wallet/frontend/src/utils/constants.ts | 5 +- 2 files changed, 56 insertions(+), 48 deletions(-) diff --git a/packages/wallet/frontend/src/pages/transactions.tsx b/packages/wallet/frontend/src/pages/transactions.tsx index d9758fbc7..d71cef38e 100644 --- a/packages/wallet/frontend/src/pages/transactions.tsx +++ b/packages/wallet/frontend/src/pages/transactions.tsx @@ -20,6 +20,7 @@ import { cx } from 'class-variance-authority' import { IconButton } from '@/ui/IconButton' import { Play } from '@/components/icons/Play' import { Label } from '@/ui/forms/Label' +import { ASSET_SCALE_IMBALANCE } from '@/utils/constants' type WalletAddressSelectOption = SelectOption & { accountId: string @@ -280,53 +281,57 @@ const TransactionsPage: NextPageWithLayout = ({ /> {transactions.results.length ? ( - transactions.results.map((trx) => ( - - {trx.accountName} - - {trx.walletAddressPublicName ?? - trx.walletAddressUrl ?? - ''} - {trx.walletAddressUrl ? ( - - {trx.walletAddressUrl} - - ) : null} - - - {trx.description ? ( - trx.description - ) : ( -

No description

- )} -
- - {trx.type === 'INCOMING' ? '+' : '-'} - { - formatAmount({ - value: String(trx.value) ?? 0, - assetCode: trx.assetCode, - assetScale: trx.assetScale - }).amount - } - - - - - - {formatDate({ date: trx.createdAt.toString() })} - -
- )) + transactions.results.map((trx) => + trx.description !== ASSET_SCALE_IMBALANCE ? ( + <> + + {trx.accountName} + + {trx.walletAddressPublicName ?? + trx.walletAddressUrl ?? + ''} + {trx.walletAddressUrl ? ( + + {trx.walletAddressUrl} + + ) : null} + + + {trx.description ? ( + trx.description + ) : ( +

No description

+ )} +
+ + {trx.type === 'INCOMING' ? '+' : '-'} + { + formatAmount({ + value: String(trx.value) ?? 0, + assetCode: trx.assetCode, + assetScale: trx.assetScale + }).amount + } + + + + + + {formatDate({ date: trx.createdAt.toString() })} + +
+ + ) : null + ) ) : ( diff --git a/packages/wallet/frontend/src/utils/constants.ts b/packages/wallet/frontend/src/utils/constants.ts index bcac57bd8..fe5925b95 100644 --- a/packages/wallet/frontend/src/utils/constants.ts +++ b/packages/wallet/frontend/src/utils/constants.ts @@ -19,6 +19,9 @@ export const INTERLEDGER_WALLET_ADDRESS = '$ilp.rafiki.money/interledger' // Default number of grants to be shown on page export const GRANTS_DISPLAY_NR = 10 -//Default Base64 encoded Public Key +// Default Base64 encoded Public Key export const BASE64_PUBLIC_KEY = 'ewogICJrdHkiOiAiT0tQIiwKICAiY3J2IjogIkVkMjU1MTkiLAogICJraWQiOiAidGVzdC1rZXktZWQyNTUxOSIsCiAgIngiOiAiSnJRTGo1UF84OWlYRVM5LXZGZ3JJeTI5Y2xGOUNDX29QUHN3M2M1RDBicyIKfQ==' + +// Transaction asset scale 9 imbalance note +export const ASSET_SCALE_IMBALANCE = 'Asset scale 9 imbalance' From 308306e2c5f7bdf38593e4aa468afa54da3574ae Mon Sep 17 00:00:00 2001 From: Tymmmy <117268143+Tymmmy@users.noreply.github.com> Date: Mon, 19 Aug 2024 16:54:24 +0300 Subject: [PATCH 38/58] next version update for error fixes --- packages/wallet/frontend/package.json | 2 +- pnpm-lock.yaml | 196 +++++++++++--------------- 2 files changed, 84 insertions(+), 114 deletions(-) diff --git a/packages/wallet/frontend/package.json b/packages/wallet/frontend/package.json index 6cdefa69e..d0203b408 100644 --- a/packages/wallet/frontend/package.json +++ b/packages/wallet/frontend/package.json @@ -13,7 +13,7 @@ "class-variance-authority": "^0.7.0", "@wallet/shared": "workspace:*", "ky": "^1.5.0", - "next": "13.4.12", + "next": "14.2.5", "nprogress": "^0.2.0", "react": "18.3.1", "react-dom": "18.3.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0fda03722..571f8ee32 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -195,7 +195,7 @@ importers: version: 18.3.0 '@vitejs/plugin-react-swc': specifier: ^3.7.0 - version: 3.7.0(@swc/helpers@0.5.1)(vite@5.3.5(@types/node@20.12.11)) + version: 3.7.0(@swc/helpers@0.5.5)(vite@5.3.5(@types/node@20.12.11)) autoprefixer: specifier: ^10.4.20 version: 10.4.20(postcss@8.4.41) @@ -317,7 +317,7 @@ importers: version: 5.4.1 iron-session: specifier: ^6.3.1 - version: 6.3.1(express@4.19.2)(koa@2.14.2)(next@13.4.12(@babel/core@7.23.0)(babel-plugin-macros@3.1.0)) + version: 6.3.1(express@4.19.2)(koa@2.14.2)(next@14.2.5(@babel/core@7.23.0)(babel-plugin-macros@3.1.0)) knex: specifier: ^3.1.0 version: 3.1.0(pg@8.12.0) @@ -419,8 +419,8 @@ importers: specifier: ^1.5.0 version: 1.5.0 next: - specifier: 13.4.12 - version: 13.4.12(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + specifier: 14.2.5 + version: 14.2.5(react-dom@18.3.1(react@18.3.1))(react@18.3.1) nprogress: specifier: ^0.2.0 version: 0.2.0 @@ -1638,62 +1638,62 @@ packages: '@next/bundle-analyzer@13.5.4': resolution: {integrity: sha512-2vgmkuSKyTiyI7NorL+zYerxQRvzmSGbCDr2/kVrbKX28a4UNhbYn8/cQW8z6pvx0EncEFpd0GCUA5r9aRLhJg==} - '@next/env@13.4.12': - resolution: {integrity: sha512-RmHanbV21saP/6OEPBJ7yJMuys68cIf8OBBWd7+uj40LdpmswVAwe1uzeuFyUsd6SfeITWT3XnQfn6wULeKwDQ==} + '@next/env@14.2.5': + resolution: {integrity: sha512-/zZGkrTOsraVfYjGP8uM0p6r0BDT6xWpkjdVbcz66PJVSpwXX3yNiRycxAuDfBKGWBrZBXRuK/YVlkNgxHGwmA==} '@next/eslint-plugin-next@13.5.4': resolution: {integrity: sha512-vI94U+D7RNgX6XypSyjeFrOzxGlZyxOplU0dVE5norIfZGn/LDjJYPHdvdsR5vN1eRtl6PDAsOHmycFEOljK5A==} - '@next/swc-darwin-arm64@13.4.12': - resolution: {integrity: sha512-deUrbCXTMZ6ZhbOoloqecnUeNpUOupi8SE2tx4jPfNS9uyUR9zK4iXBvH65opVcA/9F5I/p8vDXSYbUlbmBjZg==} + '@next/swc-darwin-arm64@14.2.5': + resolution: {integrity: sha512-/9zVxJ+K9lrzSGli1///ujyRfon/ZneeZ+v4ptpiPoOU+GKZnm8Wj8ELWU1Pm7GHltYRBklmXMTUqM/DqQ99FQ==} engines: {node: '>= 10'} cpu: [arm64] os: [darwin] - '@next/swc-darwin-x64@13.4.12': - resolution: {integrity: sha512-WRvH7RxgRHlC1yb5oG0ZLx8F7uci9AivM5/HGGv9ZyG2Als8Ij64GC3d+mQ5sJhWjusyU6T6V1WKTUoTmOB0zQ==} + '@next/swc-darwin-x64@14.2.5': + resolution: {integrity: sha512-vXHOPCwfDe9qLDuq7U1OYM2wUY+KQ4Ex6ozwsKxp26BlJ6XXbHleOUldenM67JRyBfVjv371oneEvYd3H2gNSA==} engines: {node: '>= 10'} cpu: [x64] os: [darwin] - '@next/swc-linux-arm64-gnu@13.4.12': - resolution: {integrity: sha512-YEKracAWuxp54tKiAvvq73PUs9lok57cc8meYRibTWe/VdPB2vLgkTVWFcw31YDuRXdEhdX0fWS6Q+ESBhnEig==} + '@next/swc-linux-arm64-gnu@14.2.5': + resolution: {integrity: sha512-vlhB8wI+lj8q1ExFW8lbWutA4M2ZazQNvMWuEDqZcuJJc78iUnLdPPunBPX8rC4IgT6lIx/adB+Cwrl99MzNaA==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] - '@next/swc-linux-arm64-musl@13.4.12': - resolution: {integrity: sha512-LhJR7/RAjdHJ2Isl2pgc/JaoxNk0KtBgkVpiDJPVExVWA1c6gzY57+3zWuxuyWzTG+fhLZo2Y80pLXgIJv7g3g==} + '@next/swc-linux-arm64-musl@14.2.5': + resolution: {integrity: sha512-NpDB9NUR2t0hXzJJwQSGu1IAOYybsfeB+LxpGsXrRIb7QOrYmidJz3shzY8cM6+rO4Aojuef0N/PEaX18pi9OA==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] - '@next/swc-linux-x64-gnu@13.4.12': - resolution: {integrity: sha512-1DWLL/B9nBNiQRng+1aqs3OaZcxC16Nf+mOnpcrZZSdyKHek3WQh6j/fkbukObgNGwmCoVevLUa/p3UFTTqgqg==} + '@next/swc-linux-x64-gnu@14.2.5': + resolution: {integrity: sha512-8XFikMSxWleYNryWIjiCX+gU201YS+erTUidKdyOVYi5qUQo/gRxv/3N1oZFCgqpesN6FPeqGM72Zve+nReVXQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] - '@next/swc-linux-x64-musl@13.4.12': - resolution: {integrity: sha512-kEAJmgYFhp0VL+eRWmUkVxLVunn7oL9Mdue/FS8yzRBVj7Z0AnIrHpTIeIUl1bbdQq1VaoOztnKicAjfkLTRCQ==} + '@next/swc-linux-x64-musl@14.2.5': + resolution: {integrity: sha512-6QLwi7RaYiQDcRDSU/os40r5o06b5ue7Jsk5JgdRBGGp8l37RZEh9JsLSM8QF0YDsgcosSeHjglgqi25+m04IQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] - '@next/swc-win32-arm64-msvc@13.4.12': - resolution: {integrity: sha512-GMLuL/loR6yIIRTnPRY6UGbLL9MBdw2anxkOnANxvLvsml4F0HNIgvnU3Ej4BjbqMTNjD4hcPFdlEow4XHPdZA==} + '@next/swc-win32-arm64-msvc@14.2.5': + resolution: {integrity: sha512-1GpG2VhbspO+aYoMOQPQiqc/tG3LzmsdBH0LhnDS3JrtDx2QmzXe0B6mSZZiN3Bq7IOMXxv1nlsjzoS1+9mzZw==} engines: {node: '>= 10'} cpu: [arm64] os: [win32] - '@next/swc-win32-ia32-msvc@13.4.12': - resolution: {integrity: sha512-PhgNqN2Vnkm7XaMdRmmX0ZSwZXQAtamBVSa9A/V1dfKQCV1rjIZeiy/dbBnVYGdj63ANfsOR/30XpxP71W0eww==} + '@next/swc-win32-ia32-msvc@14.2.5': + resolution: {integrity: sha512-Igh9ZlxwvCDsu6438FXlQTHlRno4gFpJzqPjSIBZooD22tKeI4fE/YMRoHVJHmrQ2P5YL1DoZ0qaOKkbeFWeMg==} engines: {node: '>= 10'} cpu: [ia32] os: [win32] - '@next/swc-win32-x64-msvc@13.4.12': - resolution: {integrity: sha512-Z+56e/Ljt0bUs+T+jPjhFyxYBcdY2RIq9ELFU+qAMQMteHo7ymbV7CKmlcX59RI9C4YzN8PgMgLyAoi916b5HA==} + '@next/swc-win32-x64-msvc@14.2.5': + resolution: {integrity: sha512-tEQ7oinq1/CjSG9uSTerca3v4AZ+dFa+4Yu6ihaG8Ud8ddqLQgFGcnwYls13H5X5CPDPZJdYxyeMui6muOLd4g==} engines: {node: '>= 10'} cpu: [x64] os: [win32] @@ -2266,8 +2266,8 @@ packages: '@swc/counter@0.1.3': resolution: {integrity: sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==} - '@swc/helpers@0.5.1': - resolution: {integrity: sha512-sJ902EfIzn1Fa+qYmjdQqh8tPsoxyBz+8yBKC2HKUxyezKJFwPGOn7pv4WY6QuQW//ySQi5lJjA/ZT9sNWWNTg==} + '@swc/helpers@0.5.5': + resolution: {integrity: sha512-KGYxvIOXcceOAbEk4bi/dVLEK9z8sZ0uBB3Il5b1rhfClSpcX0yfRO0KmTkqR2cnQDymwLB+25ZyMzICg/cm/A==} '@swc/types@0.1.8': resolution: {integrity: sha512-RNFA3+7OJFNYY78x0FYwi1Ow+iF1eF5WvmfY1nXPOEH4R2p/D4Cr1vzje7dNAI2aLFqpv8Wyz4oKSWqIZArpQA==} @@ -2928,12 +2928,6 @@ packages: resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==} engines: {node: '>=10'} - caniuse-lite@1.0.30001543: - resolution: {integrity: sha512-qxdO8KPWPQ+Zk6bvNpPeQIOH47qZSYdFZd6dXQzb2KzhnSXju4Kd7H1PkSJx6NICSMgo/IhRZRhhfPTHYpJUCA==} - - caniuse-lite@1.0.30001599: - resolution: {integrity: sha512-LRAQHZ4yT1+f9LemSMeqdMpMxZcc4RMWdj4tiFe3G8tNkWK+E58g+/tzotb5cU6TbcVJLr4fySiAW7XmxQvZQA==} - caniuse-lite@1.0.30001649: resolution: {integrity: sha512-fJegqZZ0ZX8HOWr6rcafGr72+xcgJKI9oWfDW5DrD7ExUtgZC7a7R7ZYmZqplh7XDocFdGeIFn7roAxhOeYrPQ==} @@ -3823,9 +3817,6 @@ packages: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} - glob-to-regexp@0.4.1: - resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} - glob@10.4.5: resolution: {integrity: sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==} hasBin: true @@ -4804,20 +4795,20 @@ packages: resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==} engines: {node: '>= 0.6'} - next@13.4.12: - resolution: {integrity: sha512-eHfnru9x6NRmTMcjQp6Nz0J4XH9OubmzOa7CkWL+AUrUxpibub3vWwttjduu9No16dug1kq04hiUUpo7J3m3Xw==} - engines: {node: '>=16.8.0'} + next@14.2.5: + resolution: {integrity: sha512-0f8aRfBVL+mpzfBjYfQuLWh2WyAwtJXCRfkPF4UJ5qd2YwrHczsrSzXU4tRMV0OAxR8ZJZWPFn6uhSC56UTsLA==} + engines: {node: '>=18.17.0'} hasBin: true peerDependencies: '@opentelemetry/api': ^1.1.0 - fibers: '>= 3.1.0' + '@playwright/test': ^1.41.2 react: ^18.2.0 react-dom: ^18.2.0 sass: ^1.3.0 peerDependenciesMeta: '@opentelemetry/api': optional: true - fibers: + '@playwright/test': optional: true sass: optional: true @@ -5173,8 +5164,8 @@ packages: postcss-value-parser@4.2.0: resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==} - postcss@8.4.14: - resolution: {integrity: sha512-E398TUmfAYFPBSdzgeieK2Y1+1cpdxJx8yXbK/m57nRhKSmk1GB2tO4lbLBtlkfPQTDKfe4Xqv1ASWPpayPEig==} + postcss@8.4.31: + resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==} engines: {node: ^10 || ^12 || >=14} postcss@8.4.41: @@ -6277,10 +6268,6 @@ packages: walker@1.0.8: resolution: {integrity: sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==} - watchpack@2.4.0: - resolution: {integrity: sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg==} - engines: {node: '>=10.13.0'} - wcwidth@1.0.1: resolution: {integrity: sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==} @@ -6467,9 +6454,6 @@ packages: resolution: {integrity: sha512-zK7YHHz4ZXpW89AHXUPbQVGKI7uvkd3hzusTdotCg1UxyaVtg0zFJSTfW/Dq5f7OBBVnq6cZIaC8Ti4hb6dtCA==} engines: {node: '>= 14'} - zod@3.21.4: - resolution: {integrity: sha512-m46AKbrzKVzOzs/DZgVnG5H55N1sv1M8qZU3A8RIKbs3mrACDNeIOeilDymVb2HdmP8uwshOCF4uJ8uM9rCqJw==} - zod@3.23.8: resolution: {integrity: sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==} @@ -7977,37 +7961,37 @@ snapshots: - bufferutil - utf-8-validate - '@next/env@13.4.12': {} + '@next/env@14.2.5': {} '@next/eslint-plugin-next@13.5.4': dependencies: glob: 7.1.7 - '@next/swc-darwin-arm64@13.4.12': + '@next/swc-darwin-arm64@14.2.5': optional: true - '@next/swc-darwin-x64@13.4.12': + '@next/swc-darwin-x64@14.2.5': optional: true - '@next/swc-linux-arm64-gnu@13.4.12': + '@next/swc-linux-arm64-gnu@14.2.5': optional: true - '@next/swc-linux-arm64-musl@13.4.12': + '@next/swc-linux-arm64-musl@14.2.5': optional: true - '@next/swc-linux-x64-gnu@13.4.12': + '@next/swc-linux-x64-gnu@14.2.5': optional: true - '@next/swc-linux-x64-musl@13.4.12': + '@next/swc-linux-x64-musl@14.2.5': optional: true - '@next/swc-win32-arm64-msvc@13.4.12': + '@next/swc-win32-arm64-msvc@14.2.5': optional: true - '@next/swc-win32-ia32-msvc@13.4.12': + '@next/swc-win32-ia32-msvc@14.2.5': optional: true - '@next/swc-win32-x64-msvc@13.4.12': + '@next/swc-win32-x64-msvc@14.2.5': optional: true '@nodelib/fs.scandir@2.1.5': @@ -8505,7 +8489,7 @@ snapshots: '@swc/core-win32-x64-msvc@1.5.28': optional: true - '@swc/core@1.5.28(@swc/helpers@0.5.1)': + '@swc/core@1.5.28(@swc/helpers@0.5.5)': dependencies: '@swc/counter': 0.1.3 '@swc/types': 0.1.8 @@ -8520,12 +8504,13 @@ snapshots: '@swc/core-win32-arm64-msvc': 1.5.28 '@swc/core-win32-ia32-msvc': 1.5.28 '@swc/core-win32-x64-msvc': 1.5.28 - '@swc/helpers': 0.5.1 + '@swc/helpers': 0.5.5 '@swc/counter@0.1.3': {} - '@swc/helpers@0.5.1': + '@swc/helpers@0.5.5': dependencies: + '@swc/counter': 0.1.3 tslib: 2.6.2 '@swc/types@0.1.8': @@ -8859,9 +8844,9 @@ snapshots: '@ungap/structured-clone@1.2.0': {} - '@vitejs/plugin-react-swc@3.7.0(@swc/helpers@0.5.1)(vite@5.3.5(@types/node@20.12.11))': + '@vitejs/plugin-react-swc@3.7.0(@swc/helpers@0.5.5)(vite@5.3.5(@types/node@20.12.11))': dependencies: - '@swc/core': 1.5.28(@swc/helpers@0.5.1) + '@swc/core': 1.5.28(@swc/helpers@0.5.5) vite: 5.3.5(@types/node@20.12.11) transitivePeerDependencies: - '@swc/helpers' @@ -9289,7 +9274,7 @@ snapshots: browserslist@4.23.0: dependencies: - caniuse-lite: 1.0.30001599 + caniuse-lite: 1.0.30001649 electron-to-chromium: 1.4.681 node-releases: 2.0.14 update-browserslist-db: 1.0.13(browserslist@4.23.0) @@ -9362,10 +9347,6 @@ snapshots: camelcase@6.3.0: {} - caniuse-lite@1.0.30001543: {} - - caniuse-lite@1.0.30001599: {} - caniuse-lite@1.0.30001649: {} capital-case@1.0.4: @@ -10410,8 +10391,6 @@ snapshots: dependencies: is-glob: 4.0.3 - glob-to-regexp@0.4.1: {} - glob@10.4.5: dependencies: foreground-child: 3.2.1 @@ -10741,7 +10720,7 @@ snapshots: ipaddr.js@1.9.1: {} - iron-session@6.3.1(express@4.19.2)(koa@2.14.2)(next@13.4.12(@babel/core@7.23.0)(babel-plugin-macros@3.1.0)): + iron-session@6.3.1(express@4.19.2)(koa@2.14.2)(next@14.2.5(@babel/core@7.23.0)(babel-plugin-macros@3.1.0)): dependencies: '@peculiar/webcrypto': 1.4.3 '@types/cookie': 0.5.2 @@ -10753,7 +10732,7 @@ snapshots: optionalDependencies: express: 4.19.2 koa: 2.14.2 - next: 13.4.12(@babel/core@7.23.0)(babel-plugin-macros@3.1.0) + next: 14.2.5(@babel/core@7.23.0)(babel-plugin-macros@3.1.0) iron-webcrypto@0.2.8: dependencies: @@ -11624,53 +11603,51 @@ snapshots: negotiator@0.6.3: {} - next@13.4.12(@babel/core@7.23.0)(babel-plugin-macros@3.1.0): + next@14.2.5(@babel/core@7.23.0)(babel-plugin-macros@3.1.0): dependencies: - '@next/env': 13.4.12 - '@swc/helpers': 0.5.1 + '@next/env': 14.2.5 + '@swc/helpers': 0.5.5 busboy: 1.6.0 - caniuse-lite: 1.0.30001543 - postcss: 8.4.14 + caniuse-lite: 1.0.30001649 + graceful-fs: 4.2.11 + postcss: 8.4.31 styled-jsx: 5.1.1(@babel/core@7.23.0)(babel-plugin-macros@3.1.0) - watchpack: 2.4.0 - zod: 3.21.4 optionalDependencies: - '@next/swc-darwin-arm64': 13.4.12 - '@next/swc-darwin-x64': 13.4.12 - '@next/swc-linux-arm64-gnu': 13.4.12 - '@next/swc-linux-arm64-musl': 13.4.12 - '@next/swc-linux-x64-gnu': 13.4.12 - '@next/swc-linux-x64-musl': 13.4.12 - '@next/swc-win32-arm64-msvc': 13.4.12 - '@next/swc-win32-ia32-msvc': 13.4.12 - '@next/swc-win32-x64-msvc': 13.4.12 + '@next/swc-darwin-arm64': 14.2.5 + '@next/swc-darwin-x64': 14.2.5 + '@next/swc-linux-arm64-gnu': 14.2.5 + '@next/swc-linux-arm64-musl': 14.2.5 + '@next/swc-linux-x64-gnu': 14.2.5 + '@next/swc-linux-x64-musl': 14.2.5 + '@next/swc-win32-arm64-msvc': 14.2.5 + '@next/swc-win32-ia32-msvc': 14.2.5 + '@next/swc-win32-x64-msvc': 14.2.5 transitivePeerDependencies: - '@babel/core' - babel-plugin-macros optional: true - next@13.4.12(react-dom@18.3.1(react@18.3.1))(react@18.3.1): + next@14.2.5(react-dom@18.3.1(react@18.3.1))(react@18.3.1): dependencies: - '@next/env': 13.4.12 - '@swc/helpers': 0.5.1 + '@next/env': 14.2.5 + '@swc/helpers': 0.5.5 busboy: 1.6.0 - caniuse-lite: 1.0.30001543 - postcss: 8.4.14 + caniuse-lite: 1.0.30001649 + graceful-fs: 4.2.11 + postcss: 8.4.31 react: 18.3.1 react-dom: 18.3.1(react@18.3.1) styled-jsx: 5.1.1(react@18.3.1) - watchpack: 2.4.0 - zod: 3.21.4 optionalDependencies: - '@next/swc-darwin-arm64': 13.4.12 - '@next/swc-darwin-x64': 13.4.12 - '@next/swc-linux-arm64-gnu': 13.4.12 - '@next/swc-linux-arm64-musl': 13.4.12 - '@next/swc-linux-x64-gnu': 13.4.12 - '@next/swc-linux-x64-musl': 13.4.12 - '@next/swc-win32-arm64-msvc': 13.4.12 - '@next/swc-win32-ia32-msvc': 13.4.12 - '@next/swc-win32-x64-msvc': 13.4.12 + '@next/swc-darwin-arm64': 14.2.5 + '@next/swc-darwin-x64': 14.2.5 + '@next/swc-linux-arm64-gnu': 14.2.5 + '@next/swc-linux-arm64-musl': 14.2.5 + '@next/swc-linux-x64-gnu': 14.2.5 + '@next/swc-linux-x64-musl': 14.2.5 + '@next/swc-win32-arm64-msvc': 14.2.5 + '@next/swc-win32-ia32-msvc': 14.2.5 + '@next/swc-win32-x64-msvc': 14.2.5 transitivePeerDependencies: - '@babel/core' - babel-plugin-macros @@ -12039,7 +12016,7 @@ snapshots: postcss-value-parser@4.2.0: {} - postcss@8.4.14: + postcss@8.4.31: dependencies: nanoid: 3.3.7 picocolors: 1.0.1 @@ -13239,11 +13216,6 @@ snapshots: dependencies: makeerror: 1.0.12 - watchpack@2.4.0: - dependencies: - glob-to-regexp: 0.4.1 - graceful-fs: 4.2.11 - wcwidth@1.0.1: dependencies: defaults: 1.0.4 @@ -13444,6 +13416,4 @@ snapshots: compress-commons: 6.0.2 readable-stream: 4.4.2 - zod@3.21.4: {} - zod@3.23.8: {} From dfbf7f37aed36edad4aa6130097924186b3b4e59 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 20 Aug 2024 21:06:21 +0300 Subject: [PATCH 39/58] Update Rapyd threshold --- docker/dev/docker-compose.yml | 2 +- packages/wallet/backend/src/config/env.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker/dev/docker-compose.yml b/docker/dev/docker-compose.yml index a1904ff30..7e338705f 100644 --- a/docker/dev/docker-compose.yml +++ b/docker/dev/docker-compose.yml @@ -54,7 +54,7 @@ services: RATE_API_KEY: ${RATE_API_KEY} BASE_ASSET_SCALE: 2 MAX_ASSET_SCALE: 9 - RAPYD_THRESHOLD: 100000000 # 0.1 + RAPYD_THRESHOLD: 10000000 # 0.01 DEBT_THRESHOLD: 5 REDIS_URL: redis://redis:6379/0 restart: always diff --git a/packages/wallet/backend/src/config/env.ts b/packages/wallet/backend/src/config/env.ts index 766fc1504..620e0cfa9 100644 --- a/packages/wallet/backend/src/config/env.ts +++ b/packages/wallet/backend/src/config/env.ts @@ -34,7 +34,7 @@ const envSchema = z.object({ .transform((value) => value === 'true'), BASE_ASSET_SCALE: z.coerce.number().nonnegative().default(2), MAX_ASSET_SCALE: z.coerce.number().nonnegative().default(9), - RAPYD_THRESHOLD: z.coerce.bigint().nonnegative().default(100_000_000n), // $0.1 in asset scale 9 + RAPYD_THRESHOLD: z.coerce.bigint().nonnegative().default(100_000_00n), // $0.01 in asset scale 9 DEBT_THRESHOLD: z.coerce.number().multipleOf(0.01).nonnegative().default(5.0), // $5.00 DEFAULT_WALLET_ACCOUNT: z .object({ From 021c9b8fdcc5f6a9bc98e7ca4e3398baffd3ff01 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 20 Aug 2024 21:08:09 +0300 Subject: [PATCH 40/58] Use truncate for amounts to prevent ceiling --- packages/wallet/backend/src/rafiki/service.ts | 9 +++++---- packages/wallet/backend/src/walletAddress/service.ts | 12 ++++++------ 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/packages/wallet/backend/src/rafiki/service.ts b/packages/wallet/backend/src/rafiki/service.ts index a2f83bcae..74d104241 100644 --- a/packages/wallet/backend/src/rafiki/service.ts +++ b/packages/wallet/backend/src/rafiki/service.ts @@ -166,11 +166,12 @@ export class RafikiService implements IRafikiService { private amountToNumber( amount: Amount, - assetScale: number = amount.assetScale + toAssetScale: number = amount.assetScale ): number { - return +(Number(amount.value) * 10 ** -amount.assetScale).toFixed( - assetScale - ) + const factor = 10 ** toAssetScale; + const scaledValue = Number(amount.value) * 10 ** -amount.assetScale; + const truncatedValue = Math.floor(scaledValue * factor) / factor; + return truncatedValue; } private async handleIncomingPaymentCompleted(wh: WebHook) { diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index ffbff9b00..7f7fea97f 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -278,12 +278,12 @@ export class WalletAddressService implements IWalletAddressService { ) } - const amount = Number( - ( - Number(balance * this.env.RAPYD_THRESHOLD) * - 10 ** -walletAddress.assetScale - ).toPrecision(2) + const value = ( + Number(balance * this.env.RAPYD_THRESHOLD) * + 10 ** -walletAddress.assetScale ) + const factor = 10 ** this.env.BASE_ASSET_SCALE; + const amount = Math.floor(value * factor) / factor; if (!walletAddress.account.user.rapydWalletId) { throw new Error( @@ -338,7 +338,7 @@ export class WalletAddressService implements IWalletAddressService { accountId: walletAddress.accountId, paymentId: transfer.data.id, assetCode: walletAddress.assetCode!, - value: BigInt(amount * 10 ** this.env.BASE_ASSET_SCALE), + value: BigInt(Math.floor(amount * 10 ** this.env.MAX_ASSET_SCALE - this.env.BASE_ASSET_SCALE)), type, status: 'COMPLETED', description: 'Asset scale 9 imbalance' From b920316d8058f17d9e8a257567d8c1e98bdec83a Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 20 Aug 2024 21:08:58 +0300 Subject: [PATCH 41/58] Skip imbalance transactions when syncing balances --- packages/wallet/backend/src/transaction/service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/wallet/backend/src/transaction/service.ts b/packages/wallet/backend/src/transaction/service.ts index cb64b76ac..597daf5be 100644 --- a/packages/wallet/backend/src/transaction/service.ts +++ b/packages/wallet/backend/src/transaction/service.ts @@ -176,7 +176,6 @@ export class TransactionService implements ITransactionService { since: Date, trx?: TransactionOrKnex ) { - //TODO updatedAt instead of createdAt? const transactions = await Transaction.query(trx) .where({ walletAddressId, @@ -184,6 +183,7 @@ export class TransactionService implements ITransactionService { status: 'COMPLETED' }) .andWhere('createdAt', '>', since) + .andWhereNot('description', 'Asset scale 9 imbalance'); const ids = transactions.map(({ id }) => id) const sumResult = (await Transaction.query(trx) From 4601b42a00e4e68b2ac11229458c85d5290ac3bd Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 20 Aug 2024 21:10:01 +0300 Subject: [PATCH 42/58] Prevent ceiling when formatting amounts in frontend --- packages/wallet/frontend/src/utils/helpers.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index 3e98b48de..59fee5563 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -40,6 +40,10 @@ type FormatAmountArgs = AssetOP & { export const formatAmount = (args: FormatAmountArgs): FormattedAmount => { const { value, displayScale = 9, assetCode, assetScale } = args + + const scaledValue = Number(`${value}e-${assetScale}`) + const flooredValue = Math.floor(scaledValue * 10 ** displayScale) / 10 ** displayScale + const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: assetCode, @@ -47,7 +51,7 @@ export const formatAmount = (args: FormatAmountArgs): FormattedAmount => { minimumFractionDigits: displayScale }) - const amount = formatter.format(Number(`${value}e-${assetScale}`)) + const amount = formatter.format(flooredValue) const symbol = getCurrencySymbol(assetCode) return { @@ -79,6 +83,7 @@ export const getFee = (quote: QuoteResponse): FormattedAmount => { return formatAmount({ assetCode: quote.fee.assetCode, assetScale: quote.fee.assetScale, + displayScale: 2, value: quote.fee.value }) } @@ -89,6 +94,7 @@ export const getFee = (quote: QuoteResponse): FormattedAmount => { return formatAmount({ assetCode: quote.debitAmount.assetCode, assetScale: quote.debitAmount.assetScale, + displayScale: 2, value: fee.toString() }) } From 1593a26670a79c5e71e8a7031cac55bddb0b4c7b Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 20 Aug 2024 21:10:46 +0300 Subject: [PATCH 43/58] Use scale 2 in quote dialog and notifications --- packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx | 2 ++ packages/wallet/frontend/src/pages/_app.tsx | 2 ++ 2 files changed, 4 insertions(+) diff --git a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx index 4a17299db..6302c98b0 100644 --- a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx +++ b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx @@ -26,12 +26,14 @@ export const QuoteDialog = ({ const receiveAmount = formatAmount({ value: quote.receiveAmount.value, + displayScale: 2, assetCode: quote.receiveAmount.assetCode, assetScale: quote.receiveAmount.assetScale }) const debitAmount = formatAmount({ value: quote.debitAmount.value, + displayScale: 2, assetCode: quote.debitAmount.assetCode, assetScale: quote.debitAmount.assetScale }) diff --git a/packages/wallet/frontend/src/pages/_app.tsx b/packages/wallet/frontend/src/pages/_app.tsx index bf1bbdad9..2ccb7f8fb 100644 --- a/packages/wallet/frontend/src/pages/_app.tsx +++ b/packages/wallet/frontend/src/pages/_app.tsx @@ -40,6 +40,7 @@ export default function App({ Component, pageProps }: AppPropsWithLayout) { { formatAmount({ value: amount.value, + displayScale: 2, assetCode: amount.assetCode, assetScale: amount.assetScale }).amount @@ -68,6 +69,7 @@ export default function App({ Component, pageProps }: AppPropsWithLayout) { { formatAmount({ value: amount.value, + displayScale: 2, assetCode: amount.assetCode, assetScale: amount.assetScale }).amount From ed442426551b09b79b6648e76bf5d85b52f345c2 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Tue, 20 Aug 2024 21:11:16 +0300 Subject: [PATCH 44/58] Prettier --- packages/wallet/backend/src/rafiki/service.ts | 8 ++++---- packages/wallet/backend/src/transaction/service.ts | 2 +- .../wallet/backend/src/walletAddress/service.ts | 13 ++++++++----- packages/wallet/frontend/src/utils/helpers.ts | 3 ++- 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/packages/wallet/backend/src/rafiki/service.ts b/packages/wallet/backend/src/rafiki/service.ts index 74d104241..004308290 100644 --- a/packages/wallet/backend/src/rafiki/service.ts +++ b/packages/wallet/backend/src/rafiki/service.ts @@ -168,10 +168,10 @@ export class RafikiService implements IRafikiService { amount: Amount, toAssetScale: number = amount.assetScale ): number { - const factor = 10 ** toAssetScale; - const scaledValue = Number(amount.value) * 10 ** -amount.assetScale; - const truncatedValue = Math.floor(scaledValue * factor) / factor; - return truncatedValue; + const factor = 10 ** toAssetScale + const scaledValue = Number(amount.value) * 10 ** -amount.assetScale + const truncatedValue = Math.floor(scaledValue * factor) / factor + return truncatedValue } private async handleIncomingPaymentCompleted(wh: WebHook) { diff --git a/packages/wallet/backend/src/transaction/service.ts b/packages/wallet/backend/src/transaction/service.ts index 597daf5be..983a77fcb 100644 --- a/packages/wallet/backend/src/transaction/service.ts +++ b/packages/wallet/backend/src/transaction/service.ts @@ -183,7 +183,7 @@ export class TransactionService implements ITransactionService { status: 'COMPLETED' }) .andWhere('createdAt', '>', since) - .andWhereNot('description', 'Asset scale 9 imbalance'); + .andWhereNot('description', 'Asset scale 9 imbalance') const ids = transactions.map(({ id }) => id) const sumResult = (await Transaction.query(trx) diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index 7f7fea97f..a6d4804c1 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -278,12 +278,11 @@ export class WalletAddressService implements IWalletAddressService { ) } - const value = ( + const value = Number(balance * this.env.RAPYD_THRESHOLD) * 10 ** -walletAddress.assetScale - ) - const factor = 10 ** this.env.BASE_ASSET_SCALE; - const amount = Math.floor(value * factor) / factor; + const factor = 10 ** this.env.BASE_ASSET_SCALE + const amount = Math.floor(value * factor) / factor if (!walletAddress.account.user.rapydWalletId) { throw new Error( @@ -338,7 +337,11 @@ export class WalletAddressService implements IWalletAddressService { accountId: walletAddress.accountId, paymentId: transfer.data.id, assetCode: walletAddress.assetCode!, - value: BigInt(Math.floor(amount * 10 ** this.env.MAX_ASSET_SCALE - this.env.BASE_ASSET_SCALE)), + value: BigInt( + Math.floor( + amount * 10 ** this.env.MAX_ASSET_SCALE - this.env.BASE_ASSET_SCALE + ) + ), type, status: 'COMPLETED', description: 'Asset scale 9 imbalance' diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index 59fee5563..15929b601 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -42,7 +42,8 @@ export const formatAmount = (args: FormatAmountArgs): FormattedAmount => { const { value, displayScale = 9, assetCode, assetScale } = args const scaledValue = Number(`${value}e-${assetScale}`) - const flooredValue = Math.floor(scaledValue * 10 ** displayScale) / 10 ** displayScale + const flooredValue = + Math.floor(scaledValue * 10 ** displayScale) / 10 ** displayScale const formatter = new Intl.NumberFormat('en-US', { style: 'currency', From ba0ff7b340c2375b2c9ca75f9434dc671392d04e Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 17:32:17 +0300 Subject: [PATCH 45/58] Remove unused file --- .../backend/src/config/walletAddress.ts | 25 ------------------- 1 file changed, 25 deletions(-) delete mode 100644 packages/wallet/backend/src/config/walletAddress.ts diff --git a/packages/wallet/backend/src/config/walletAddress.ts b/packages/wallet/backend/src/config/walletAddress.ts deleted file mode 100644 index 321478a18..000000000 --- a/packages/wallet/backend/src/config/walletAddress.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { Env } from '@/config/env' -import { RafikiClient } from '@/rafiki/rafiki-client' -import { AccountService } from '@/account/service' -import { WalletAddressService } from '@/walletAddress/service' -import { TransactionService } from '@/transaction/service' -import { RapydClient } from '@/rapyd/rapyd-client' -import { Logger } from 'winston' - -export function createWalletAddressService( - env: Env, - rafikiClient: RafikiClient, - accountService: AccountService, - rapydClient: RapydClient, - transactionService: TransactionService, - logger: Logger -) { - return new WalletAddressService( - accountService, - rafikiClient, - env, - transactionService, - rapydClient, - logger - ) -} From 29cc5e9ac0d1353ea2ea3f9567f006b50b0a91e0 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 17:34:59 +0300 Subject: [PATCH 46/58] Cache all WAs --- .../backend/src/walletAddress/service.ts | 42 ++++++++++++++++++- .../tests/walletAddress/service.test.ts | 5 +++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index a6d4804c1..5dc7494fd 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -4,6 +4,7 @@ import { Env } from '@/config/env' import { RafikiClient } from '@/rafiki/rafiki-client' import axios from 'axios' import { getRandomValues } from 'crypto' +import { Cache, RedisClient } from '@shared/backend' import { WalletAddress } from './model' import { PartialModelObject, TransactionOrKnex, raw } from 'objection' import { RapydClient } from '@/rapyd/rapyd-client' @@ -75,14 +76,18 @@ export const createWalletAddressIfFalsy = async ({ } export class WalletAddressService implements IWalletAddressService { + private cache: Cache constructor( private accountService: AccountService, private rafikiClient: RafikiClient, private env: Env, + redisClient: RedisClient, private transactionService: TransactionService, private rapydClient: RapydClient, private logger: Logger - ) {} + ) { + this.cache = new Cache(redisClient, 'WalletAddresses') + } async create(args: CreateWalletAddressArgs): Promise { const account = await this.accountService.findAccountById( @@ -129,6 +134,10 @@ export class WalletAddressService implements IWalletAddressService { assetCode: account.assetCode, assetScale: this.env.MAX_ASSET_SCALE }) + + await this.cache.set(walletAddress.id, walletAddress, { + expiry: 60 + }) } return walletAddress @@ -154,6 +163,13 @@ export class WalletAddressService implements IWalletAddressService { } async getById(args: GetWalletAddressArgs): Promise { + const cacheHit = await this.cache.get(args.walletAddressId) + + if (cacheHit) { + //* TODO: reset ttl + return cacheHit + } + if (args.userId && args.accountId) { await this.accountService.findAccountById(args.accountId, args.userId) } @@ -170,6 +186,10 @@ export class WalletAddressService implements IWalletAddressService { throw new NotFound() } + await this.cache.set(walletAddress.id, walletAddress, { + expiry: 60 + }) + return walletAddress } @@ -236,6 +256,16 @@ export class WalletAddressService implements IWalletAddressService { publicName }) ]) + + await this.cache.delete(walletAddressId) + const updatedWalletAddress = await walletAddress + .$query(trx) + .findById(walletAddressId) + updatedWalletAddress && + (await this.cache.set(walletAddressId, updatedWalletAddress, { + expiry: 60 + })) + await trx.commit() } catch (e) { await trx.rollback() @@ -257,6 +287,12 @@ export class WalletAddressService implements IWalletAddressService { } async findByIdWithoutValidation(id: string) { + const cacheHit = await this.cache.get(id) + if (cacheHit) { + //* TODO: reset ttl + return cacheHit + } + const walletAddress = await WalletAddress.query() .findById(id) .where('active', true) @@ -265,6 +301,10 @@ export class WalletAddressService implements IWalletAddressService { throw new NotFound() } + await this.cache.set(walletAddress.id, walletAddress, { + expiry: 60 + }) + return walletAddress } diff --git a/packages/wallet/backend/tests/walletAddress/service.test.ts b/packages/wallet/backend/tests/walletAddress/service.test.ts index be8af0cde..f5e5a0602 100644 --- a/packages/wallet/backend/tests/walletAddress/service.test.ts +++ b/packages/wallet/backend/tests/walletAddress/service.test.ts @@ -73,6 +73,11 @@ describe('Wallet Address Service', () => { accountService, env: serviceEnv, logger, + cache: { + get: jest.fn(), + set: jest.fn(), + delete: jest.fn() + }, rafikiClient: { createRafikiWalletAddress: () => ({ id: faker.string.uuid(), From 8b1f95f6f3377116371f12333650a8186cc58b10 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 17:37:43 +0300 Subject: [PATCH 47/58] Fix balance inconsistency on AccountCard --- .../src/components/cards/AccountCard.tsx | 13 ++++-- .../src/pages/account/[accountId].tsx | 9 ++-- packages/wallet/frontend/src/pages/index.tsx | 44 +++++++++++++++---- packages/wallet/frontend/src/utils/helpers.ts | 16 +++++++ 4 files changed, 68 insertions(+), 14 deletions(-) diff --git a/packages/wallet/frontend/src/components/cards/AccountCard.tsx b/packages/wallet/frontend/src/components/cards/AccountCard.tsx index d70f5bbbc..da69bec64 100644 --- a/packages/wallet/frontend/src/components/cards/AccountCard.tsx +++ b/packages/wallet/frontend/src/components/cards/AccountCard.tsx @@ -9,9 +9,14 @@ import { useSnapshot } from 'valtio' type AccountCardProps = { account: Account idOnboarding?: string + incomingOutgoingBalance: number } -export const AccountCard = ({ account, idOnboarding }: AccountCardProps) => { +export const AccountCard = ({ + account, + idOnboarding, + incomingOutgoingBalance +}: AccountCardProps) => { const { isUserFirstTime, setRunOnboarding } = useOnboardingContext() const { accountsSnapshot } = useSnapshot(balanceState) @@ -24,7 +29,9 @@ export const AccountCard = ({ account, idOnboarding }: AccountCardProps) => { ? Number(snapshotAccount.balance) : 0 const accountBalance = Number(account.balance) - const value = (snapshotBalance || accountBalance).toString() + const value = ( + (snapshotBalance || accountBalance) + incomingOutgoingBalance + ).toString() return formatAmount({ value, @@ -32,7 +39,7 @@ export const AccountCard = ({ account, idOnboarding }: AccountCardProps) => { assetCode: account.assetCode, assetScale: account.assetScale }) - }, [account, accountsSnapshot]) + }, [account, accountsSnapshot, incomingOutgoingBalance]) return ( { pp.url = replaceWalletAddressProtocol(pp.url) - balance += Number(pp.incomingBalance) - Number(pp.outgoingBalance) }) return { diff --git a/packages/wallet/frontend/src/pages/index.tsx b/packages/wallet/frontend/src/pages/index.tsx index 7568e8c7b..1a8725c19 100644 --- a/packages/wallet/frontend/src/pages/index.tsx +++ b/packages/wallet/frontend/src/pages/index.tsx @@ -16,10 +16,16 @@ import { userService } from '@/lib/api/user' import type { NextPageWithLayout } from '@/lib/types/app' import { useOnboardingContext } from '@/lib/context/onboarding' import { useEffect } from 'react' +import { calculateBalance } from '@/utils/helpers' +import { walletAddressService } from '@/lib/api/walletAddress' type HomeProps = InferGetServerSidePropsType -const HomePage: NextPageWithLayout = ({ accounts, user }) => { +const HomePage: NextPageWithLayout = ({ + accounts, + incomingOutgoingBalances, + user +}) => { const { isUserFirstTime, setRunOnboarding, stepIndex, setStepIndex } = useOnboardingContext() @@ -107,6 +113,9 @@ const HomePage: NextPageWithLayout = ({ accounts, user }) => { ))} @@ -124,28 +133,47 @@ const HomePage: NextPageWithLayout = ({ accounts, user }) => { export const getServerSideProps: GetServerSideProps<{ accounts: Account[] + incomingOutgoingBalances: Record user: { firstName: string lastName: string email: string } }> = async (ctx) => { - const response = await accountService.list(ctx.req.headers.cookie) - const user = await userService.me(ctx.req.headers.cookie) + const accountsResponse = await accountService.list(ctx.req.headers.cookie) + const userResponse = await userService.me(ctx.req.headers.cookie) - if (!response.success || !user.success) { + if ( + !accountsResponse.success || + !userResponse.success || + !accountsResponse.result + ) { return { notFound: true } } + const incomingOutgoingBalances: Record = {} + for (const account of accountsResponse.result) { + const walletAddressesResponse = await walletAddressService.list( + account.id, + ctx.req.headers.cookie + ) + if (walletAddressesResponse.success && walletAddressesResponse.result) { + incomingOutgoingBalances[account.id] = calculateBalance( + walletAddressesResponse.result + ) + } + } + return { props: { - accounts: response.result ?? [], + accounts: accountsResponse.result ?? [], + incomingOutgoingBalances, user: { - firstName: user.result?.firstName ?? '', - lastName: user.result?.lastName ?? '', - email: user.result?.email ?? '' + firstName: userResponse.result?.firstName ?? '', + lastName: userResponse.result?.lastName ?? '', + email: userResponse.result?.email ?? '' } } } diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index 15929b601..1f9416a0d 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -2,6 +2,7 @@ import { cx, CxOptions } from 'class-variance-authority' import { twMerge } from 'tailwind-merge' import { AssetOP } from '@wallet/shared' import { QuoteResponse } from '@wallet/shared' +import { WalletAddressResponse } from '@wallet/shared' /** * `getObjectKeys` should be used only when we have additional knowledge. @@ -141,3 +142,18 @@ export const replaceWalletAddressProtocol = ( ? paymentPointer.replace('http://', '$') : paymentPointer } + +export const calculateBalance = ( + walletAddresses?: WalletAddressResponse[] +): number => { + if (!walletAddresses || !Array.isArray(walletAddresses)) { + return 0 + } + + return walletAddresses.reduce((acc, pp) => { + const incoming = Number(pp.incomingBalance) || 0 + const outgoing = Number(pp.outgoingBalance) || 0 + console.log('Incoming - outgoing: ', acc + incoming - outgoing) + return acc + (incoming - outgoing) + }, 0) +} From 1f81cc69593d8cc7d3661a6b5f90eb46d461a34b Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 18:00:49 +0300 Subject: [PATCH 48/58] Fix inconsistency in send and request screens, show scale 9 --- packages/wallet/frontend/src/pages/index.tsx | 4 +-- .../frontend/src/pages/transfer/request.tsx | 33 ++++++++++++++----- .../frontend/src/pages/transfer/send.tsx | 33 ++++++++++++++----- 3 files changed, 49 insertions(+), 21 deletions(-) diff --git a/packages/wallet/frontend/src/pages/index.tsx b/packages/wallet/frontend/src/pages/index.tsx index 1a8725c19..ee98a3fcb 100644 --- a/packages/wallet/frontend/src/pages/index.tsx +++ b/packages/wallet/frontend/src/pages/index.tsx @@ -113,9 +113,7 @@ const HomePage: NextPageWithLayout = ({ ))} diff --git a/packages/wallet/frontend/src/pages/transfer/request.tsx b/packages/wallet/frontend/src/pages/transfer/request.tsx index 8f24aa390..2bf33f1ae 100644 --- a/packages/wallet/frontend/src/pages/transfer/request.tsx +++ b/packages/wallet/frontend/src/pages/transfer/request.tsx @@ -11,6 +11,7 @@ import { useDialog } from '@/lib/hooks/useDialog' import { TimeUnit, requestSchema, transfersService } from '@/lib/api/transfers' import { SuccessDialog } from '@/components/dialogs/SuccessDialog' import { + calculateBalance, formatAmount, getObjectKeys, replaceWalletAddressProtocol @@ -44,7 +45,10 @@ const timeUnitOptions: SelectTimeUnitOption[] = [ type RequestProps = InferGetServerSidePropsType -const RequestPage: NextPageWithLayout = ({ accounts }) => { +const RequestPage: NextPageWithLayout = ({ + accounts, + incomingOutgoingBalances +}) => { const [openDialog, closeDialog] = useDialog() const { isUserFirstTime, setRunOnboarding, stepIndex, setStepIndex } = useOnboardingContext() @@ -73,15 +77,17 @@ const RequestPage: NextPageWithLayout = ({ accounts }) => { : 0 const accountBalance = Number(selectedAccount.balance) - const value = (snapshotBalance || accountBalance).toString() + const value = ( + (snapshotBalance || accountBalance) + + incomingOutgoingBalances[selectedAccount.value] + ).toString() return formatAmount({ value, - displayScale: 2, assetCode: selectedAccount.assetCode, assetScale: selectedAccount.assetScale }).amount - }, [accountsSnapshot, selectedAccount]) + }, [accountsSnapshot, selectedAccount, incomingOutgoingBalances]) useEffect(() => { if (isUserFirstTime) { @@ -323,20 +329,28 @@ type SelectAccountOption = SelectOption & } export const getServerSideProps: GetServerSideProps<{ accounts: SelectAccountOption[] + incomingOutgoingBalances: Record }> = async (ctx) => { const [accountsResponse] = await Promise.all([ accountService.list(ctx.req.headers.cookie) ]) - if (!accountsResponse.success) { + if (!accountsResponse.success || !accountsResponse.result) { return { notFound: true } } - if (!accountsResponse.result) { - return { - notFound: true + const incomingOutgoingBalances: Record = {} + for (const account of accountsResponse.result) { + const walletAddressesResponse = await walletAddressService.list( + account.id, + ctx.req.headers.cookie + ) + if (walletAddressesResponse.success && walletAddressesResponse.result) { + incomingOutgoingBalances[account.id] = calculateBalance( + walletAddressesResponse.result + ) } } @@ -350,7 +364,8 @@ export const getServerSideProps: GetServerSideProps<{ return { props: { - accounts + accounts, + incomingOutgoingBalances } } } diff --git a/packages/wallet/frontend/src/pages/transfer/send.tsx b/packages/wallet/frontend/src/pages/transfer/send.tsx index f45022987..cf0867afb 100644 --- a/packages/wallet/frontend/src/pages/transfer/send.tsx +++ b/packages/wallet/frontend/src/pages/transfer/send.tsx @@ -14,6 +14,7 @@ import { accountService } from '@/lib/api/account' import { sendSchema, transfersService } from '@/lib/api/transfers' import { SuccessDialog } from '@/components/dialogs/SuccessDialog' import { + calculateBalance, formatAmount, getObjectKeys, replaceWalletAddressProtocol @@ -39,7 +40,10 @@ import { AssetOP } from '@wallet/shared' type SendProps = InferGetServerSidePropsType -const SendPage: NextPageWithLayout = ({ accounts }) => { +const SendPage: NextPageWithLayout = ({ + accounts, + incomingOutgoingBalances +}) => { const [openDialog, closeDialog] = useDialog() const { isUserFirstTime, setRunOnboarding, stepIndex, setStepIndex } = useOnboardingContext() @@ -71,15 +75,17 @@ const SendPage: NextPageWithLayout = ({ accounts }) => { ? Number(snapshotAccount.balance) : 0 const accountBalance = Number(selectedAccount.balance) - const value = (snapshotBalance || accountBalance).toString() + const value = ( + (snapshotBalance || accountBalance) + + incomingOutgoingBalances[selectedAccount.value] + ).toString() return formatAmount({ value, - displayScale: 2, assetCode: selectedAccount.assetCode, assetScale: selectedAccount.assetScale }).amount - }, [accountsSnapshot, selectedAccount]) + }, [accountsSnapshot, selectedAccount, incomingOutgoingBalances]) const sendForm = useZodForm({ schema: sendSchema, @@ -488,20 +494,28 @@ type SelectAccountOption = SelectOption & } export const getServerSideProps: GetServerSideProps<{ accounts: SelectAccountOption[] + incomingOutgoingBalances: Record }> = async (ctx) => { const [accountsResponse] = await Promise.all([ accountService.list(ctx.req.headers.cookie) ]) - if (!accountsResponse.success) { + if (!accountsResponse.success || !accountsResponse.result) { return { notFound: true } } - if (!accountsResponse.result) { - return { - notFound: true + const incomingOutgoingBalances: Record = {} + for (const account of accountsResponse.result) { + const walletAddressesResponse = await walletAddressService.list( + account.id, + ctx.req.headers.cookie + ) + if (walletAddressesResponse.success && walletAddressesResponse.result) { + incomingOutgoingBalances[account.id] = calculateBalance( + walletAddressesResponse.result + ) } } @@ -515,7 +529,8 @@ export const getServerSideProps: GetServerSideProps<{ return { props: { - accounts + accounts, + incomingOutgoingBalances } } } From db4de9cc5e498fdb50af7b9f3af0d0d39b1ace8c Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 18:30:46 +0300 Subject: [PATCH 49/58] Remove console log --- packages/wallet/frontend/src/utils/helpers.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index 1f9416a0d..2572e7ec5 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -153,7 +153,6 @@ export const calculateBalance = ( return walletAddresses.reduce((acc, pp) => { const incoming = Number(pp.incomingBalance) || 0 const outgoing = Number(pp.outgoingBalance) || 0 - console.log('Incoming - outgoing: ', acc + incoming - outgoing) return acc + (incoming - outgoing) }, 0) } From df198f3dceaf595c74d412c51b5e4ae58bb240a5 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 19:40:49 +0300 Subject: [PATCH 50/58] Fix amounts sent to Rapyd --- .../wallet/backend/src/walletAddress/service.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index 5dc7494fd..c9e1f7b3c 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -319,7 +319,7 @@ export class WalletAddressService implements IWalletAddressService { } const value = - Number(balance * this.env.RAPYD_THRESHOLD) * + Number(balance) * 10 ** -walletAddress.assetScale const factor = 10 ** this.env.BASE_ASSET_SCALE const amount = Math.floor(value * factor) / factor @@ -427,20 +427,20 @@ export class WalletAddressService implements IWalletAddressService { const tmpWalletAddress = await walletAddress .$query(trx) .updateAndFetchById(walletAddress.id, { - incomingBalance: raw('?? + ?', ['incomingBalance', incoming.sum]), - outgoingBalance: raw('?? + ?', ['outgoingBalance', outgoing.sum]) + incomingBalance: raw('?? + ?', ['incomingBalance', incoming.sum % this.env.RAPYD_THRESHOLD]), + outgoingBalance: raw('?? + ?', ['outgoingBalance', outgoing.sum % this.env.RAPYD_THRESHOLD]) }) const incomingBalance = - tmpWalletAddress.incomingBalance / this.env.RAPYD_THRESHOLD + tmpWalletAddress.incomingBalance const outgoingBalance = - tmpWalletAddress.outgoingBalance / this.env.RAPYD_THRESHOLD + tmpWalletAddress.outgoingBalance this.logger.debug( `Incoming balance: ${incomingBalance}. Outgoing balance: ${outgoingBalance}` ) - if (incomingBalance > 0n) { + if (incomingBalance >= this.env.RAPYD_THRESHOLD) { await this.handleImbalance( { balance: incomingBalance, @@ -451,7 +451,7 @@ export class WalletAddressService implements IWalletAddressService { ) } - if (outgoingBalance > 0n) { + if (outgoingBalance >= this.env.RAPYD_THRESHOLD) { await this.handleImbalance( { balance: outgoingBalance, From 9723429f2cdfc473a73d37d4ca47601fd255482c Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 19:42:21 +0300 Subject: [PATCH 51/58] Prettier --- .../backend/src/walletAddress/service.ts | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index c9e1f7b3c..cf74e5e47 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -318,9 +318,7 @@ export class WalletAddressService implements IWalletAddressService { ) } - const value = - Number(balance) * - 10 ** -walletAddress.assetScale + const value = Number(balance) * 10 ** -walletAddress.assetScale const factor = 10 ** this.env.BASE_ASSET_SCALE const amount = Math.floor(value * factor) / factor @@ -427,14 +425,18 @@ export class WalletAddressService implements IWalletAddressService { const tmpWalletAddress = await walletAddress .$query(trx) .updateAndFetchById(walletAddress.id, { - incomingBalance: raw('?? + ?', ['incomingBalance', incoming.sum % this.env.RAPYD_THRESHOLD]), - outgoingBalance: raw('?? + ?', ['outgoingBalance', outgoing.sum % this.env.RAPYD_THRESHOLD]) + incomingBalance: raw('?? + ?', [ + 'incomingBalance', + incoming.sum % this.env.RAPYD_THRESHOLD + ]), + outgoingBalance: raw('?? + ?', [ + 'outgoingBalance', + outgoing.sum % this.env.RAPYD_THRESHOLD + ]) }) - const incomingBalance = - tmpWalletAddress.incomingBalance - const outgoingBalance = - tmpWalletAddress.outgoingBalance + const incomingBalance = tmpWalletAddress.incomingBalance + const outgoingBalance = tmpWalletAddress.outgoingBalance this.logger.debug( `Incoming balance: ${incomingBalance}. Outgoing balance: ${outgoingBalance}` From 27f32c375f358531c83808a3763a78b4a553c6e5 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 20:28:43 +0300 Subject: [PATCH 52/58] Fix type mismatch --- packages/wallet/backend/src/walletAddress/service.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index cf74e5e47..58e6810ac 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -427,11 +427,11 @@ export class WalletAddressService implements IWalletAddressService { .updateAndFetchById(walletAddress.id, { incomingBalance: raw('?? + ?', [ 'incomingBalance', - incoming.sum % this.env.RAPYD_THRESHOLD + BigInt(incoming.sum) % this.env.RAPYD_THRESHOLD ]), outgoingBalance: raw('?? + ?', [ 'outgoingBalance', - outgoing.sum % this.env.RAPYD_THRESHOLD + BigInt(outgoing.sum) % this.env.RAPYD_THRESHOLD ]) }) From 3925b62c4890ddc0201750f3a91fbe6293fe03ec Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 20:40:46 +0300 Subject: [PATCH 53/58] Replace asset scale hardcoded values with constants --- packages/wallet/backend/src/account/service.ts | 2 +- .../wallet/frontend/src/components/cards/AccountCard.tsx | 3 ++- .../wallet/frontend/src/components/dialogs/QuoteDialog.tsx | 5 +++-- packages/wallet/frontend/src/pages/_app.tsx | 5 +++-- packages/wallet/frontend/src/pages/account/[accountId].tsx | 5 +++-- packages/wallet/frontend/src/pages/account/create.tsx | 3 ++- packages/wallet/frontend/src/pages/exchange.tsx | 3 ++- packages/wallet/frontend/src/utils/constants.ts | 3 +++ packages/wallet/frontend/src/utils/helpers.ts | 7 ++++--- 9 files changed, 23 insertions(+), 13 deletions(-) diff --git a/packages/wallet/backend/src/account/service.ts b/packages/wallet/backend/src/account/service.ts index c66800625..016228667 100644 --- a/packages/wallet/backend/src/account/service.ts +++ b/packages/wallet/backend/src/account/service.ts @@ -309,7 +309,7 @@ export class AccountService implements IAccountService { name = 'USD Account' ): Promise { const asset = (await this.rafikiClient.listAssets({ first: 100 })).find( - (asset) => asset.code === 'USD' && asset.scale === 9 + (asset) => asset.code === 'USD' && asset.scale === this.env.MAX_ASSET_SCALE ) if (!asset) { return diff --git a/packages/wallet/frontend/src/components/cards/AccountCard.tsx b/packages/wallet/frontend/src/components/cards/AccountCard.tsx index da69bec64..0968573be 100644 --- a/packages/wallet/frontend/src/components/cards/AccountCard.tsx +++ b/packages/wallet/frontend/src/components/cards/AccountCard.tsx @@ -5,6 +5,7 @@ import { useMemo } from 'react' import { useOnboardingContext } from '@/lib/context/onboarding' import { balanceState } from '@/lib/balance' import { useSnapshot } from 'valtio' +import { BASE_ASSET_SCALE } from '@/utils/constants' type AccountCardProps = { account: Account @@ -35,7 +36,7 @@ export const AccountCard = ({ return formatAmount({ value, - displayScale: 2, + displayScale: BASE_ASSET_SCALE, assetCode: account.assetCode, assetScale: account.assetScale }) diff --git a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx index 6302c98b0..9c7e3dc04 100644 --- a/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx +++ b/packages/wallet/frontend/src/components/dialogs/QuoteDialog.tsx @@ -5,6 +5,7 @@ import { Dialog, Transition } from '@headlessui/react' import { Fragment } from 'react' import { PaperPlane } from '../icons/PaperPlane' import { QuoteResponse } from '@wallet/shared' +import { BASE_ASSET_SCALE } from '@/utils/constants' type QuoteDialogProps = { onClose: () => void @@ -26,14 +27,14 @@ export const QuoteDialog = ({ const receiveAmount = formatAmount({ value: quote.receiveAmount.value, - displayScale: 2, + displayScale: BASE_ASSET_SCALE, assetCode: quote.receiveAmount.assetCode, assetScale: quote.receiveAmount.assetScale }) const debitAmount = formatAmount({ value: quote.debitAmount.value, - displayScale: 2, + displayScale: BASE_ASSET_SCALE, assetCode: quote.debitAmount.assetCode, assetScale: quote.debitAmount.assetScale }) diff --git a/packages/wallet/frontend/src/pages/_app.tsx b/packages/wallet/frontend/src/pages/_app.tsx index 2ccb7f8fb..89953c680 100644 --- a/packages/wallet/frontend/src/pages/_app.tsx +++ b/packages/wallet/frontend/src/pages/_app.tsx @@ -11,6 +11,7 @@ import { io, Socket } from 'socket.io-client' import { useEffect } from 'react' import { updateBalance } from '@/lib/balance' import { formatAmount } from '@/utils/helpers' +import { BASE_ASSET_SCALE } from '@/utils/constants' const titilium = Titillium_Web({ subsets: ['latin'], @@ -40,7 +41,7 @@ export default function App({ Component, pageProps }: AppPropsWithLayout) { { formatAmount({ value: amount.value, - displayScale: 2, + displayScale: BASE_ASSET_SCALE, assetCode: amount.assetCode, assetScale: amount.assetScale }).amount @@ -69,7 +70,7 @@ export default function App({ Component, pageProps }: AppPropsWithLayout) { { formatAmount({ value: amount.value, - displayScale: 2, + displayScale: BASE_ASSET_SCALE, assetCode: amount.assetCode, assetScale: amount.assetScale }).amount diff --git a/packages/wallet/frontend/src/pages/account/[accountId].tsx b/packages/wallet/frontend/src/pages/account/[accountId].tsx index 8c02c1874..890e959eb 100644 --- a/packages/wallet/frontend/src/pages/account/[accountId].tsx +++ b/packages/wallet/frontend/src/pages/account/[accountId].tsx @@ -29,6 +29,7 @@ import { useSnapshot } from 'valtio' import { balanceState } from '@/lib/balance' import { PageHeader } from '@/components/PageHeader' import { WalletAddressResponse } from '@wallet/shared' +import { BASE_ASSET_SCALE } from '@/utils/constants' type AccountPageProps = InferGetServerSidePropsType @@ -50,11 +51,11 @@ const AccountPage: NextPageWithLayout = ({ const accountBalance = Number(account.balance) - // `balance` represents incoming amount - outgoing amount in asset scale 9 + // `balance` represents incoming amount - outgoing amount in asset scale MAX_ASSET_SCALE const value = ((snapshotBalance || accountBalance) + balance).toString() const amountScale2 = formatAmount({ value, - displayScale: 2, + displayScale: BASE_ASSET_SCALE, assetCode: account.assetCode, assetScale: account.assetScale }) diff --git a/packages/wallet/frontend/src/pages/account/create.tsx b/packages/wallet/frontend/src/pages/account/create.tsx index 70ab5b88b..9c419eb90 100644 --- a/packages/wallet/frontend/src/pages/account/create.tsx +++ b/packages/wallet/frontend/src/pages/account/create.tsx @@ -19,6 +19,7 @@ import { NextPageWithLayout } from '@/lib/types/app' import { useOnboardingContext } from '@/lib/context/onboarding' import { useEffect } from 'react' import { createAccountSchema } from '@wallet/shared' +import { MAX_ASSET_SCALE } from '@/utils/constants' type CreateAccountProps = InferGetServerSidePropsType const CreateAccountPage: NextPageWithLayout = ({ @@ -138,7 +139,7 @@ export const getServerSideProps: GetServerSideProps<{ } const assets = response.result - ?.filter((asset) => asset.scale <= 9) + ?.filter((asset) => asset.scale <= MAX_ASSET_SCALE) ?.map((asset) => ({ value: asset.id, label: asset.code diff --git a/packages/wallet/frontend/src/pages/exchange.tsx b/packages/wallet/frontend/src/pages/exchange.tsx index 9d0e4df86..ded6d2031 100644 --- a/packages/wallet/frontend/src/pages/exchange.tsx +++ b/packages/wallet/frontend/src/pages/exchange.tsx @@ -26,6 +26,7 @@ import { balanceState } from '@/lib/balance' import { useSnapshot } from 'valtio' import { exchangeAssetSchema } from '@wallet/shared' import { AssetOP } from '@wallet/shared' +import { MAX_ASSET_SCALE } from '@/utils/constants' type ExchangeAssetProps = InferGetServerSidePropsType const ExchangeAssetPage: NextPageWithLayout = ({ @@ -250,7 +251,7 @@ export const getServerSideProps: GetServerSideProps<{ } const assets = assetResponse.result - ?.filter((asset) => asset.scale <= 2) + ?.filter((asset) => asset.scale <= MAX_ASSET_SCALE) ?.map((asset) => ({ value: asset.id, label: asset.code diff --git a/packages/wallet/frontend/src/utils/constants.ts b/packages/wallet/frontend/src/utils/constants.ts index fe5925b95..e4980671a 100644 --- a/packages/wallet/frontend/src/utils/constants.ts +++ b/packages/wallet/frontend/src/utils/constants.ts @@ -25,3 +25,6 @@ export const BASE64_PUBLIC_KEY = // Transaction asset scale 9 imbalance note export const ASSET_SCALE_IMBALANCE = 'Asset scale 9 imbalance' + +export const MAX_ASSET_SCALE = 9; +export const BASE_ASSET_SCALE = 2; diff --git a/packages/wallet/frontend/src/utils/helpers.ts b/packages/wallet/frontend/src/utils/helpers.ts index 2572e7ec5..1a18f6ae2 100644 --- a/packages/wallet/frontend/src/utils/helpers.ts +++ b/packages/wallet/frontend/src/utils/helpers.ts @@ -3,6 +3,7 @@ import { twMerge } from 'tailwind-merge' import { AssetOP } from '@wallet/shared' import { QuoteResponse } from '@wallet/shared' import { WalletAddressResponse } from '@wallet/shared' +import { BASE_ASSET_SCALE, MAX_ASSET_SCALE } from './constants' /** * `getObjectKeys` should be used only when we have additional knowledge. @@ -40,7 +41,7 @@ type FormatAmountArgs = AssetOP & { } export const formatAmount = (args: FormatAmountArgs): FormattedAmount => { - const { value, displayScale = 9, assetCode, assetScale } = args + const { value, displayScale = MAX_ASSET_SCALE, assetCode, assetScale } = args const scaledValue = Number(`${value}e-${assetScale}`) const flooredValue = @@ -85,7 +86,7 @@ export const getFee = (quote: QuoteResponse): FormattedAmount => { return formatAmount({ assetCode: quote.fee.assetCode, assetScale: quote.fee.assetScale, - displayScale: 2, + displayScale: BASE_ASSET_SCALE, value: quote.fee.value }) } @@ -96,7 +97,7 @@ export const getFee = (quote: QuoteResponse): FormattedAmount => { return formatAmount({ assetCode: quote.debitAmount.assetCode, assetScale: quote.debitAmount.assetScale, - displayScale: 2, + displayScale: BASE_ASSET_SCALE, value: fee.toString() }) } From e81c0f578a4ebedfa5a641f7f721c3d422f73658 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 20:41:42 +0300 Subject: [PATCH 54/58] Prettier --- packages/wallet/backend/src/account/service.ts | 3 ++- packages/wallet/frontend/src/utils/constants.ts | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/wallet/backend/src/account/service.ts b/packages/wallet/backend/src/account/service.ts index 016228667..db6eadd3f 100644 --- a/packages/wallet/backend/src/account/service.ts +++ b/packages/wallet/backend/src/account/service.ts @@ -309,7 +309,8 @@ export class AccountService implements IAccountService { name = 'USD Account' ): Promise { const asset = (await this.rafikiClient.listAssets({ first: 100 })).find( - (asset) => asset.code === 'USD' && asset.scale === this.env.MAX_ASSET_SCALE + (asset) => + asset.code === 'USD' && asset.scale === this.env.MAX_ASSET_SCALE ) if (!asset) { return diff --git a/packages/wallet/frontend/src/utils/constants.ts b/packages/wallet/frontend/src/utils/constants.ts index e4980671a..7109e16d8 100644 --- a/packages/wallet/frontend/src/utils/constants.ts +++ b/packages/wallet/frontend/src/utils/constants.ts @@ -26,5 +26,5 @@ export const BASE64_PUBLIC_KEY = // Transaction asset scale 9 imbalance note export const ASSET_SCALE_IMBALANCE = 'Asset scale 9 imbalance' -export const MAX_ASSET_SCALE = 9; -export const BASE_ASSET_SCALE = 2; +export const MAX_ASSET_SCALE = 9 +export const BASE_ASSET_SCALE = 2 From 650a72fd6cf1eb1e4a9eb8f756c8aaa7874220a6 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 22:43:17 +0300 Subject: [PATCH 55/58] Fix balance calculation --- packages/wallet/backend/src/walletAddress/service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index 58e6810ac..c2007fc40 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -366,7 +366,7 @@ export class WalletAddressService implements IWalletAddressService { const updatePart: PartialModelObject = { [updatedField]: raw('?? - ?', [ updatedField, - this.env.RAPYD_THRESHOLD * balance + balance ]) } From 119e4dab16e409f7ac2def4aa174c42100d3608b Mon Sep 17 00:00:00 2001 From: bsanduc Date: Wed, 21 Aug 2024 22:46:11 +0300 Subject: [PATCH 56/58] Prettier --- packages/wallet/backend/src/walletAddress/service.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/wallet/backend/src/walletAddress/service.ts b/packages/wallet/backend/src/walletAddress/service.ts index c2007fc40..d4499bbf2 100644 --- a/packages/wallet/backend/src/walletAddress/service.ts +++ b/packages/wallet/backend/src/walletAddress/service.ts @@ -364,10 +364,7 @@ export class WalletAddressService implements IWalletAddressService { 'incomingBalance' | 'outgoingBalance' > = type === 'OUTGOING' ? 'outgoingBalance' : 'incomingBalance' const updatePart: PartialModelObject = { - [updatedField]: raw('?? - ?', [ - updatedField, - balance - ]) + [updatedField]: raw('?? - ?', [updatedField, balance]) } await Promise.all([ From b78cf2388cc1a0acbad17c71a5569933de7f174c Mon Sep 17 00:00:00 2001 From: Tymmmy <117268143+Tymmmy@users.noreply.github.com> Date: Thu, 22 Aug 2024 10:08:44 +0300 Subject: [PATCH 57/58] Update index.tsx --- .../wallet/frontend/src/pages/grant-interactions/index.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/wallet/frontend/src/pages/grant-interactions/index.tsx b/packages/wallet/frontend/src/pages/grant-interactions/index.tsx index 3087a2874..6bafe84fe 100644 --- a/packages/wallet/frontend/src/pages/grant-interactions/index.tsx +++ b/packages/wallet/frontend/src/pages/grant-interactions/index.tsx @@ -11,6 +11,7 @@ import { useDialog } from '@/lib/hooks/useDialog' import { ErrorDialog } from '@/components/dialogs/ErrorDialog' import { useRouter } from 'next/router' import { GrantResponse } from '@wallet/shared' +import { BASE_ASSET_SCALE } from '@/utils/constants' type GrantInteractionPageProps = InferGetServerSidePropsType< typeof getServerSideProps @@ -181,7 +182,8 @@ export const getServerSideProps: GetServerSideProps<{ access.limits.debitAmount.formattedAmount = formatAmount({ value: access.limits.debitAmount.value ?? 0, assetCode: access.limits.debitAmount.assetCode, - assetScale: access.limits.debitAmount.assetScale + assetScale: access.limits.debitAmount.assetScale, + displayScale: BASE_ASSET_SCALE }).amount } } From 79fd71ae1ce9b12dc4add6f04131f6833276b2f2 Mon Sep 17 00:00:00 2001 From: bsanduc Date: Thu, 22 Aug 2024 10:27:11 +0300 Subject: [PATCH 58/58] Revert onboarding to EUR --- README.md | 2 +- packages/wallet/backend/src/rapyd/rapyd-client.ts | 2 +- packages/wallet/backend/tests/incomingPayment/service.test.ts | 2 +- packages/wallet/backend/tests/mocks.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4395ac6f5..8b621d190 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ The `RAPYD_ACCESS_KEY` and `RAPYD_SECRET_KEY` variables values can be found in y To create a new Interledger Test Wallet account, a verification email will be sent to the provided email address. If you want to send emails within the development environment, you will need to have a personal Sendgrid account and update the following environment variables: `SEND_EMAIL` to `true`, `SENDGRID_API_KEY` and `FROM_EMAIL`. If you prefer not to send emails in the development environment, simply set `SEND_EMAIL` to `false` and use the verification link found in the Docker `wallet-backend` container logs to finalize the registration process for a new user. Cross-currency transactions are supported. To enable this functionality, you will need to register at [freecurrencyapi.com/](https://freecurrencyapi.com/) and update the `RATE_API_KEY` environment variable with your own API key. -Currencies can be added in the `admin` environment. For example `assetCode` is `USD`, `assetScale` is `2`, and you will need to add an amount to `liquidity`. +Currencies can be added in the `admin` environment. For example `assetCode` is `EUR`, `assetScale` is `9`, and you will need to add an amount to `liquidity`. To have everything ready for `DEV` environment, we already set up some default values for Interledger Test Wallet, this way developers are ready to login without validation, and test e-commerce application without any additional setup: diff --git a/packages/wallet/backend/src/rapyd/rapyd-client.ts b/packages/wallet/backend/src/rapyd/rapyd-client.ts index e223bd708..89feb8904 100644 --- a/packages/wallet/backend/src/rapyd/rapyd-client.ts +++ b/packages/wallet/backend/src/rapyd/rapyd-client.ts @@ -289,7 +289,7 @@ export class RapydClient implements IRapydClient { : ',' const [street, city, postCode] = args.user.address?.split(', ') ?? [] let address = [street, postCode].join(addressDelimiter) - if (args.assetCode === 'USD') address = address.replace(/[,\s]+/g, '') + if (args.assetCode === 'EUR') address = address.replace(/[,\s]+/g, '') // withdraw funds/create payout from wallet account into bank account const userDetails: RequiredFieldsType = { diff --git a/packages/wallet/backend/tests/incomingPayment/service.test.ts b/packages/wallet/backend/tests/incomingPayment/service.test.ts index 673047fc6..76b8dd343 100644 --- a/packages/wallet/backend/tests/incomingPayment/service.test.ts +++ b/packages/wallet/backend/tests/incomingPayment/service.test.ts @@ -168,7 +168,7 @@ describe('Incoming Payment Service', () => { faker.internet.url() ) expect(receivedAmount).toMatchObject({ - assetCode: 'USD', + assetCode: 'EUR', assetScale: 1, value: '0' }) diff --git a/packages/wallet/backend/tests/mocks.ts b/packages/wallet/backend/tests/mocks.ts index bfc3f5450..d54212fea 100644 --- a/packages/wallet/backend/tests/mocks.ts +++ b/packages/wallet/backend/tests/mocks.ts @@ -526,6 +526,6 @@ export const mockWalletAddress = { } export const mockExternalPayment = { - receivedAmount: { value: '0', assetCode: 'USD', assetScale: 1 }, + receivedAmount: { value: '0', assetCode: 'EUR', assetScale: 1 }, authServer: 'http://rafiki-auth:3006' }