Skip to content

Commit

Permalink
Move tagTracker to https
Browse files Browse the repository at this point in the history
  • Loading branch information
Boldizsar Mezei committed Dec 12, 2023
1 parent 11e7d43 commit 2781ff4
Show file tree
Hide file tree
Showing 6 changed files with 94 additions and 97 deletions.
17 changes: 7 additions & 10 deletions packages/client/src/https/datasets/TransactionDataset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
TransactionType,
WEN_FUNC,
} from '@build-5/interfaces';
import { toQueryParams, wrappedFetch } from '../fetch.utils';
import { toQueryParams } from '../fetch.utils';
import { fetchLive } from '../get/observable';
import { DatasetClass } from './Dataset';

Expand Down Expand Up @@ -156,17 +156,14 @@ export class TransactionDataset<D extends Dataset> extends DatasetClass<D, Trans
return fetchLive<Transaction[]>(this.apiKey, url);
};

getBySourceTransaction = async (sourceTransaction: string) => {
getBySourceTransactionLive = (sourceTransaction: string) => {
const params: GetManyAdvancedRequest = {
dataset: this.dataset,
fieldName: ['payload.sourceTransaction'],
fieldValue: [sourceTransaction],
operator: [Opr.ARRAY_CONTAINS],
fieldName: ['payload.sourceTransaction', 'payload.walletReference.confirmed'],
fieldValue: [sourceTransaction, true],
operator: [Opr.ARRAY_CONTAINS, Opr.EQUAL],
};
return await wrappedFetch<Transaction[]>(
this.apiKey,
this.origin + ApiRoutes.GET_MANY_ADVANCED,
{ ...params },
);
const url = this.origin + ApiRoutes.GET_MANY_ADVANCED + toQueryParams({ ...params });
return fetchLive<Transaction[]>(this.apiKey, url);
};
}
3 changes: 3 additions & 0 deletions packages/client/src/https/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { AirdropDataset } from './datasets/token/AirdropDataset';
import { TokenDataset } from './datasets/token/TokenDataset';
import { TokenMarketDataset } from './datasets/token/TokenMarketDataset';
import { TokenPurchaseDataset } from './datasets/token/TokenPurchaseDataset';
import { Observable } from './tag.tracker';

