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

feat: Automated E2E Holders #653

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
70 changes: 70 additions & 0 deletions tests/tenderly-simulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Address } from '@paraswap/core';
import axios from 'axios';
import { TxObject } from '../src/types';
import { StateOverrides, StateSimulateApiOverride } from './smart-tokens';
import { fixHexStringForTenderly } from './utils';

const TENDERLY_TOKEN = process.env.TENDERLY_TOKEN;
const TENDERLY_ACCOUNT_ID = process.env.TENDERLY_ACCOUNT_ID;
Expand All @@ -18,6 +19,11 @@ export type SimulationResult = {
transaction?: any;
};

type FundingResult = {
success: boolean;
url?: string;
};

export interface TransactionSimulator {
forkId: string;
setup(): Promise<void>;
Expand All @@ -26,6 +32,8 @@ export interface TransactionSimulator {
params: TxObject,
stateOverrides?: StateOverrides,
): Promise<SimulationResult>;

addBalance(address: Address, amount: string): Promise<FundingResult>;
}

export class EstimateGasSimulation implements TransactionSimulator {
Expand All @@ -35,6 +43,10 @@ export class EstimateGasSimulation implements TransactionSimulator {

async setup() {}

async addBalance(): Promise<FundingResult> {
return { success: true };
}

async simulate(
params: TxObject,
_: StateOverrides,
Expand Down Expand Up @@ -122,6 +134,14 @@ export class TenderlySimulation implements TransactionSimulator {
},
);

// if encode states fail, the simulation will most likely faily due to allowance/balance checks.
if (result.status !== 200) {
console.error(`TenderlySimulation_encodeStates`, result.data);
return {
success: false,
};
}

_params.state_objects = Object.keys(result.data.stateOverrides).reduce(
(acc, contract) => {
const _storage = result.data.stateOverrides[contract].value;
Expand Down Expand Up @@ -169,4 +189,54 @@ export class TenderlySimulation implements TransactionSimulator {
};
}
}

// Override the balance of an address (native token).
// NOTE: you probably can't find these transactions on the dashboard as Tenderly does not include them in the list of transactions.
async addBalance(address: string, amount: string): Promise<any> {
try {
const { data } = await axios.post(
`https://rpc.tenderly.co/fork/${this.forkId}`,
{
method: 'tenderly_addBalance',
params: [[address], fixHexStringForTenderly(amount)],
id: this.network.toString(),
jsonrpc: '2.0',
},
{ headers: { 'Content-Type': 'application/json' } },
);

if ('error' in data) {
console.error('addBalance error', data.error);
return {
success: false,
};
}

let res = await axios.get(
`https://api.tenderly.co/api/v1/account/paraswap/project/paraswap/fork/${this.forkId}/transactions`,
{
headers: { 'x-access-key': TENDERLY_TOKEN! },
params: {
page: 1,
perPage: 1,
exclude_internal: false,
},
},
);
this.lastTx = res.data.fork_transactions[0].id;
// console.log(
// 'Add Balance Success',
// `https://dashboard.tenderly.co/${TENDERLY_ACCOUNT_ID}/${TENDERLY_PROJECT}/fork/${this.forkId}/simulation/${this.lastTx}`,
// );
return {
success: true,
};
} catch (err) {
console.error(`TenderlySimulation_addBalance:`, err);
return {
success: false,
url: `https://dashboard.tenderly.co/${TENDERLY_ACCOUNT_ID}/${TENDERLY_PROJECT}/fork/${this.forkId}/simulation/${this.lastTx}`,
};
}
}
}
41 changes: 37 additions & 4 deletions tests/utils-e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from '../src/implementations/local-paraswap-sdk';
import {
EstimateGasSimulation,
SimulationResult,
TenderlySimulation,
TransactionSimulator,
} from './tenderly-simulation';
Expand Down Expand Up @@ -36,6 +37,7 @@ import { GIFTER_ADDRESS } from './constants-e2e';
import { generateDeployBytecode, sleep } from './utils';
import { assert } from 'ts-essentials';
import * as util from 'util';
import { BigNumber, ethers } from 'ethers';

export const testingEndpoint = process.env.E2E_TEST_ENDPOINT;

Expand Down Expand Up @@ -262,7 +264,7 @@ export function formatDeployMessage(
export async function testE2E(
srcToken: Token,
destToken: Token,
senderAddress: Address,
_senderAddress: Address,
_amount: string,
swapSide = SwapSide.SELL,
dexKey: string,
Expand All @@ -277,6 +279,7 @@ export async function testE2E(
sleepMs?: number,
replaceTenderlyWithEstimateGas?: boolean,
) {
const sender = ethers.Wallet.createRandom().address;
const amount = BigInt(_amount);

const ts: TransactionSimulator = replaceTenderlyWithEstimateGas
Expand All @@ -286,10 +289,16 @@ export async function testE2E(

if (srcToken.address.toLowerCase() !== ETHER_ADDRESS.toLowerCase()) {
const allowanceTx = await ts.simulate(
allowTokenTransferProxyParams(srcToken.address, senderAddress, network),
allowTokenTransferProxyParams(srcToken.address, sender, network),
);
if (!allowanceTx.success) console.log(allowanceTx.url);
expect(allowanceTx!.success).toEqual(true);
} else {
const addBalanceTx = await ts.addBalance(
sender,
BigNumber.from(_amount).toHexString(),
);
expect(addBalanceTx.success).toEqual(true);
}

if (deployedTestContractAddress) {
Expand Down Expand Up @@ -391,10 +400,34 @@ export async function testE2E(
const swapParams = await paraswap.buildTransaction(
priceRoute,
minMaxAmount,
senderAddress,
sender,
);

const swapTx = await ts.simulate(swapParams);
const address = generateConfig(network).tokenTransferProxyAddress;

let swapTx: SimulationResult;
// When the source token is not ETH, we brute force the storage slots for all known balances and allowances
if (srcToken.address.toLowerCase() !== ETHER_ADDRESS.toLowerCase()) {
const multipliedAmount = BigNumber.from(amount).mul(2).toString();
swapTx = await ts.simulate(swapParams, {
networkID: network.toString(),
stateOverrides: {
[`${srcToken.address.toLowerCase()}`]: {
value: {
[`balances[${sender}]`]: multipliedAmount,
[`_balances[${sender}]`]: multipliedAmount,
[`balanceOf[${sender}]`]: multipliedAmount,
[`allowance[${sender}][${address.toLowerCase()}]`]:
multipliedAmount,
[`_allowances[${sender}][${address.toLowerCase()}]`]:
multipliedAmount,
},
},
},
});
} else {
swapTx = await ts.simulate(swapParams);
}
// Only log gas estimate if testing against API
if (useAPI) {
const gasUsed = swapTx.gasUsed || '0';
Expand Down
8 changes: 8 additions & 0 deletions tests/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,11 @@ export const generateDeployBytecode = (

return deployedBytecode.toString();
};

export const fixHexStringForTenderly = (hexString: string): string => {
if (hexString[2] === '0') {
hexString = '0x' + hexString.substring(3);
}

return hexString;
};
Loading