Skip to content

Commit 81d48d2

Browse files
chore: update swap order and cleanup
1 parent a3ea7e2 commit 81d48d2

10 files changed

+233
-215
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ This is a Typescript project. Npm as package manager and node. Tested with npm v
2626
7. Run the scripts with `npm exec ts-node src/main/scripts/SCRIPT.ts`, where `SCRIPT` can be:
2727

2828
* `do-swap` (performs a cross-chain token transfer from Optimism to Polygon based on the first received route)
29-
* `do-swap-aptos-evm` (performs a cross-chain token transfer from Aptos (WETH) to Optimism ETH)
30-
* `do-swap-evm-aptos` (performs a cross-chain token transfer from Optimism (ETH) to Aptos (WETH))
29+
* `do-swap-non-evm-to-evm` (performs a cross-chain token transfer from Aptos (WETH) to Optimism ETH)
30+
* `do-swap-evm-to-non-evm` (performs a cross-chain token transfer from Optimism (ETH) to Aptos (WETH))
3131
* `get-approvals` (gets the status of an approval)
3232
* `get-chains` (gets the list of supported chains)
3333
* `get-routes` (gets a set of routes that satisfy a swap)

src/main/endpoints/routes.ts

Lines changed: 38 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,30 @@ import type {
44
RoutesResponse,
55
Route,
66
} from "@blockdaemon/blockdaemon-defi-api-typescript-fetch";
7-
import {aptosProvider, isAptosTransaction, log} from "../utils/common";
8-
import {Account, MoveStructId} from "@aptos-labs/ts-sdk";
7+
import { aptosProvider, isAptosTransaction, log } from "../utils/common";
8+
import { Account, MoveStructId } from "@aptos-labs/ts-sdk";
99

1010
const logger = log.getLogger("routes-endpoint");
1111

1212
function chooseBestRoute(routes: Route[], preferredIntegrator: string): Route {
1313
const topThree = [...routes]
14-
.sort((a, b) => Number(b.to.amount) - Number(a.to.amount))
15-
.slice(0, 3);
14+
.sort((a, b) => Number(b.to.amount) - Number(a.to.amount))
15+
.slice(0, 3);
1616

1717
const chosen = topThree.filter(
18-
(r) => r.steps?.[0].integrationDetails?.key === preferredIntegrator,
18+
(r) => r.steps?.[0].integrationDetails?.key === preferredIntegrator,
1919
);
2020

2121
return chosen[0];
2222
}
2323