export class ProjectWrapper {
constructor(
Expand Down Expand Up @@ -84,6 +85,8 @@ export class ProjectWrapper {
}
}

trackByTag = (tag: string) => new Observable(this.origin, tag);

uploadFile = async (pathToFile: string, member: string, uid: string) => {
const isLocal = !Object.values(Build5).includes(this.origin);
const url = this.origin + `/${isLocal ? 'https-' : ''}` + WEN_FUNC.uploadFile;
Expand Down
78 changes: 78 additions & 0 deletions packages/client/src/https/tag.tracker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { Dataset, TangleResponse, Transaction, TransactionType } from '@build-5/interfaces';
import { Observable as RxjsObservable, Subscriber, Subscription } from 'rxjs';
import { API_KEY, Build5, https } from '../https';
import { TransactionDataset } from '../https/datasets/TransactionDataset';

export interface TagTrackResult extends TangleResponse {
chainReference?: string;
}

export class Observable extends RxjsObservable<TagTrackResult> {
private observer: Subscriber<TagTrackResult> | undefined;
private dataset: TransactionDataset<Dataset.TRANSACTION> | undefined;
private transactionIds: string[] = [];
private subs: { [key: string]: Subscription } = {};

constructor(origin: Build5, tag: string) {
super((observer) => {
this.observer = observer;

this.dataset = https(origin).project(API_KEY[origin]).dataset(Dataset.TRANSACTION);
this.observer.next({ status: 'waiting for payment' });

this.subs['payment'] = this.dataset
.getPaymentByTagLive(tag.startsWith('0x') ? tag : toHex(tag))
.subscribe(async (payments) => {
payments.sort((a, b) => a.createdOn?.seconds! - b.createdOn?.seconds!);
for (const payment of payments) {
if (!this.transactionIds.includes(payment.uid)) {
this.transactionIds.push(payment.uid);
this.observer?.next({
status: 'payment received',
chainReference: payment.payload.chainReference || '',
});
this.getResponseForPayment(payment);
}
}
});

return this.closeConnection;
});
}

private getResponseForPayment = (payment: Transaction) => {
const obs = this.dataset!.getBySourceTransactionLive(payment.uid);
this.subs[payment.uid] = obs.subscribe((transactions) => {
for (const tran of transactions) {
if (!this.transactionIds.includes(tran.uid)) {
this.transactionIds.push(tran.uid);

if (tran.type === TransactionType.CREDIT_TANGLE_REQUEST) {
this.observer?.next({
...tran.payload.response,
chainReference: tran.payload.walletReference?.chainReference || '',
});
return;
}

if (tran.type === TransactionType.UNLOCK) {
this.observer?.next({ status: 'Success' });
return;
}
}
}
});
};

private closeConnection = () => {
Object.values(this.subs).forEach((subs) => subs.unsubscribe());
this.observer?.complete();
};
}

const toHex = (stringToConvert: string) =>
'0x' +
stringToConvert
.split('')
.map((c) => c.charCodeAt(0).toString(16).padStart(2, '0'))
.join('');
11 changes: 2 additions & 9 deletions packages/client/src/otr/datasets/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export class OtrRequest<T> {
walletType +
`://wallet/sendConfirmation?address=${this.otrAddress}` +
'&disableToggleGift=true&disableChangeExpiration=true' +
`&amount=${nativeToken ? nativeToken.amount : this.amount}` +
`&amount=${nativeToken ? nativeToken.amount : this.amount || 0}` +
`&tag=${tag}&giftStorageDeposit=true` +
`&metadata=${JSON.stringify(metadata)}` +
(nativeToken ? `&assetId=${nativeToken?.id}` : '')
Expand All @@ -58,7 +58,7 @@ export class OtrRequest<T> {
const { metadata, nativeToken, tag, amount } = this.getMetadata();
const parameters = {
address: this.otrAddress,
baseCoinAmount: Number(amount).toFixed(0),
baseCoinAmount: Number(amount || 0).toFixed(0),
tokenId: nativeToken?.id,
tokenAmount: nativeToken ? Number(nativeToken.amount).toFixed(0) : undefined,
tag,
Expand Down Expand Up @@ -100,13 +100,6 @@ const getFireflyWalletType = (otrAddress: string) => {
throw Error('Invalid otr address, ono firefly wallet type found');
};

export const toHex = (stringToConvert: string) =>
'0x' +
stringToConvert
.split('')
.map((c) => c.charCodeAt(0).toString(16).padStart(2, '0'))
.join('');

export const otrAddressToNetwork = (address: string): Network => {
for (const network of Object.values(Network)) {
if (address.startsWith(network)) {
Expand Down
79 changes: 2 additions & 77 deletions packages/client/src/otr/otr.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
import {
Dataset,
Network,
TangleResponse,
Transaction,
TransactionType,
} from '@build-5/interfaces';
import { Observable as RxjsObservable, Subscriber, Subscription } from 'rxjs';
import { API_KEY, Build5, https } from '../https';
import { TransactionDataset } from '../https/datasets/TransactionDataset';
import { Dataset } from '@build-5/interfaces';
import { AuctionOtrDataset } from './datasets/AuctionOtrDataset';
import { AwardOtrDataset } from './datasets/AwardOtrDataset';
import { MemberOtrDataset } from './datasets/MemberOtrDataset';
import { NftOtrDataset } from './datasets/NftOtrDataset';
import { ProposalOtrDataset } from './datasets/ProposalOtrDataset';
import { SpaceOtrDataset } from './datasets/SpaceOtrDataset';
import { TokenOtrDataset } from './datasets/TokenOtrDataset';
import { DatasetType, toHex } from './datasets/common';
import { DatasetType } from './datasets/common';

export class OtrWrapper {
constructor(private readonly otrAddress: string) {}
Expand All @@ -40,70 +31,4 @@ export class OtrWrapper {
throw Error('invalid dataset name');
}
}

trackByTag = (tag: string) => {
const origin = this.otrAddress.startsWith(Network.RMS) ? Build5.TEST : Build5.PROD;
return new Observable(origin, tag);
};
}

interface TagTrackResult extends TangleResponse {
chainReference?: string;
}

class Observable extends RxjsObservable<TagTrackResult> {
private observer: Subscriber<TagTrackResult> | undefined;
private paymentsSubs: Subscription | undefined;
private payments: string[] = [];
private dataset: TransactionDataset<Dataset.TRANSACTION> | undefined;

constructor(origin: Build5, tag: string) {
super((observer) => {
this.observer = observer;

this.dataset = https(origin).project(API_KEY[origin]).dataset(Dataset.TRANSACTION);
this.observer.next({ status: 'waiting for payment' });

this.paymentsSubs = this.dataset
.getPaymentByTagLive(tag.startsWith('0x') ? tag : toHex(tag))
.subscribe(async (payments) => {
payments.sort((a, b) => a.createdOn?.seconds! - b.createdOn?.seconds!);
for (const payment of payments) {
await this.getResponseForPayment(payment);
}
});

return this.closeConnection;
});
}

private getResponseForPayment = async (payment: Transaction) => {
if (this.payments.includes(payment.uid)) {
return;
}
this.payments.push(payment.uid);

for (let i = 0; i < 10; ++i) {
const result = await this.dataset!.getBySourceTransaction(payment.uid);
const credit = result.find((t) => t.type === TransactionType.CREDIT_TANGLE_REQUEST);
if (credit) {
this.observer?.next({
...credit.payload.response,
chainReference: credit.payload.chainReference || '',
});
return;
}
const transfer = result.find((t) => t.type === TransactionType.UNLOCK);
if (transfer) {
this.observer?.next({ status: 'Success' });
return;
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
};

private closeConnection = () => {
this.paymentsSubs?.unsubscribe();
this.observer?.complete();
};
}
3 changes: 2 additions & 1 deletion packages/client/test/otr/otr.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Dataset } from '@build-5/interfaces';
import * as build5 from '../../src';
import { API_KEY, Build5 } from '../../src/https';
import { Build5OtrAddress } from '../../src/otr';

describe('', () => {
Expand All @@ -14,7 +15,7 @@ describe('', () => {
const tag = request.getTag(deeplink);
console.log(tag);

const obs = build5.otr(otrAddress).trackByTag(tag);
const obs = build5.https(Build5.TEST).project(API_KEY[Build5.TEST]).trackByTag(tag);
const subs = obs.subscribe((n) => console.log(n));

await new Promise((resolve) => setTimeout(resolve, 200000));
Expand Down

0 comments on commit 2781ff4

Please sign in to comment.