-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbuildTransaction.ts
76 lines (67 loc) · 2.37 KB
/
buildTransaction.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { BigNumber } from "@ethersproject/bignumber";
import { Router as FibrousRouter } from "fibrous-router-sdk";
import { parseUnits } from "ethers";
import { account } from "./account";
// RPC URL for the Scroll network, you can change this to the RPC URL of your choice
const rpcUrl = "https://rpc.scroll.io";
// Destination address for the swap (required)
const destination = "<DESTINATION_ADDRESS>";
// Private key of the account that will be used to sign the transaction
const privateKey = "<PRIVATE_KEY>";
async function main() {
// Create a new router instance
const fibrous = new FibrousRouter();
// Create a new contract instance
const account0 = account(privateKey, rpcUrl);
const contractwwallet = await fibrous.getContractWAccount(
account0,
"scroll",
);
// Build route options
const tokens = await fibrous.supportedTokens("scroll");
/**
* recommended that use the token address directly
* because there may be more than one token with the same symbol.
*/
const tokenInAddress = tokens.get("usdt")?.address;
const tokenOutAddress = tokens.get("usdc")?.address;
const tokenInDecimals = Number(tokens.get("usdt")?.decimals);
if (!tokenInAddress || !tokenOutAddress || !tokenInDecimals) {
throw new Error("Token not found");
}
const inputAmount = BigNumber.from(parseUnits("5", tokenInDecimals));
// Call the buildTransaction method in order to build the transaction
// slippage: The maximum acceptable slippage of the buyAmount amount.
const slippage = 1;
const swapCall = await fibrous.buildTransaction(
inputAmount,
tokenInAddress,
tokenOutAddress,
slippage,
destination,
"scroll",
);
const approveResponse = await fibrous.buildApproveEVM(
inputAmount,
tokenInAddress,
account0,
"scroll",
);
if (approveResponse === true) {
try {
const tx = await contractwwallet.swap(
swapCall.route,
swapCall.swap_parameters,
);
await tx.wait();
console.log(`https://scrollscan.com/tx/${tx.hash}`);
} catch (e) {
console.error("Error swapping tokens: ", e);
}
} else {
console.error("Error approving tokens");
}
}
main().catch((e) => {
console.error("Error: ", e);
});