Skip to content

Commit

Permalink
Add updatedTxParams and confirm history event (#15)
Browse files Browse the repository at this point in the history
* chore: add updatedTxParams and confirm history event

* chore: add cancellable property to SmartTransactions
  • Loading branch information
meppsilon authored Nov 4, 2021
1 parent 2b2a19e commit f0d4bfc
Show file tree
Hide file tree
Showing 5 changed files with 106 additions and 5 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@types/lodash": "^4.14.176",
"bignumber.js": "^9.0.1",
"ethers": "^5.5.1",
"fast-json-patch": "^3.1.0",
"lodash": "^4.17.21"
},
"devDependencies": {
Expand Down
50 changes: 45 additions & 5 deletions src/SmartTransactionsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,20 @@ import {
getAPIRequestURL,
isSmartTransactionPending,
calculateStatus,
snapshotFromTxMeta,
replayHistory,
generateHistoryEntry,
} from './utils';
import { CHAIN_IDS } from './constants';

const { handleFetch, safelyExecute } = util;

// TODO: JSDoc all methods
// TODO: Remove all comments (* ! ?)
const SECOND = 1000;

export const DEFAULT_INTERVAL = 10 * 1000;
export const DEFAULT_INTERVAL = SECOND * 10;
export const CANCELLABLE_INTERVAL = SECOND * 10.5;

export interface SmartTransactionsControllerConfig extends BaseConfig {
interval: number;
Expand Down Expand Up @@ -167,12 +172,15 @@ export default class SmartTransactionsController extends BaseController<

if (currentIndex === -1 || currentIndex === undefined) {
// add smart transaction
const snapshot = cloneDeep(smartTransaction);
const history = [snapshot];
const historifiedSmartTransaction = { ...smartTransaction, history };
this.update({
smartTransactions: {
...this.state.smartTransactions,
[chainId]: [
...this.state.smartTransactions?.[chainId],
smartTransaction,
historifiedSmartTransaction,
],
},
});
Expand Down Expand Up @@ -228,6 +236,9 @@ export default class SmartTransactionsController extends BaseController<
const transactionReceipt = await this.ethersProvider.getTransactionReceipt(
txHash,
);
const transaction = await this.ethersProvider.getTransaction(txHash);
const maxFeePerGas = transaction.maxFeePerGas.toHexString();
const maxPriorityFeePerGas = transaction.maxPriorityFeePerGas.toHexString();
if (transactionReceipt?.blockNumber) {
const blockData = await this.ethersProvider.getBlock(
transactionReceipt?.blockNumber,
Expand All @@ -240,16 +251,36 @@ export default class SmartTransactionsController extends BaseController<
}
return value;
});
const updatedTxParams = {
...smartTransaction.txParams,
maxFeePerGas,
maxPriorityFeePerGas,
};
// call confirmExternalTransaction
const originalTxMeta = {
...smartTransaction,
id: smartTransaction.uuid,
status: 'confirmed',
hash: txHash,
txParams: updatedTxParams,
};
const snapshot = cloneDeep(originalTxMeta);
const history = [snapshot];
const txMeta = { ...originalTxMeta, history };
// create txMeta snapshot for history
const snapshot = snapshotFromTxMeta(originalTxMeta);
// recover previous tx state obj
const previousState = replayHistory(originalTxMeta.history);
// generate history entry and add to history
const entry = generateHistoryEntry(
previousState,
snapshot,
'txStateManager: setting status to confirmed',
);
const txMeta =
entry.length > 0
? {
...originalTxMeta,
history: originalTxMeta.history.concat(entry),
}
: originalTxMeta;
this.txController.confirmExternalTransaction(
txMeta,
txReceipt,
Expand Down Expand Up @@ -376,7 +407,16 @@ export default class SmartTransactionsController extends BaseController<
time,
txParams,
uuid: data.uuid,
cancellable: true,
});

setTimeout(() => {
console.log('reset cancellable');
this.updateSmartTransaction({
uuid: data.uuid,
cancellable: false,
});
}, CANCELLABLE_INTERVAL);
nonceLock.releaseLock();
return data;
}
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export interface SmartTransaction {
destinationTokenAddress?: string;
destinationTokenDecimals?: string;
destinationTokenSymbol?: string;
history?: any;
metamaskNetworkId?: string;
nonceDetails?: any;
origin?: string;
Expand All @@ -81,6 +82,7 @@ export interface SmartTransaction {
txParams?: any;
type?: string;
confirmed?: boolean;
cancellable?: boolean;
}

// TODO: maybe grab the type from transactions controller?
Expand Down
53 changes: 53 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import jsonDiffer from 'fast-json-patch';
import { cloneDeep } from 'lodash';
import {
APIType,
SmartTransaction,
Expand Down Expand Up @@ -82,3 +84,54 @@ export const calculateStatus = (status: SmartTransactionsStatus) => {
}
return SmartTransactionStatuses.UNKNOWN;
};

/**
Generates an array of history objects sense the previous state.
The object has the keys
op (the operation performed),
path (the key and if a nested object then each key will be separated with a `/`)
value
with the first entry having the note and a timestamp when the change took place
@param {Object} previousState - the previous state of the object
@param {Object} newState - the update object
@param {string} [note] - a optional note for the state change
@returns {Array}
*/
export function generateHistoryEntry(
previousState: any,
newState: any,
note: string,
) {
const entry: any = jsonDiffer.compare(previousState, newState);
// Add a note to the first op, since it breaks if we append it to the entry
if (entry[0]) {
if (note) {
entry[0].note = note;
}

entry[0].timestamp = Date.now();
}
return entry;
}

/**
Recovers previous txMeta state obj
@returns {Object}
*/
export function replayHistory(_shortHistory: any) {
const shortHistory = cloneDeep(_shortHistory);
return shortHistory.reduce(
(val: any, entry: any) => jsonDiffer.applyPatch(val, entry).newDocument,
);
}

/**
* Snapshot {@code txMeta}
* @param {Object} txMeta - the tx metadata object
* @returns {Object} a deep clone without history
*/
export function snapshotFromTxMeta(txMeta: any) {
const shallow = { ...txMeta };
delete shallow.history;
return cloneDeep(shallow);
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3862,6 +3862,11 @@ fast-glob@^3.1.1:
micromatch "^4.0.2"
picomatch "^2.2.1"

fast-json-patch@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/fast-json-patch/-/fast-json-patch-3.1.0.tgz#ec8cd9b9c4c564250ec8b9140ef7a55f70acaee6"
integrity sha512-IhpytlsVTRndz0hU5t0/MGzS/etxLlfrpG5V5M9mVbuj9TrJLWaMfsox9REM5rkuGX0T+5qjpe8XA1o0gZ42nA==

[email protected], fast-json-stable-stringify@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633"
Expand Down

0 comments on commit f0d4bfc

Please sign in to comment.