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
27 changes: 27 additions & 0 deletions migration/1772756747747-RefPayoutFrequency.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @typedef {import('typeorm').MigrationInterface} MigrationInterface
* @typedef {import('typeorm').QueryRunner} QueryRunner
*/

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

/**
* @param {QueryRunner} queryRunner
*/
async up(queryRunner) {
await queryRunner.query(`ALTER TABLE "user" ADD "refPayoutFrequency" nvarchar(256) NOT NULL CONSTRAINT "DF_925ad625277b6513eaee6172211" DEFAULT 'Daily'`);
}

/**
* @param {QueryRunner} queryRunner
*/
async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "user" DROP CONSTRAINT "DF_925ad625277b6513eaee6172211"`);
await queryRunner.query(`ALTER TABLE "user" DROP COLUMN "refPayoutFrequency"`);
}
}
7 changes: 7 additions & 0 deletions src/integration/blockchain/shared/evm/evm.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ export class EvmUtil {
return this.blockchainToChainIdMap.get(blockchain);
}

static getBlockchain(chainId: number): Blockchain | undefined {
for (const [blockchain, id] of this.blockchainToChainIdMap.entries()) {
if (id === chainId) return blockchain;
}
return undefined;
}

static createWallet({ seed, index }: WalletAccount, provider?: ethers.providers.JsonRpcProvider): ethers.Wallet {
const wallet = ethers.Wallet.fromMnemonic(seed, this.getPathFor(index));
return provider ? wallet.connect(provider) : wallet;
Expand Down
90 changes: 52 additions & 38 deletions src/integration/blockchain/spark/spark-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,51 +56,66 @@ export class SparkClient extends BlockchainClient {
this.cachedAddress = new AsyncField(() => this.wallet.then((w) => w.getSparkAddress()), true);
}

private async call<T>(operation: (wallet: SparkWallet) => Promise<T>): Promise<T> {
try {
const wallet = await this.wallet;
return await operation(wallet);
} catch (e) {
if (e?.message?.includes('Channel has been shut down')) {
this.logger.info('Spark channel shut down, reinitializing wallet...');
this.wallet.reset();
this.cachedAddress.reset();
const wallet = await this.wallet;
return operation(wallet);
}
throw e;
}
}

get walletAddress(): string {
return this.cachedAddress.value;
}

// --- TRANSACTION METHODS --- //

async sendTransaction(to: string, amount: number): Promise<{ txid: string; fee: number }> {
const wallet = await this.wallet;
return this.call(async (wallet) => {
const amountSats = Math.round(amount * 1e8);

await this.syncLeaves(wallet);
await this.syncLeaves(wallet);

const amountSats = Math.round(amount * 1e8);
const result = await wallet.transfer({
amountSats,
receiverSparkAddress: to,
});

const result = await wallet.transfer({
amountSats,
receiverSparkAddress: to,
return { txid: result.id, fee: 0 };
});

return { txid: result.id, fee: 0 };
}

async getTransaction(txId: string): Promise<SparkTransaction> {
const wallet = await this.wallet;

await this.syncLeaves(wallet);

const transfer = await wallet.getTransfer(txId);

if (!transfer) {
throw new Error(`Transaction ${txId} not found`);
}

// Outgoing: complete once sender key is tweaked (funds left our wallet)
// Incoming: complete once receiver has claimed
const isConfirmed =
transfer.status === 'TRANSFER_STATUS_SENDER_KEY_TWEAKED' || transfer.status === 'TRANSFER_STATUS_COMPLETED';

return {
txid: transfer.id,
blockhash: isConfirmed ? 'confirmed' : undefined,
confirmations: isConfirmed ? 1 : 0,
time: transfer.createdTime ? Math.floor(transfer.createdTime.getTime() / 1000) : undefined,
blocktime: transfer.updatedTime ? Math.floor(transfer.updatedTime.getTime() / 1000) : undefined,
fee: 0,
};
return this.call(async (wallet) => {
await this.syncLeaves(wallet);

const transfer = await wallet.getTransfer(txId);

if (!transfer) {
throw new Error(`Transaction ${txId} not found`);
}

// Outgoing: complete once sender key is tweaked (funds left our wallet)
// Incoming: complete once receiver has claimed
const isConfirmed = ['TRANSFER_STATUS_SENDER_KEY_TWEAKED', 'TRANSFER_STATUS_COMPLETED'].includes(transfer.status);

return {
txid: transfer.id,
blockhash: isConfirmed ? 'confirmed' : undefined,
confirmations: isConfirmed ? 1 : 0,
time: transfer.createdTime ? Math.floor(transfer.createdTime.getTime() / 1000) : undefined,
blocktime: transfer.updatedTime ? Math.floor(transfer.updatedTime.getTime() / 1000) : undefined,
fee: 0,
};
});
}

async getTransfers(limit = 100, offset = 0): Promise<SparkTransfer[]> {
Expand Down Expand Up @@ -192,8 +207,7 @@ export class SparkClient extends BlockchainClient {

async isHealthy(): Promise<boolean> {
try {
const wallet = await this.wallet;
return wallet != null;
return await this.call(async (wallet) => wallet != null);
} catch {
return false;
}
Expand All @@ -202,13 +216,13 @@ export class SparkClient extends BlockchainClient {
// --- BLOCKCHAIN CLIENT INTERFACE --- //

async getNativeCoinBalance(): Promise<number> {
const wallet = await this.wallet;
return this.call(async (wallet) => {
const { balance } = await wallet.getBalance();

await this.syncLeaves(wallet);
await this.syncLeaves(wallet);

const { balance } = await wallet.getBalance();

return Number(balance) / 1e8;
return Number(balance) / 1e8;
});
}

async getNativeCoinBalanceForAddress(_address: string): Promise<number> {
Expand Down
5 changes: 5 additions & 0 deletions src/shared/models/asset/asset.entity.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Blockchain } from 'src/integration/blockchain/shared/enums/blockchain.enum';
import { EvmUtil } from 'src/integration/blockchain/shared/evm/evm.util';
import { AmlRule } from 'src/subdomains/core/aml/enums/aml-rule.enum';
import { LiquidityBalance } from 'src/subdomains/core/liquidity-management/entities/liquidity-balance.entity';
import { LiquidityManagementRule } from 'src/subdomains/core/liquidity-management/entities/liquidity-management-rule.entity';
Expand Down Expand Up @@ -131,6 +132,10 @@ export class Asset extends IEntity {
return this.approxPriceChf ? 1 / this.approxPriceChf : 1;
}

get evmChainId(): number | undefined {
return EvmUtil.getChainId(this.blockchain);
}

isBuyableOn(blockchains: Blockchain[]): boolean {
return blockchains.includes(this.blockchain) || this.type === AssetType.CUSTOM;
}
Expand Down
27 changes: 19 additions & 8 deletions src/shared/models/asset/dto/asset.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsInt, IsNotEmpty, IsString, ValidateIf } from 'class-validator';
import { IsEnum, IsInt, IsNotEmpty, IsOptional, IsString, ValidateIf } from 'class-validator';
import { Blockchain } from 'src/integration/blockchain/shared/enums/blockchain.enum';
import { AssetCategory, AssetType } from '../asset.entity';

Expand Down Expand Up @@ -75,23 +75,34 @@ export class AssetDto {
}

export class AssetInDto {
@ApiPropertyOptional()
@ApiPropertyOptional({ description: 'DFX asset ID. Use either id alone OR blockchain/evmChainId with chainId.' })
@IsNotEmpty()
@ValidateIf((a: AssetInDto) => Boolean(a.id || !(a.chainId || a.blockchain)))
@ValidateIf((a: AssetInDto) => a.id != null || !(a.blockchain || a.evmChainId))
@IsInt()
id?: number;

@ApiPropertyOptional()
@IsNotEmpty()
@ValidateIf((a: AssetInDto) => Boolean(a.chainId || !a.id))
@ApiPropertyOptional({
description: 'On-chain contract address (for tokens). If omitted with blockchain/evmChainId, uses native coin.',
})
@IsOptional()
@IsString()
chainId?: string;

@ApiPropertyOptional()
@ApiPropertyOptional({
description: 'Blockchain name (e.g. Ethereum, Polygon). Use with chainId.',
})
@IsNotEmpty()
@ValidateIf((a: AssetInDto) => Boolean(a.blockchain || !a.id))
@ValidateIf((a: AssetInDto) => a.blockchain != null || (!a.id && !a.evmChainId))
@IsEnum(Blockchain)
blockchain?: Blockchain;

@ApiPropertyOptional({
description: 'Numeric EVM chain ID (e.g. 1 for Ethereum, 137 for Polygon). Alternative to blockchain.',
})
@IsNotEmpty()
@ValidateIf((a: AssetInDto) => a.evmChainId != null || (!a.id && !a.blockchain))
@IsInt()
evmChainId?: number;
}

export class AssetLimitsDto {
Expand Down
17 changes: 16 additions & 1 deletion src/shared/models/fiat/dto/fiat.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsInt, IsNotEmpty, IsString, ValidateIf } from 'class-validator';
import { FiatPaymentMethod } from 'src/subdomains/supporting/payment/dto/payment-method.enum';

export class FiatInDto {
@ApiPropertyOptional({ description: 'Fiat currency ID' })
@IsNotEmpty()
@ValidateIf((f: FiatInDto) => Boolean(f.id || !f.name))
@IsInt()
id?: number;

@ApiPropertyOptional({ description: 'Fiat currency code (e.g. EUR, USD, CHF)' })
@IsNotEmpty()
@ValidateIf((f: FiatInDto) => Boolean(f.name || !f.id))
@IsString()
name?: string;
}

export class FiatDto {
@ApiProperty()
id: number;
Expand Down
Loading
Loading