Skip to content

Commit

Permalink
feat: use timestamp expiry
Browse files Browse the repository at this point in the history
  • Loading branch information
Karl Ranna committed Dec 1, 2020
1 parent 2644404 commit 67da614
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 30 deletions.
55 changes: 28 additions & 27 deletions lib/connextclient/ConnextClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
OnchainTransferResponse,
ConnextBlockNumberResponse,
ConnextChannelDetails,
GetBlockByNumberResponse,
} from './types';
import { parseResponseBody } from '../utils/utils';
import { Observable, fromEvent, from, defer, Subscription, throwError, interval, timer } from 'rxjs';
Expand Down Expand Up @@ -96,6 +97,9 @@ const CHAIN_IDENTIFIERS: { [key: string]: number } = {
mainnet: 1,
};

const AVERAGE_ETH_BLOCK_TIME_SECONDS = 15;
const ONE_SECOND_IN_MS = 1000;

/**
* A class representing a client to interact with connext.
*/
Expand Down Expand Up @@ -214,15 +218,19 @@ class ConnextClient extends SwapClient {
} = expectedIncomingTransfer;
const currency = this.getCurrencyByTokenaddress(tokenAddress);
const blockHeight = await this.getHeight();
const timelock = expiry - blockHeight;
const block = await this.getBlockByNumber(blockHeight);
const currentTime = parseInt(block.result.timestamp, 16);
// The timelock can be up to 10 blocks less than the agreed upon value
const TIMELOCK_BUFFER = 10;
// We calculate the timelock from current timestamp to the expiry
const TIME_DIFF_IN_MS = expiry - currentTime;
const timelock = TIME_DIFF_IN_MS / ONE_SECOND_IN_MS / AVERAGE_ETH_BLOCK_TIME_SECONDS;
if (
tokenAddress === expectedTokenAddress &&
units === expectedUnits &&
timelock >= expectedTimelock - TIMELOCK_BUFFER
) {
this.logger.debug(`accepting incoming transfer with rHash: ${rHash}, units: ${units}, timelock ${timelock}, currency ${currency}, and routingId ${routingId}`);
this.logger.debug(`accepting incoming transfer with rHash: ${rHash}, units: ${units}, timelock ${timelock.toFixed(0)}, currency ${currency}, and routingId ${routingId}`);
this.expectedIncomingTransfers.delete(rHash);
this.emit('htlcAccepted', rHash, units, currency);
} else {
Expand Down Expand Up @@ -437,36 +445,17 @@ class ConnextClient extends SwapClient {
}

public sendSmallestAmount = async (
rHash: string,
destination: string,
currency: string,
) => {
const tokenAddress = this.getTokenAddress(currency);

assert(this.channelAddress, 'cannot send transfer without channel address');
assert(this.publicIdentifier, 'cannot send transfer with channel address');
const expiry = await this.getExpiry(this.finalLock);
await this.executeHashLockTransfer({
type: 'HashlockTransfer',
amount: '1',
assetId: tokenAddress,
details: {
expiry,
lockHash: `0x${rHash}`,
},
recipient: destination,
meta: {
routingId: this.deriveRoutingId(rHash, tokenAddress),
},
channelAddress: this.channelAddress,
publicIdentifier: this.publicIdentifier,
});
return 'sendSmallestAmount is broken';
throw new Error('Connext.sendSmallestAmount is not implemented');
}

private getExpiry = async (locktime: number): Promise<string> => {
const blockHeight = await this.getHeight();
return (blockHeight + locktime).toString();
const currentBlock = await this.getBlockByNumber(blockHeight);
const currentTimeStamp = parseInt(currentBlock.result.timestamp, 16);
const locktimeMilliseconds = AVERAGE_ETH_BLOCK_TIME_SECONDS * locktime * ONE_SECOND_IN_MS;
const expiry = currentTimeStamp + locktimeMilliseconds;
return expiry.toString();
}

private deriveRoutingId = (lockHash: string, assetId: string): string => {
Expand Down Expand Up @@ -719,6 +708,18 @@ class ConnextClient extends SwapClient {
return true;
}

private getBlockByNumber = async (blockNumber: number) => {
const res = await this.sendRequest(`/ethprovider/${CHAIN_IDENTIFIERS[this.network]}`, 'POST', {
method: 'eth_getBlockByNumber',
params: [
`0x${blockNumber.toString(16)}`,
false
],
});
const block = await parseResponseBody<GetBlockByNumberResponse>(res);
return block;
}

public getHeight = async () => {
const res = await this.sendRequest(`/ethprovider/${CHAIN_IDENTIFIERS[this.network]}`, 'POST', {
method: 'eth_blockNumber',
Expand Down
31 changes: 28 additions & 3 deletions lib/connextclient/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export type ConnextChannelDetails = {
* The payload for tokenPayment call.
*/
export type ConnextTransferRequest = {
type: 'HashlockTransfer';
type: "HashlockTransfer";
channelAddress: string;
amount: string;
assetId: string;
Expand Down Expand Up @@ -126,6 +126,31 @@ export type ConnextBalanceResponse = {
result: string;
};

export type GetBlockByNumberResponse = {
result: {
difficulty: string;
extraData: string;
gasLimit: string;
gasUsed: string;
hash: string;
logsBloom: string;
miner: string;
mixHash: string;
nonce: string;
number: string;
parentHash: string;
receiptsRoot: string;
sha3Uncles: string;
size: string;
stateRoot: string;
timestamp: string;
totalDifficulty: string;
transactions: string[];
transactionsRoot: string;
uncles: string[];
};
};

/**
* The response for hashLockTransfer call.
*/
Expand All @@ -139,8 +164,8 @@ export type ConnextTransferResponse = {
* The response for withdraw call.
*/
export type ConnextWithdrawResponse = {
channelAddress: '0xa929dB0530daB525596f5d48Fb5C322fDa8A337B';
transferId: '0xc2e4592d3fb6c02ee1d3b07bed83b5914f8ca084b0f91d6b80bf8107e58c9c38';
channelAddress: "0xa929dB0530daB525596f5d48Fb5C322fDa8A337B";
transferId: "0xc2e4592d3fb6c02ee1d3b07bed83b5914f8ca084b0f91d6b80bf8107e58c9c38";
};

type ConnextRoutingPath = {
Expand Down

0 comments on commit 67da614

Please sign in to comment.