Skip to content

Commit

Permalink
added tests for homa auto route
Browse files Browse the repository at this point in the history
  • Loading branch information
shunjizhan committed Mar 26, 2024
1 parent e7cac15 commit fc53139
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
endpoint:
- wss://crosschain-dev.polkawallet.io:9915
- wss://acala-rpc.aca-api.network
mock-signature-host: true
# block: ${env.ACALA_BLOCK_NUMBER}
db: ./db.sqlite
Expand Down
94 changes: 94 additions & 0 deletions src/__tests__/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { ONE_ACA, almostEq, toHuman } from '@acala-network/asset-router/dist/uti
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { encodeAddress } from '@polkadot/util-crypto';
import { formatEther, parseEther, parseUnits } from 'ethers/lib/utils';
import assert from 'assert';

import {
BASILISK_TESTNET_NODE_URL,
Expand All @@ -22,6 +23,7 @@ import {
TEST_KEY,
} from './testConsts';
import { ETH_RPC, FUJI_TOKEN, GOERLI_USDC, PARA_ID } from '../consts';
import { RouteStatus } from '../api';
import {
encodeXcmDest,
expectError,
Expand All @@ -31,6 +33,8 @@ import {
relayAndRoute,
relayAndRouteBatch,
routeHoma,
routeHomaAuto,
routeStatus,
routeWormhole,
routeXcm,
shouldRouteHoma,
Expand Down Expand Up @@ -421,6 +425,9 @@ describe.skip('/routeHoma', () => {
};

const testHomaRouter = async (destAddr: string) => {
const relayerBal = await relayerAcalaFork.getBalance();
assert(relayerBal.gt(parseEther('10')), `relayer doesn't have enough balance to relay! ${relayerAcalaFork.address}`);

const routeArgs = {
destAddr,
chain: 'acala',
Expand Down Expand Up @@ -473,6 +480,80 @@ describe.skip('/routeHoma', () => {
expect(bal1.relayerBalDot.sub(bal0.relayerBalDot).toBigInt()).to.eq(routingFee.toBigInt());
};

const testAutoHomaRouter = async (destAddr: string) => {
const relayerBal = await relayerAcalaFork.getBalance();
assert(relayerBal.gt(parseEther('10')), `relayer doesn't have enough balance to relay! ${relayerAcalaFork.address}`);

const routeArgs = {
destAddr,
chain: 'acala',
};
const res = await shouldRouteHoma(routeArgs);
({ routerAddr } = res.data);

// make sure user has enough DOT to transfer to router
const bal = await fetchTokenBalances();
if (bal.userBalDot.lt(parsedStakeAmount)) {
if (bal.relayerBalDot.lt(parsedStakeAmount)) {
throw new Error('both relayer and user do not have enough DOT to transfer to router!');
}

console.log('refilling dot for user ...');
await (await dot.connect(relayerAcalaFork).transfer(TEST_ADDR_USER, parsedStakeAmount)).wait();
}

const bal0 = await fetchTokenBalances();

console.log('sending auto routing request ...');
const routeRes = await routeHomaAuto({
...routeArgs,
token: DOT,
});
const reqId = routeRes.data;
console.log(`auto route submitted! reqId: ${reqId}`);

const waitForRoute = new Promise<void>((resolve, reject) => {
const pollRouteStatus = setInterval(async () => {
const res = await routeStatus({ id: reqId });
// console.log(`current status: ${res.data.status}`);

if (res.data.status === RouteStatus.Complete) {
resolve();
clearInterval(pollRouteStatus);
}
}, 1000);

setTimeout(reject, 100 * 1000);
});

console.log('xcming to router ...');
await mockXcmToRouter(routerAddr, userAcalaFork, DOT, stakeAmount);

console.log('waiting for auto routing ...');
await waitForRoute;

console.log('route complete!');
const bal1 = await fetchTokenBalances();

// router should be destroyed
const routerCode = await providerKarura.getCode(routerAddr);
expect(routerCode).to.eq('0x');
expect(bal1.routerBalDot.toNumber()).to.eq(0);
expect(bal1.routerBalLdot.toNumber()).to.eq(0);

// user should receive LDOT
const routingFee = await fee.getFee(DOT);
const exchangeRate = parseEther((1 / Number(formatEther(await homa.getExchangeRate()))).toString()); // 10{18} DOT => ? LDOT
const expectedLdot = parsedStakeAmount.sub(routingFee).mul(exchangeRate).div(ONE_ACA);
const ldotReceived = bal1.userBalLdot.sub(bal0.userBalLdot);

expect(almostEq(expectedLdot, ldotReceived)).to.be.true;
// expect(bal0.userBalDot.sub(bal1.userBalDot)).to.eq(parsedStakeAmount); // TODO: why this has a super slight off?

// relayer should receive DOT fee
expect(bal1.relayerBalDot.sub(bal0.relayerBalDot).toBigInt()).to.eq(routingFee.toBigInt());
};

it('route to evm address', async () => {
await testHomaRouter(TEST_ADDR_USER);
});
Expand All @@ -484,5 +565,18 @@ describe.skip('/routeHoma', () => {

await testHomaRouter(userSubstrateAddr);
});

it('auto route to evm address', async () => {
await testAutoHomaRouter(TEST_ADDR_USER);
});

it('auto route to substrate address', async () => {
const ACALA_SS58_PREFIX = 10;
const userAccountId = await evmAccounts.getAccountId(TEST_ADDR_USER);
const userSubstrateAddr = encodeAddress(userAccountId, ACALA_SS58_PREFIX);

await testAutoHomaRouter(userSubstrateAddr);
});
});


30 changes: 15 additions & 15 deletions src/__tests__/shouldRoute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,13 +321,13 @@ describe.concurrent.skip('/shouldRouteHoma', () => {
});

expect(res).toMatchInlineSnapshot(`
{
"data": {
"routerAddr": "0xa013818BBddc5d2d55ab9cCD50759b3B1953d6cd",
"shouldRoute": true,
},
}
`);
{
"data": {
"routerAddr": "0x8A4f03B2D615172f0714AaC2E8C399a6f0d9e448",
"shouldRoute": true,
},
}
`);

// should be case insensitive
res = await shouldRouteHoma({
Expand All @@ -336,13 +336,13 @@ describe.concurrent.skip('/shouldRouteHoma', () => {
});

expect(res).toMatchInlineSnapshot(`
{
"data": {
"routerAddr": "0xa013818BBddc5d2d55ab9cCD50759b3B1953d6cd",
"shouldRoute": true,
},
}
`);
{
"data": {
"routerAddr": "0x8A4f03B2D615172f0714AaC2E8C399a6f0d9e448",
"shouldRoute": true,
},
}
`);
}
});

Expand All @@ -357,7 +357,7 @@ describe.concurrent.skip('/shouldRouteHoma', () => {
expect(res).toMatchInlineSnapshot(`
{
"data": {
"routerAddr": "0xfD6143c380706912a04230f22cF92c402561820e",
"routerAddr": "0x1140EFc2C45e9307701DA521884F75dDDe28f28f",
"shouldRoute": true,
},
}
Expand Down
8 changes: 8 additions & 0 deletions src/__tests__/testUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,14 @@ export const routeHoma = process.env.COVERAGE
? _supertestPost(RELAYER_API.ROUTE_HOMA)
: _axiosPost(RELAYER_URL.ROUTE_HOMA);

export const routeHomaAuto = process.env.COVERAGE
? _supertestPost(RELAYER_API.ROUTE_HOMA_AUTO)
: _axiosPost(RELAYER_URL.ROUTE_HOMA_AUTO);

export const routeStatus = process.env.COVERAGE
? _supertestGet(RELAYER_API.ROUTE_STATUS)
: _axiosGet(RELAYER_URL.ROUTE_STATUS);

export const shouldRouteEuphrates = process.env.COVERAGE
? _supertestGet(RELAYER_API.SHOULD_ROUTER_EUPHRATES)
: _axiosGet(RELAYER_URL.SHOULD_ROUTER_EUPHRATES);
Expand Down
2 changes: 1 addition & 1 deletion src/api/homa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const routeHoma = async ({ chain, destAddr }: RouteParamsHoma) => {
return receipt.transactionHash;
};

enum RouteStatus {
export enum RouteStatus {
Waiting = 0,
Routing = 1,
Confirming = 2,
Expand Down
4 changes: 4 additions & 0 deletions src/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ export const RELAYER_API = {

SHOULD_ROUTER_HOMA: '/shouldRouteHoma',
ROUTE_HOMA: '/routeHoma',
ROUTE_HOMA_AUTO: '/routeHomaAuto',
ROUTE_STATUS: '/routeStatus',

SHOULD_ROUTER_EUPHRATES: '/shouldRouteEuphrates',
ROUTE_EUPHRATES: '/routeEuphrates',
Expand All @@ -80,6 +82,8 @@ export const RELAYER_URL = {

SHOULD_ROUTER_HOMA: `${RELAYER_BASE_URL}${RELAYER_API.SHOULD_ROUTER_HOMA}`,
ROUTE_HOMA: `${RELAYER_BASE_URL}${RELAYER_API.ROUTE_HOMA}`,
ROUTE_HOMA_AUTO: `${RELAYER_BASE_URL}${RELAYER_API.ROUTE_HOMA_AUTO}`,
ROUTE_STATUS: `${RELAYER_BASE_URL}${RELAYER_API.ROUTE_STATUS}`,

SHOULD_ROUTER_EUPHRATES: `${RELAYER_BASE_URL}${RELAYER_API.SHOULD_ROUTER_EUPHRATES}`,
ROUTE_EUPHRATES: `${RELAYER_BASE_URL}${RELAYER_API.ROUTE_EUPHRATES}`,
Expand Down
4 changes: 2 additions & 2 deletions src/middlewares/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,11 @@ const ROUTER_CONFIGS: {
'/health': {
handler: healthCheck,
},
'/getRouteStatus': {
'/routeStatus': {
schema: routeStatusSchema,
handler: getRouteStatus,
},
'/getAllRouteStatus': {
'/allRouteStatus': {
handler: getAllRouteStatus,
},
},
Expand Down
2 changes: 1 addition & 1 deletion src/utils/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import {
ZERO_ADDR,
} from '../consts';
import { RelayAndRouteParams, RouteParamsWormhole, RouteParamsXcm } from './validate';
import { getRouterChainTokenAddr } from './wormhole';
import { checkShouldRelayBeforeRouting } from './relay';
import { getRouterChainTokenAddr } from './wormhole';

interface RouteProps {
routerAddr: string;
Expand Down

0 comments on commit fc53139

Please sign in to comment.