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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions migration/1779096542464-AddSupportNode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* @typedef {import('typeorm').MigrationInterface} MigrationInterface
* @typedef {import('typeorm').QueryRunner} QueryRunner
*/

/**
* @class
* @implements {MigrationInterface}
*/
module.exports = class AddSupportNode1779096542464 {
name = 'AddSupportNode1779096542464';

/**
* @param {QueryRunner} queryRunner
*/
async up(queryRunner) {
await queryRunner.query(
`CREATE TABLE "support_note" ("id" int NOT NULL IDENTITY(1,1), "updated" datetime2 NOT NULL CONSTRAINT "DF_0808df6f9b73cd053eabaa41038" DEFAULT getdate(), "created" datetime2 NOT NULL CONSTRAINT "DF_44fc0bddcb58532cdb9218636fd" DEFAULT getdate(), "userDataId" int, "department" nvarchar(256) NOT NULL, "authorId" int NOT NULL, "authorMail" nvarchar(256) NOT NULL, "subject" nvarchar(256), "content" nvarchar(MAX) NOT NULL, CONSTRAINT "PK_50d71a126818b986dfd11f3cc4c" PRIMARY KEY ("id"))`,
);
await queryRunner.query(`CREATE INDEX "IDX_1824182fbb53ca85959eedda54" ON "support_note" ("userDataId") `);
await queryRunner.query(
`ALTER TABLE "support_note" ADD CONSTRAINT "FK_1824182fbb53ca85959eedda54d" FOREIGN KEY ("userDataId") REFERENCES "user_data"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}

/**
* @param {QueryRunner} queryRunner
*/
async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "support_note" DROP CONSTRAINT "FK_1824182fbb53ca85959eedda54d"`);
await queryRunner.query(`DROP INDEX "IDX_1824182fbb53ca85959eedda54" ON "support_note"`);
await queryRunner.query(`DROP TABLE "support_note"`);
}
};
51 changes: 46 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@
"reflect-metadata": "^0.1.14",
"rimraf": "^4.4.1",
"rxjs": "^7.8.2",
"sanitize-html": "^2.17.0",
"sanitize-html": "^2.17.4",
"secp256k1": "^5.0.1",
"swagger-ui-express": "^4.6.3",
"swissqrbill": "^4.2.0",
Expand Down
26 changes: 7 additions & 19 deletions src/integration/blockchain/shared/evm/evm-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,25 +184,13 @@ export abstract class EvmClient extends BlockchainClient {
protected async getTokenGasLimitForAsset(token: Asset): Promise<EthersNumber> {
const contract = this.getERC20ContractForDex(token.chainId);

return this.getTokenGasLimitForContact(contract, this.randomReceiverAddress);
}

async getTokenGasLimitForContact(contract: Contract, to: string, amount?: EthersNumber): Promise<EthersNumber> {
// Use actual amount if provided, otherwise use 1 for gas estimation
// Some tokens may have minimum transfer amounts or balance checks that fail with 1 Wei
const estimateAmount = amount ?? 1;

try {
const gasEstimate = await contract.estimateGas.transfer(to, estimateAmount);
return gasEstimate.mul(12).div(10);
} catch (error) {
// If gas estimation fails (e.g., from EIP-7702 delegated address), use a safe default
// Standard ERC20 transfer is ~65k gas, using 100k as safe upper bound with buffer
this.logger.verbose(
`Gas estimation failed for token transfer to ${to}: ${error.message}. Using default gas limit of 100000`,
);
return ethers.BigNumber.from(100000);
}
// Sample amount of 1 wei for fee estimation only (no concrete TX context here)
return this.getTokenGasLimitForContact(contract, this.randomReceiverAddress, ethers.BigNumber.from(1));
}

async getTokenGasLimitForContact(contract: Contract, to: string, amount: EthersNumber): Promise<EthersNumber> {
const gasEstimate = await contract.estimateGas.transfer(to, amount);
return gasEstimate.mul(12).div(10);
}

async prepareTransaction(
Expand Down
39 changes: 39 additions & 0 deletions src/shared/utils/__tests__/bitbox-ascii.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { toBitboxAscii } from '../bitbox-ascii.util';

describe('toBitboxAscii', () => {
it('returns ASCII input unchanged', () => {
expect(toBitboxAscii('Joshua Krueger')).toBe('Joshua Krueger');
expect(toBitboxAscii('')).toBe('');
expect(toBitboxAscii('123 Main St')).toBe('123 Main St');
});

it('expands German umlauts with digraph romanization', () => {
expect(toBitboxAscii('Krüger')).toBe('Krueger');
expect(toBitboxAscii('Müller')).toBe('Mueller');
expect(toBitboxAscii('Über')).toBe('Ueber');
expect(toBitboxAscii('Größe')).toBe('Groesse');
expect(toBitboxAscii('STRAẞE')).toBe('STRASSE');
});

it('expands Nordic æ/ø to digraphs', () => {
expect(toBitboxAscii('Æsir')).toBe('Aesir');
expect(toBitboxAscii('Mørk')).toBe('Moerk');
expect(toBitboxAscii('Þór')).toBe('Thor');
});

it('strips accents from Latin-script letters', () => {
expect(toBitboxAscii('Garção')).toBe('Garcao');
expect(toBitboxAscii('Łódź')).toBe('Lodz');
expect(toBitboxAscii('Naïve')).toBe('Naive');
expect(toBitboxAscii('Ångström')).toBe('Angstroem');
});

it('replaces unmapped non-ASCII runes with ?', () => {
expect(toBitboxAscii('hello 你好')).toBe('hello ??');
expect(toBitboxAscii('emoji 🙂')).toMatch(/^emoji \?+$/);
});

it('treats name from production incident as expected', () => {
expect(toBitboxAscii('Joshua Krüger')).toBe('Joshua Krueger');
});
});
79 changes: 79 additions & 0 deletions src/shared/utils/bitbox-ascii.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Transliteration that mirrors realunit-app's `toBitboxSafeAscii` (Dart).
// Used to reconcile EIP-712 string fields that the BitBox firmware accepts
// (printable ASCII only) with the UTF-8 originals stored on the user_data
// row. Distinct from the npm `transliteration` package — that one maps
// `ü` to `u` (single char) while the BitBox-safe convention follows the
// German romanization (`ü` → `ue`, `ß` → `ss`).
//
// Same chained-replace idiom as `Util.removeSpecialChars`. Digraph rules
// must run before the single-char fallback, and the final catch-all
// replaces any leftover non-ASCII with `?` so the BitBox firmware never
// sees a non-printable byte.

export function toBitboxAscii(value: string): string {
if (/^[\x20-\x7E]*$/.test(value)) return value;

return (
value
// Digraph romanizations — must come before single-char fallbacks
.replace(/ä/g, 'ae')
.replace(/ö/g, 'oe')
.replace(/ü/g, 'ue')
.replace(/ß/g, 'ss')
.replace(/Ä/g, 'Ae')
.replace(/Ö/g, 'Oe')
.replace(/Ü/g, 'Ue')
.replace(/ẞ/g, 'SS')
.replace(/æ/g, 'ae')
.replace(/Æ/g, 'Ae')
.replace(/œ/g, 'oe')
.replace(/Œ/g, 'Oe')
.replace(/ø/g, 'oe')
.replace(/Ø/g, 'Oe')
.replace(/þ/g, 'th')
.replace(/Þ/g, 'Th')
.replace(/ð/g, 'd')
.replace(/Ð/g, 'D')
// Single-char base-letter equivalents
.replace(/[àáâãåāăą]/g, 'a')
.replace(/[ÀÁÂÃÅĀĂĄ]/g, 'A')
.replace(/[çćčĉċ]/g, 'c')
.replace(/[ÇĆČĈĊ]/g, 'C')
.replace(/[ďđ]/g, 'd')
.replace(/[ĎĐ]/g, 'D')
.replace(/[èéêëēėęě]/g, 'e')
.replace(/[ÈÉÊËĒĖĘĚ]/g, 'E')
.replace(/[ğġ]/g, 'g')
.replace(/[ĞĠ]/g, 'G')
.replace(/ħ/g, 'h')
.replace(/Ħ/g, 'H')
.replace(/[ìíîïīįı]/g, 'i')
.replace(/[ÌÍÎÏĪĮİ]/g, 'I')
.replace(/ĵ/g, 'j')
.replace(/Ĵ/g, 'J')
.replace(/ķ/g, 'k')
.replace(/Ķ/g, 'K')
.replace(/[łľĺļ]/g, 'l')
.replace(/[ŁĽĹĻ]/g, 'L')
.replace(/[ñńňņ]/g, 'n')
.replace(/[ÑŃŇŅ]/g, 'N')
.replace(/[òóôõōő]/g, 'o')
.replace(/[ÒÓÔÕŌŐ]/g, 'O')
.replace(/[ŕřŗ]/g, 'r')
.replace(/[ŔŘŖ]/g, 'R')
.replace(/[śšşŝș]/g, 's')
.replace(/[ŚŠŞŜȘ]/g, 'S')
.replace(/[ťţțŧ]/g, 't')
.replace(/[ŤŢȚŦ]/g, 'T')
.replace(/[ùúûūůűų]/g, 'u')
.replace(/[ÙÚÛŪŮŰŲ]/g, 'U')
.replace(/ŵ/g, 'w')
.replace(/Ŵ/g, 'W')
.replace(/[ýÿŷ]/g, 'y')
.replace(/[ÝŸŶ]/g, 'Y')
.replace(/[źżž]/g, 'z')
.replace(/[ŹŻŽ]/g, 'Z')
// Any remaining non-ASCII or non-printable rune
.replace(/[^\x20-\x7E]/g, '?')
);
}
17 changes: 17 additions & 0 deletions src/subdomains/core/aml/dto/manual-aml-check.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator';
import { AmlReason } from '../enums/aml-reason.enum';
import { CheckStatus } from '../enums/check-status.enum';

export class ManualAmlCheckDto {
@IsNotEmpty()
@IsEnum(CheckStatus)
amlCheck: CheckStatus;

@IsOptional()
@IsEnum(AmlReason)
amlReason?: AmlReason;

@IsNotEmpty()
@IsString()
responsible: string;
}
21 changes: 21 additions & 0 deletions src/subdomains/core/aml/enums/aml-error.enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,27 @@ export const DelayResultError = [
AmlError.BANK_RELEASE_DATE_MISSING,
];

// Keep in sync with packages/core/src/definitions/compliance.ts (ManualPassWhitelistErrors / canManualPass)
export const ManualPassWhitelistErrors: AmlError[] = [
AmlError.PHONE_VERIFICATION_NEEDED,
AmlError.IP_PHONE_VERIFICATION_NEEDED,
AmlError.BIC_PHONE_VERIFICATION_NEEDED,
AmlError.IBAN_PHONE_VERIFICATION_NEEDED,
AmlError.IP_COUNTRY_MISMATCH,
AmlError.TRADE_APPROVAL_DATE_MISSING,
AmlError.USER_DATA_FAILED_CALL,
AmlError.USER_DATA_REJECTED_CALL,
AmlError.REFERRAL_NO_TRADE_HISTORY,
];

export function canManualPass(comment: string | null | undefined): boolean {
const errors = (comment ?? '')
.split(';')
.map((e) => e.trim())
.filter(Boolean);
return errors.length > 0 && errors.every((e) => ManualPassWhitelistErrors.includes(e as AmlError));
}

export enum AmlErrorType {
SINGLE = 'Single', // Only one error may occur
MULTI = 'Multi', // All errors must have the same amlCheck
Expand Down
8 changes: 8 additions & 0 deletions src/subdomains/core/aml/enums/aml-reason.enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ export const KycAmlReasons = [
AmlReason.KYC_DATA_NEEDED,
];

export const PhoneAmlReasons = [
AmlReason.MANUAL_CHECK_PHONE,
AmlReason.MANUAL_CHECK_PHONE_FAILED,
AmlReason.MANUAL_CHECK_IP_PHONE,
AmlReason.MANUAL_CHECK_IP_COUNTRY_PHONE,
AmlReason.MANUAL_CHECK_EXTERNAL_ACCOUNT_PHONE,
];

export const RecheckAmlReasons = [
AmlReason.MANUAL_CHECK_PHONE,
AmlReason.MANUAL_CHECK_IP_PHONE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { RoleGuard } from 'src/shared/auth/role.guard';
import { UserActiveGuard } from 'src/shared/auth/user-active.guard';
import { UserRole } from 'src/shared/auth/user-role.enum';
import { RefundInternalDto } from '../../history/dto/refund-internal.dto';
import { ManualAmlCheckDto } from '../../aml/dto/manual-aml-check.dto';
import { UpdateBuyCryptoDto } from './dto/update-buy-crypto.dto';
import { BuyCrypto } from './entities/buy-crypto.entity';
import { BuyCryptoWebhookService } from './services/buy-crypto-webhook.service';
Expand Down Expand Up @@ -65,4 +66,12 @@ export class BuyCryptoController {
async resetAmlCheck(@Param('id') id: string): Promise<void> {
return this.buyCryptoService.resetAmlCheck(+id);
}

@Put(':id/amlCheck')
@ApiBearerAuth()
@ApiExcludeEndpoint()
@UseGuards(AuthGuard(), RoleGuard(UserRole.COMPLIANCE), UserActiveGuard())
async manualPassAmlCheck(@Param('id') id: string, @Body() dto: ManualAmlCheckDto): Promise<BuyCrypto> {
return this.buyCryptoService.manualPassAmlCheck(+id, dto);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { createCustomHistory } from 'src/subdomains/core/history/dto/__mocks__/h
import { BuyFiatService } from 'src/subdomains/core/sell-crypto/process/services/buy-fiat.service';
import { TransactionUtilService } from 'src/subdomains/core/transaction/transaction-util.service';
import { BankDataService } from 'src/subdomains/generic/user/models/bank-data/bank-data.service';
import { UserDataService } from 'src/subdomains/generic/user/models/user-data/user-data.service';
import { UserService } from 'src/subdomains/generic/user/models/user/user.service';
import { BankTxService } from 'src/subdomains/supporting/bank-tx/bank-tx/services/bank-tx.service';
import { FiatOutputService } from 'src/subdomains/supporting/fiat-output/fiat-output.service';
Expand Down Expand Up @@ -69,6 +70,7 @@ describe('BuyCryptoService', () => {
let amlService: AmlService;
let transactionHelper: TransactionHelper;
let custodyOrderService: CustodyOrderService;
let userDataService: UserDataService;

beforeEach(async () => {
buyCryptoRepo = createMock<BuyCryptoRepository>();
Expand All @@ -95,6 +97,7 @@ describe('BuyCryptoService', () => {
amlService = createMock<AmlService>();
transactionHelper = createMock<TransactionHelper>();
custodyOrderService = createMock<CustodyOrderService>();
userDataService = createMock<UserDataService>();

const module: TestingModule = await Test.createTestingModule({
imports: [TestSharedModule],
Expand Down Expand Up @@ -124,6 +127,7 @@ describe('BuyCryptoService', () => {
{ provide: AmlService, useValue: amlService },
{ provide: TransactionHelper, useValue: transactionHelper },
{ provide: CustodyOrderService, useValue: custodyOrderService },
{ provide: UserDataService, useValue: userDataService },
],
}).compile();

Expand Down
Loading
Loading