# 前端web3入门脚本一:如何用JS代码创建钱包并转账 **Published by:** [Bot80926](https://paragraph.com/@bot80926/) **Published on:** 2023-05-04 **URL:** https://paragraph.com/@bot80926/web3-js ## Content 前言博客一转眼停更快两年了,一方面是因为博主本身工作较忙,自己也在快速学习很多知识,但回过头发现疏于整理,还是需要一个地方定期的整理回顾知识点。重启博客第一也是方便自己做一个知识的梳理,第二也是因为最近招人的时候发现web3的前端算是比较稀缺的岗位,作为一个在web3摸爬滚打快5年的老人,也想帮助更多想了解web3的前端朋友能找到一个舒服的学习路径。总而言之,all in crypto, all for crypto.技术栈: javascript / nodeJS主要用到的库: ethers(注意用^4.0.0版本,version5的代码结构和4相差较大,且文档还不完善)、 fs(用于写入文件,存储数据,当然也有其他实现,你用的舒服就好)一、创建钱包const wallet = ethers.Wallet.createRandom(); const pv = wallet.privateKey; const address = wallet.address; 二、存储数据fs.writeFile(`./addr_key_book.txt`, list, (error) => { if (error) { return console.log("create wallet failed, error: ", error); } console.log(chalk.green("Successfully created wallets in batches, file name: addr_key_book.txt")); }); 三、向其他钱包转账第一步:选一个上面我们生成的钱包的私钥来创建一个钱包实例, 这里我们选用KCC测试链( Kucoin Community Chain Testnet ),作为举例。原因是该链测试成本低,水龙头币相对于eth goerli 容易领取,都是evm兼容,可以在KCC链上调试好脚本再无缝迁移到以太坊网络上 。const wallet = new ethers.Wallet('replace with your private key', new Provider({ chain: "kcc", chainId: 322, fullnode: "https://rpc-testnet.kcc.network", }).getProvider()); 第二步: 发送原生代币(区分链原生代币和ERC20标准代币的转账方式不同)原生代币转账方式: wallet.sendTransactionconst sendBaseToken = async (to, amount) => { const tx = await wallet.sendTransaction({ to, value: ethers.utils.parseEther(amount), }); tx.wait(1); console.log(chalk.green(`Successfully sent ${amount} Base Token to ${to}, detail: https://scan-testnet.kcc.network/tx/${tx.hash}`)); return tx; }; 第三步: 发送ERC20标准代币 并自定义gas fee自定义gas fee:这里gasPrice设置为1 Gwei = 10 ** 9,fee 上限 = gasPrice * gasLimit / 10 ** 18 = 0.0005‘0x’ + 1000000000.toString(16) = 0x3b9aca00parseInt(‘0x3b9aca00’) = 0x3b9aca00override gasPrice and gasLimit const overrides = { gasPrice: "0x3b9aca00", // "1000000000", gasLimit: "0x7a120" // "500000", } ERC20代币转账方式: contract.transfer(to, amount, overrides); // overrides is optional完整转账代码段const sendErc20 = async (to, amount, contractAddress) => { //生成对应erc20合约实例 const contract = new ethers.Contract(contractAddress, erc20Abi, wallet); const tx = await contract.transfer(to, ethers.utils.parseEther(amount).toString(), overrides); // overrides is optional tx.wait(1); console.log(chalk.green(`Successfully sent ${amount} ERC20 to ${to}, detail: https://scan-testnet.kcc.network/tx/${tx.hash}`)); return tx; }; 完整代码链接:script-1-create-walletscript-2-transfer-token最新开的Github账号,以后会持续迭代更新。欢迎 follow/fork/star/issue… ## Publication Information - [Bot80926](https://paragraph.com/@bot80926/): Publication homepage - [All Posts](https://paragraph.com/@bot80926/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@bot80926): Subscribe to updates