Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add many unit tests, support for the batch_status API, refactoring #6

Merged
merged 4 commits into from
Sep 20, 2021
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
8 changes: 4 additions & 4 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ module.exports = {
coverageReporters: ['text', 'html'],
coverageThreshold: {
global: {
branches: 26,
functions: 50,
lines: 60,
statements: 61,
branches: 84,
functions: 91,
lines: 93,
statements: 93,
},
},
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node'],
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"scripts": {
"setup": "yarn install && yarn allow-scripts",
"test": "jest",
"test:watch": "jest --watch",
"test:watch": "jest --watchAll",
"prepublishOnly": "yarn build:clean && yarn lint && yarn test",
"lint:eslint": "eslint . --cache --ext js,ts",
"lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' --ignore-path .gitignore",
Expand Down
218 changes: 215 additions & 3 deletions src/SmartTransactionsController.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,136 @@
import nock from 'nock';
import { NetworkState } from '@metamask/controllers';
import SmartTransactionsController, {
DEFAULT_INTERVAL,
} from './SmartTransactionsController';
import { API_BASE_URL, CHAIN_IDS } from './constants';
import { SmartTransaction } from './types';

const createUnsignedTransaction = () => {
return {
from: '0x268392a24B6b093127E8581eAfbD1DA228bAdAe3',
to: '0x0000000000000000000000000000000000000000',
value: 0,
data: '0x',
nonce: 0,
type: 2,
chainId: 4,
};
};

const createGetTransactionsApiResponse = () => {
return {
cancelFees: [
{ maxFeePerGas: 2100001000, maxPriorityFeePerGas: 466503987 },
{ maxFeePerGas: 2310003200, maxPriorityFeePerGas: 513154852 },
{ maxFeePerGas: 2541005830, maxPriorityFeePerGas: 564470851 },
{ maxFeePerGas: 2795108954, maxPriorityFeePerGas: 620918500 },
{ maxFeePerGas: 3074622644, maxPriorityFeePerGas: 683010971 },
{ maxFeePerGas: 3382087983, maxPriorityFeePerGas: 751312751 },
{ maxFeePerGas: 3720300164, maxPriorityFeePerGas: 826444778 },
{ maxFeePerGas: 4092333900, maxPriorityFeePerGas: 909090082 },
{ maxFeePerGas: 4501571383, maxPriorityFeePerGas: 1000000000 },
{ maxFeePerGas: 4951733023, maxPriorityFeePerGas: 1100001000 },
{ maxFeePerGas: 5446911277, maxPriorityFeePerGas: 1210002200 },
{ maxFeePerGas: 5991607851, maxPriorityFeePerGas: 1331003630 },
{ maxFeePerGas: 6590774628, maxPriorityFeePerGas: 1464105324 },
{ maxFeePerGas: 7249858682, maxPriorityFeePerGas: 1610517320 },
{ maxFeePerGas: 7974851800, maxPriorityFeePerGas: 1771570663 },
{ maxFeePerGas: 8772344955, maxPriorityFeePerGas: 1948729500 },
{ maxFeePerGas: 9649588222, maxPriorityFeePerGas: 2143604399 },
{ maxFeePerGas: 10614556694, maxPriorityFeePerGas: 2357966983 },
{ maxFeePerGas: 11676022978, maxPriorityFeePerGas: 2593766039 },
],
feeEstimate: 42000000000000,
fees: [
{ maxFeePerGas: 2310003200, maxPriorityFeePerGas: 513154852 },
{ maxFeePerGas: 2541005830, maxPriorityFeePerGas: 564470850 },
{ maxFeePerGas: 2795108954, maxPriorityFeePerGas: 620918500 },
{ maxFeePerGas: 3074622644, maxPriorityFeePerGas: 683010970 },
{ maxFeePerGas: 3382087983, maxPriorityFeePerGas: 751312751 },
{ maxFeePerGas: 3720300163, maxPriorityFeePerGas: 826444777 },
{ maxFeePerGas: 4092333900, maxPriorityFeePerGas: 909090082 },
{ maxFeePerGas: 4501571382, maxPriorityFeePerGas: 999999999 },
{ maxFeePerGas: 4951733022, maxPriorityFeePerGas: 1100001000 },
{ maxFeePerGas: 5446911277, maxPriorityFeePerGas: 1210002200 },
{ maxFeePerGas: 5991607851, maxPriorityFeePerGas: 1331003630 },
{ maxFeePerGas: 6590774627, maxPriorityFeePerGas: 1464105324 },
{ maxFeePerGas: 7249858681, maxPriorityFeePerGas: 1610517320 },
{ maxFeePerGas: 7974851800, maxPriorityFeePerGas: 1771570662 },
{ maxFeePerGas: 8772344954, maxPriorityFeePerGas: 1948729500 },
{ maxFeePerGas: 9649588222, maxPriorityFeePerGas: 2143604398 },
{ maxFeePerGas: 10614556693, maxPriorityFeePerGas: 2357966982 },
{ maxFeePerGas: 11676022977, maxPriorityFeePerGas: 2593766039 },
{ maxFeePerGas: 12843636951, maxPriorityFeePerGas: 2853145236 },
],
gasLimit: 21000,
gasUsed: 21000,
};
};

const createSubmitTransactionsApiResponse = () => {
return { uuid: 'dP23W7c2kt4FK9TmXOkz1UM2F20' };
};

// TODO: How exactly a signed transaction should look like?
const createSignedTransaction = () => {
return {
from: '0x268392a24B6b093127E8581eAfbD1DA228bAdAe3',
to: '0x0000000000000000000000000000000000000000',
value: 0,
data: '0x',
nonce: 0,
type: 2,
chainId: 4,
maxFeePerGas: 2310003200,
maxPriorityFeePerGas: 513154852,
};
};

// TODO: How exactly a signed canceled transaction should look like?
const createSignedCanceledTransaction = () => {
return {
from: '0x268392a24B6b093127E8581eAfbD1DA228bAdAe3',
to: '0x0000000000000000000000000000000000000000',
value: 0,
data: '0x',
nonce: 0,
type: 2,
chainId: 4,
maxFeePerGas: 2100001000,
maxPriorityFeePerGas: 466503987,
};
};

const createPendingBatchStatusApiResponse = () => {
return [
{
uuid: 'uuid1',
status: {
cancellationFeeWei: 0,
cancellationReason: 'not_cancelled',
deadlineRatio: 0.0006295545895894369,
minedTx: 'not_mined',
},
},
];
};

const createSuccessBatchStatusApiResponse = () => {
return [
{
uuid: 'uuid1',
status: {
cancellationFeeWei: 36777567771000,
cancellationReason: 'not_cancelled',
deadlineRatio: 0.6400288486480713,
minedHash:
'0x55ad39634ee10d417b6e190cfd3736098957e958879cffe78f1f00f4fd2654d6',
minedTx: 'success',
},
},
];
};

describe('SmartTransactionsController', () => {
let smartTransactionsController: SmartTransactionsController;
Expand All @@ -17,21 +146,24 @@ describe('SmartTransactionsController', () => {

afterEach(async () => {
jest.clearAllMocks();
nock.cleanAll();
await smartTransactionsController.stop();
});

it('initializes with default config', () => {
expect(smartTransactionsController.config).toStrictEqual({
interval: DEFAULT_INTERVAL,
supportedChainIds: ['1'],
chainId: '',
supportedChainIds: [CHAIN_IDS.ETHEREUM],
chainId: CHAIN_IDS.ETHEREUM,
clientId: 'default',
});
});

it('initializes with default state', () => {
expect(smartTransactionsController.state).toStrictEqual({
smartTransactions: {},
smartTransactions: {
[CHAIN_IDS.ETHEREUM]: [],
},
userOptIn: undefined,
});
});
Expand Down Expand Up @@ -96,4 +228,84 @@ describe('SmartTransactionsController', () => {
expect(smartTransactionsController.state.userOptIn).toBeUndefined();
});
});

describe('getUnsignedTransactionsAndEstimates', () => {
it('gets unsigned transactions and estimates based on an unsigned transaction', async () => {
const unsignedTransaction = createUnsignedTransaction();
const getTransactionsApiResponse = createGetTransactionsApiResponse();
nock(API_BASE_URL)
.post(`/networks/${CHAIN_IDS.ETHEREUM}/getTransactions`)
.reply(200, getTransactionsApiResponse);
const unsignedTransactionsAndEstimates = await smartTransactionsController.getUnsignedTransactionsAndEstimates(
unsignedTransaction,
);
expect(unsignedTransactionsAndEstimates).toStrictEqual(
getTransactionsApiResponse,
);
});
});

describe('submitSignedTransactions', () => {
it('submits a smart transaction with signed transactions', async () => {
const signedTransaction = createSignedTransaction();
const signedCanceledTransaction = createSignedCanceledTransaction();
const submitTransactionsApiResponse = createSubmitTransactionsApiResponse(); // It has uuid.
nock(API_BASE_URL)
.post(`/networks/${CHAIN_IDS.ETHEREUM}/submitTransactions`)
.reply(200, submitTransactionsApiResponse);

await smartTransactionsController.submitSignedTransactions({
signedTransactions: [signedTransaction],
signedCanceledTransactions: [signedCanceledTransaction],
});

expect(smartTransactionsController.state).toStrictEqual({
smartTransactions: {
1: [submitTransactionsApiResponse],
},
userOptIn: undefined,
});
});
});

describe('fetchSmartTransactionsStatus', () => {
it('fetches a pending status for a single smart transaction via batch_status API', async () => {
const uuids = ['uuid1'];
const pendingBatchStatusApiResponse = createPendingBatchStatusApiResponse();
nock(API_BASE_URL)
.get(`/networks/${CHAIN_IDS.ETHEREUM}/batch_status?uuids=uuid1`)
.reply(200, pendingBatchStatusApiResponse);
await smartTransactionsController.fetchSmartTransactionsStatus(uuids);
expect(smartTransactionsController.state).toStrictEqual({
smartTransactions: {
'1': pendingBatchStatusApiResponse,
},
userOptIn: undefined,
});
});

it('fetches a success status for a single smart transaction via batch_status API', async () => {
const uuids = ['uuid1'];
const pendingBatchStatusApiResponse = createPendingBatchStatusApiResponse();
const successBatchStatusApiResponse = createSuccessBatchStatusApiResponse();
smartTransactionsController.update({
smartTransactions: {
[CHAIN_IDS.ETHEREUM]: [
pendingBatchStatusApiResponse[0],
] as SmartTransaction[],
},
});

nock(API_BASE_URL)
.get(`/networks/${CHAIN_IDS.ETHEREUM}/batch_status?uuids=uuid1`)
.reply(200, successBatchStatusApiResponse);
await smartTransactionsController.fetchSmartTransactionsStatus(uuids);
expect(smartTransactionsController.state).toStrictEqual({
smartTransactions: {
'1': successBatchStatusApiResponse,
},
userOptIn: undefined,
});
});
});
});
49 changes: 28 additions & 21 deletions src/SmartTransactionsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
UnsignedTransaction,
} from './types';
import { getAPIRequestURL, isSmartTransactionPending } from './utils';
import { CHAIN_IDS } from './constants';

const { handleFetch, safelyExecute } = util;

Expand Down Expand Up @@ -42,9 +43,10 @@ export default class SmartTransactionsController extends BaseController<
private updateSmartTransaction(smartTransaction: SmartTransaction): void {
const { chainId } = this.config;
const currentIndex = this.state.smartTransactions[chainId]?.findIndex(
(st) => st.UUID === smartTransaction.UUID,
(st) => st.uuid === smartTransaction.uuid,
);
if (currentIndex === -1) {

if (currentIndex === -1 || currentIndex === undefined) {
this.update({
smartTransactions: {
...this.state.smartTransactions,
Expand Down Expand Up @@ -98,9 +100,9 @@ export default class SmartTransactionsController extends BaseController<

this.defaultConfig = {
interval: DEFAULT_INTERVAL,
chainId: '',
chainId: CHAIN_IDS.ETHEREUM,
clientId: 'default',
supportedChainIds: ['1'],
supportedChainIds: [CHAIN_IDS.ETHEREUM],
};

this.defaultState = {
Expand All @@ -109,24 +111,30 @@ export default class SmartTransactionsController extends BaseController<
};

this.initialize();
this.initializeSmartTransactionsForChainId();

onNetworkStateChange(({ provider }) => {
const { chainId } = provider;
this.configure({ chainId });
if (this.config.supportedChainIds.includes(chainId)) {
this.update({
smartTransactions: {
...this.state.smartTransactions,
[chainId]: this.state.smartTransactions[chainId] ?? [],
},
});
}
this.initializeSmartTransactionsForChainId();
this.poll();
});

this.poll();
}

initializeSmartTransactionsForChainId() {
if (this.config.supportedChainIds.includes(this.config.chainId)) {
this.update({
smartTransactions: {
...this.state.smartTransactions,
[this.config.chainId]:
this.state.smartTransactions[this.config.chainId] ?? [],
},
});
}
}

async poll(interval?: number): Promise<void> {
const { chainId, supportedChainIds } = this.config;
interval && this.configure({ interval }, false, false);
Expand Down Expand Up @@ -155,7 +163,7 @@ export default class SmartTransactionsController extends BaseController<
const transactionsToUpdate: string[] = [];
smartTransactions[chainId]?.forEach((smartTransaction) => {
if (isSmartTransactionPending(smartTransaction)) {
transactionsToUpdate.push(smartTransaction.UUID);
transactionsToUpdate.push(smartTransaction.uuid);
}
});

Expand All @@ -166,16 +174,16 @@ export default class SmartTransactionsController extends BaseController<
}
}

// ! Ask backend API to accept list of UUIDs as params
async fetchSmartTransactionsStatus(UUIDS: string[]): Promise<void> {
// ! Ask backend API to accept list of uuids as params
async fetchSmartTransactionsStatus(uuids: string[]): Promise<void> {
const { chainId } = this.config;

const params = new URLSearchParams({
uuids: UUIDS.join(','),
uuids: uuids.join(','),
});

const url = `${getAPIRequestURL(
APIType.STATUS,
APIType.BATCH_STATUS,
chainId,
)}?${params.toString()}`;

Expand Down Expand Up @@ -230,19 +238,18 @@ export default class SmartTransactionsController extends BaseController<
}),
},
);

this.updateSmartTransaction({ UUID: data.uuid });
this.updateSmartTransaction({ uuid: data.uuid });
}

// ! This should return if the cancellation was on chain or not (for nonce management)
// * After this successful call client must update nonce representative
// * in transaction controller external transactions list
// ! Ask backend API to make this endpoint a POST
async cancelSmartTransaction(UUID: string): Promise<void> {
async cancelSmartTransaction(uuid: string): Promise<void> {
const { chainId } = this.config;
await this.fetch(getAPIRequestURL(APIType.CANCEL, chainId), {
method: 'POST',
body: JSON.stringify({ uuid: UUID }),
body: JSON.stringify({ uuid }),
});
}
}
Loading