-
Notifications
You must be signed in to change notification settings - Fork 0
/
viem.ts
64 lines (58 loc) · 1.65 KB
/
viem.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
import {
createPublicClient,
createWalletClient,
http,
getContract,
erc20Abi,
parseUnits,
formatUnits,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { celoAlfajores } from "viem/chains";
import {
PRIVATE_KEY,
RECIPIENT,
USDC_TOKEN_ADDRESS,
USDC_ADAPTER_ADDRESS,
} from "./constants";
/**
* Boilerplate to create a viem client and viem-compatible wallet
*/
const read = createPublicClient({
chain: celoAlfajores,
transport: http(),
});
const write = createWalletClient({
chain: celoAlfajores, // Celo testnet
transport: http(),
});
const sender = privateKeyToAccount(`0x${PRIVATE_KEY}`);
/**
* Set up ERC20 contract
*/
const contract = getContract({
address: USDC_TOKEN_ADDRESS,
abi: erc20Abi,
client: { public: read, wallet: write },
});
/**
* Makes a transaction to transfer ERC20 tokens using a fee currency
*/
async function erc20Transfer() {
console.log(`Initiating fee currency transaction...`);
const [symbol, decimals, tokenBalance] = await Promise.all([
contract.read.symbol(),
contract.read.decimals(),
contract.read.balanceOf([sender.address]),
]);
console.log(`${symbol} balance of ${sender.address}: ${formatUnits(tokenBalance, decimals)}`);
const transactionHash = await contract.write.transfer(
[RECIPIENT, parseUnits("0.01", decimals)],
{ account: sender, feeCurrency: USDC_ADAPTER_ADDRESS }
);
console.log(`Done! Transaction hash: ${transactionHash}`);
}
// Initiate ERC20 transfer with fee currency
erc20Transfer().catch((err) => {
console.error("An error occurred:", err);
});