2424
export async function getRoutes(
25-
exchangeAPI: ExchangeApi,
26-
routeParameters: GetRoutesRequest,
27-
preferredIntegrator: string = "",
25+
exchangeAPI: ExchangeApi,
26+
routeParameters: GetRoutesRequest,
27+
preferredIntegrator: string = "",
2828
): Promise<Route> {
2929
const routesResponse: RoutesResponse =
30-
await exchangeAPI.getRoutes(routeParameters);
30+
await exchangeAPI.getRoutes(routeParameters);
3131
logger.info("Got valid routes");
3232
if (!routesResponse.routes || routesResponse.routes.length === 0) {
3333
throw new Error("No valid routes returned.");
@@ -37,26 +37,26 @@ export async function getRoutes(
3737
return routesResponse.routes[0];
3838
}
3939
const selectedRoute: Route = chooseBestRoute(
40-
routesResponse.routes,
41-
preferredIntegrator,
40+
routesResponse.routes,
41+
preferredIntegrator,
4242
);
4343
logger.debug("Selected route:", JSON.stringify(selectedRoute, null, 2));
4444
logger.info(`Selected best route using ${preferredIntegrator}`);
4545
return selectedRoute;
4646
}
4747

4848
export async function executeSwap(
49-
selectedRoute: Route,
50-
wallet: { address: string; privateKey: string },
51-
rpcUrl: string,
49+
selectedRoute: Route,
50+
wallet: { address: string; privateKey: string },
51+
rpcUrl: string,
5252
): Promise<{ hash: string }> {
5353
const { signAndBroadcastTransaction } = await import("./wallet");
5454
logger.info("Executing swap transaction...");
5555
const { transactionRequest } = selectedRoute;
5656
const broadcastResult = await signAndBroadcastTransaction(
57-
transactionRequest,
58-
wallet.privateKey,
59-
rpcUrl,
57+
transactionRequest,
58+
wallet.privateKey,
59+
rpcUrl,
6060
);
6161
if (!broadcastResult?.hash) {
6262
throw new Error("Failed to broadcast swap transaction");
@@ -66,16 +66,19 @@ export async function executeSwap(
6666
}
6767

6868
export async function executeSwapAptos(
69-
selectedRoute: Route,
70-
aptosAccount: Account,
69+
selectedRoute: Route,
70+
aptosAccount: Account,
7171
): Promise<{ hash: string }> {
7272
logger.info("Executing Aptos swap transaction...");
7373

7474
const { transactionRequest } = selectedRoute;
7575

7676
try {
7777
if (!isAptosTransaction(transactionRequest)) {
78-
throw new Error('Expected Aptos transaction but received: ' + transactionRequest.chainType);
78+
throw new Error(
79+
"Expected Aptos transaction but received: " +
80+
transactionRequest.chainType,
81+
);
7982
}
8083

8184
const rawTxData = transactionRequest as any;
@@ -84,7 +87,7 @@ export async function executeSwapAptos(
8487
sender: rawTxData.sender,
8588
function: rawTxData.payload.function,
8689
typeArgs: rawTxData.payload.type_arguments,
87-
args: rawTxData.payload.arguments
90+
args: rawTxData.payload.arguments,
8891
});
8992

9093
// Format the arguments properly
@@ -94,7 +97,7 @@ export async function executeSwapAptos(
9497
return new Uint8Array(arg);
9598
}
9699
// If argument is a hex string (starting with 0x), convert to bytes
97-
if (typeof arg === 'string' && arg.startsWith('0x')) {
100+
if (typeof arg === "string" && arg.startsWith("0x")) {
98101
// Remove '0x' prefix and convert to Uint8Array
99102
const hexString = arg.slice(2);
100103
const bytes = new Uint8Array(hexString.length / 2);
@@ -104,11 +107,11 @@ export async function executeSwapAptos(
104107
return bytes;
105108
}
106109
// For boolean values
107-
if (typeof arg === 'boolean') {
110+
if (typeof arg === "boolean") {
108111
return arg;
109112
}
110113
// For numeric values
111-
if (typeof arg === 'number' || !isNaN(Number(arg))) {
114+
if (typeof arg === "number" || !isNaN(Number(arg))) {
112115
return Number(arg);
113116
}
114117
return arg;
@@ -120,13 +123,13 @@ export async function executeSwapAptos(
120123
data: {
121124
function: rawTxData.payload.function as MoveStructId,
122125
typeArguments: rawTxData.payload.type_arguments,
123-
functionArguments: formattedArguments
126+
functionArguments: formattedArguments,
124127
},
125128
options: {
126129
maxGasAmount: Number(rawTxData.max_gas_amount),
127130
gasUnitPrice: Number(rawTxData.gas_unit_price),
128-
expireTimestamp: Number(rawTxData.expiration_timestamp_secs)
129-
}
131+
expireTimestamp: Number(rawTxData.expiration_timestamp_secs),
132+
},
130133
});
131134

132135
// Sign and submit the transaction
@@ -139,12 +142,16 @@ export async function executeSwapAptos(
139142
throw new Error("No transaction hash returned from submission");
140143
}
141144

142-
const txHash = committedTxn.hash.startsWith('0x') ? committedTxn.hash : `0x${committedTxn.hash}`;
143-
logger.info(`Aptos swap transaction submitted successfully. Tx Hash: ${txHash}`);
145+
const txHash = committedTxn.hash.startsWith("0x")
146+
? committedTxn.hash
147+
: `0x${committedTxn.hash}`;
148+
logger.info(
149+
`Aptos swap transaction submitted successfully. Tx Hash: ${txHash}`,
150+
);
144151

145152
// Wait for transaction to be confirmed
146153
await aptosProvider.waitForTransaction({
147-
transactionHash: txHash
154+
transactionHash: txHash,
148155
});
149156

150157
logger.info(`Transaction executed and committed: ${txHash}`);
@@ -153,4 +160,4 @@ export async function executeSwapAptos(
153160
logger.error("Failed to execute Aptos transaction:", error);
154161
throw new Error(`Aptos transaction execution failed: ${error}`);
155162
}
156-
}
163+
}

src/main/endpoints/status.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
type ExchangeApi,
44
StatusEnum,
55
} from "@blockdaemon/blockdaemon-defi-api-typescript-fetch";
6-
import { handleApiError, isSdkErrorResponse } from "../utils/error";
6+
import { handleApiError } from "../utils/error";
77
import { log } from "../utils/common";
88

99
const scriptName = "utils-status";
@@ -12,8 +12,8 @@ const logger = log.getLogger(scriptName);
1212
const WAIT_TIME = 10000; // 10 seconds
1313
const MAX_RETRIES = 30;
1414
export async function checkTransactionStatus(
15-
exchangeAPI: ExchangeApi,
16-
request: GetStatusRequest,
15+
exchangeAPI: ExchangeApi,
16+
request: GetStatusRequest,
1717
): Promise<void> {
1818
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
1919
try {
@@ -30,13 +30,13 @@ export async function checkTransactionStatus(
3030
logger.info(`Current approval status: ${approvalStatus.status}`);
3131
if (attempt < MAX_RETRIES - 1) {
3232
logger.debug(
33-
`Waiting for ${WAIT_TIME / 1000} seconds before retry ${attempt + 1} of ${MAX_RETRIES}`,
33+
`Waiting for ${WAIT_TIME / 1000} seconds before retry ${attempt + 1} of ${MAX_RETRIES}`,
3434
);
3535
await delay(WAIT_TIME);
3636
}
3737
} catch (error) {
3838
logger.warn(
39-
`Failure at ${scriptName} - Attempt ${attempt + 1} of ${MAX_RETRIES}. Retrying...`,
39+
`Failure at ${scriptName} - Attempt ${attempt + 1} of ${MAX_RETRIES}. Retrying...`,
4040
);
4141
if (attempt < MAX_RETRIES - 1) {
4242
await delay(WAIT_TIME);
@@ -46,10 +46,10 @@ export async function checkTransactionStatus(
4646
}
4747
}
4848
throw new Error(
49-
`Transaction status not completed after ${MAX_RETRIES} attempts`,
49+
`Transaction status not completed after ${MAX_RETRIES} attempts`,
5050
);
5151
}
5252

5353
function delay(ms: number) {
54-
return new Promise(resolve => setTimeout(resolve, ms));
55-
}
54+
return new Promise((resolve) => setTimeout(resolve, ms));
55+
}

src/main/endpoints/wallet.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,22 @@ import {
55
parseUnits,
66
} from "ethers";
77
import { log } from "../utils/common";
8-
import type { TransactionRequest, EvmTransactionRequest } from "@blockdaemon/blockdaemon-defi-api-typescript-fetch";
8+
import type {
9+
TransactionRequest,
10+
EvmTransactionRequest,
11+
} from "@blockdaemon/blockdaemon-defi-api-typescript-fetch";
912

1013
const logger = log.getLogger("wallet");
1114

12-
function isEvmTransaction(tx: TransactionRequest): tx is (EvmTransactionRequest & { chainType: 'evm' }) {
13-
return tx.chainType === 'evm';
15+
function isEvmTransaction(
16+
tx: TransactionRequest,
17+
): tx is EvmTransactionRequest & { chainType: "evm" } {
18+
return tx.chainType === "evm";
1419
}
1520

1621
function removeEIPPrefix(chainId: string): number {
17-
if (chainId.startsWith('eip155:')) {
18-
return parseInt(chainId.split(':')[1]);
22+
if (chainId.startsWith("eip155:")) {
23+
return parseInt(chainId.split(":")[1]);
1924
}
2025
return parseInt(chainId);
2126
}
@@ -26,7 +31,7 @@ export async function signAndBroadcastTransaction(
2631
rpcUrl: string,
2732
): Promise<TransactionResponse> {
2833
if (!isEvmTransaction(transactionRequest)) {
29-
throw new Error('Only EVM transactions are supported');
34+
throw new Error("Only EVM transactions are supported");
3035
}
3136

3237
const chainId = removeEIPPrefix(transactionRequest.chainID);
@@ -49,7 +54,7 @@ export async function signAndBroadcastTransaction(
4954

5055
try {
5156
logger.info(
52-
`Signing and Broadcasting EVM transaction on chain ${chainId} from ${txObject.from} to ${txObject.to} with value ${txObject.value}...`,
57+
`Signing and Broadcasting EVM transaction on chain ${chainId} from ${txObject.from} to ${txObject.to} with field value ${txObject.value}...`,
5358
);
5459
const receipt = await wallet.sendTransaction(txObject);
5560

0 commit comments

Comments
 (0)