Skip to content

Commit

Permalink
Merge pull request #2706 from build-5/bugifx/client
Browse files Browse the repository at this point in the history
Client lib fixes
  • Loading branch information
adamunchained authored Dec 12, 2023
2 parents 4ea5827 + 2781ff4 commit fece8cb
Show file tree
Hide file tree
Showing 17 changed files with 215 additions and 451 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/action_deploy-prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ jobs:
- name: Deploy to npm
run: |
npm publish --workspace packages/interfaces
npm publish --workspace packages/client
cd packages/client/lib && npm publish
roll-firestore:
runs-on: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/action_deploy-wen.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ jobs:
- name: Deploy to npm as "upcoming" package
run: |
npm publish --workspace packages/interfaces --tag next
npm publish --workspace packages/client --tag next
cd packages/client/lib && npm publish --tag next
deploy_functions:
runs-on: ubuntu-latest
environment: staging
Expand Down
204 changes: 98 additions & 106 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
"serve": "run-p \"run:search\" \"run:functions\"",
"lint": "eslint --ext .js,.ts src",
"build": "tsc",
"postbuild": "cp package.json ./lib",
"test": "jest"
},
"dependencies": {
"@build-5/interfaces": "*",
"@iota/sdk": "1.1.4",
"axios": "^1.6.2",
"bip39": "3.1.0",
"form-data": "^4.0.0",
Expand Down
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('');
1 change: 0 additions & 1 deletion packages/client/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export { https } from './https';
export { otr } from './otr';
export { createWallet } from './wallet';
37 changes: 21 additions & 16 deletions packages/client/src/otr/datasets/common.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Dataset, MIN_IOTA_AMOUNT, Network } from '@build-5/interfaces';
import { Dataset, Network } from '@build-5/interfaces';
import { v4 as uuid } from 'uuid';
import { MemberOtrDataset } from './MemberOtrDataset';
import { ProposalOtrDataset } from './ProposalOtrDataset';
Expand Down Expand Up @@ -32,37 +32,33 @@ export class OtrRequest<T> {
public readonly nativeToken?: INativeToken,
) {}

getMetadata = () => {
const data = {
targetAddress: this.otrAddress,
amount: this.amount,
metadata: { request: this.metadata },
nativeToken: this.nativeToken,
tag: this.generateTag(),
};
return { ...data, amount: Math.max(MIN_IOTA_AMOUNT / 2, this.amount || 0) };
};
getMetadata = () => ({
targetAddress: this.otrAddress,
metadata: { request: this.metadata },
nativeToken: this.nativeToken,
tag: this.generateTag(),
amount: this.amount,
});

getFireflyDeepLink = () => {
const { amount, metadata, nativeToken, tag } = this.getMetadata();
const { metadata, nativeToken, tag } = this.getMetadata();
const walletType = getFireflyWalletType(this.otrAddress);
return (
walletType +
`://wallet/sendConfirmation?address=${this.otrAddress}` +
'&disableToggleGift=true&disableChangeExpiration=true' +
`&amount=${nativeToken ? nativeToken.amount : amount}` +
`&amount=${nativeToken ? nativeToken.amount : this.amount || 0}` +
`&tag=${tag}&giftStorageDeposit=true` +
`&metadata=${JSON.stringify(metadata)}` +
(nativeToken ? `&assetId=${nativeToken?.id}` : '')
);
};

getBloomDeepLink = () => {
const { amount, metadata, nativeToken, tag } = this.getMetadata();

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 @@ -103,3 +99,12 @@ const getFireflyWalletType = (otrAddress: string) => {
}
throw Error('Invalid otr address, ono firefly wallet type found');
};

export const otrAddressToNetwork = (address: string): Network => {
for (const network of Object.values(Network)) {
if (address.startsWith(network)) {
return network as Network;
}
}
throw Error('Invalid otr address');
};
77 changes: 1 addition & 76 deletions packages/client/src/otr/otr.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,4 @@
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';
Expand Down Expand Up @@ -40,70 +31,4 @@ export class OtrWrapper {
throw Error('invalid dataset name');
}
}

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

class Observable extends RxjsObservable<TangleResponse> {
private observer: Subscriber<TangleResponse> | 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);
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();
};
}

const toHex = (stringToConvert: string) =>
'0x' +
stringToConvert
.split('')
.map((c) => c.charCodeAt(0).toString(16).padStart(2, '0'))
.join('');
38 changes: 0 additions & 38 deletions packages/client/src/wallet/client.ts

This file was deleted.

15 changes: 0 additions & 15 deletions packages/client/src/wallet/common.ts

This file was deleted.

7 changes: 0 additions & 7 deletions packages/client/src/wallet/index.ts

This file was deleted.

Loading

0 comments on commit fece8cb

Please sign in to comment.