Engineering Notes

孟斌的小站

技术博客与学习记录

共 608 篇文章 标签与分类索引已启用

Web3.js常用API:发送交易

1. 使用本地钱包进行转账

import { Web3 } from 'web3';

const web3 = new Web3('https://sepolia.infura.io/v3/YOUR_INFURA_ID')
// 从私钥导入账户
const account = web3.eth.accounts.wallet.add('YOUR_PRIVATE_KEY')

// 查询当前账户余额
const balance = await web3.eth.getBalance(account[0].address)
const balanceEth = await web3.utils.fromWei(balance,'ether');
console.log('余额:',balanceEth,'ETH')

// 构造交易
const transaction = {
    nonce: await web3.eth.getBlockTransactionCount(account[0].address), // 代表从特定地址发送的交易数量。每次交易被成功地打包进区块后,从该地址发出交易的nonce就会增加。防止同一笔交易因意外导致执行多次。
    from:account[0].address,                                            // 发送地址
    to:'0x668E1d61eB2872D4bF6dd17D32DC5f1FD993A6AD',                    // 接收地址
    value: web3.utils.toWei('0.000045', 'ether'),                       // 转账金额
    gasPrice:gasPrice,                                                  // 当前gas价格
}
// 预估gas
const gas = await web3.eth.estimateGas(transaction)
console.log('预计耗费gas:', gas)
transaction.gas = gas                                                   // 最大gas,交易完成如有剩余会返还,不足会导致交易回滚
web3.eth.sendTransaction(transaction).then(console.log);

2. 发送原始交易

import { Web3 } from 'web3';

const web3 = new Web3('https://ethereum-sepolia.publicnode.com');
// 创建账户
const account = web3.eth.accounts.privateKeyToAccount('0x3afbb985211d17b9cdb5b3e7fd9f1017952d19275b4f6d31ed9f15bffb2e6185')
// 构建原始交易
const rawTransaction = {
    from: account.address,
    to:'0x668E1d61eB2872D4bF6dd17D32DC5f1FD993A6AD',
    nonce: await web3.eth.getTransactionCount(account.address),
    value:10,
    gasPrice:gasPrice,
    data: "0x0" 
}
// 预估gas
const gas = await web3.eth.estimateGas(rawTransaction)
console.log('预计耗费gas:', gas)
rawTransaction.gas = gas 

// 使用私钥对交易进行签名
const signedTransaction = await web3.eth.accounts.signTransaction(rawTransaction, account.privateKey);
// 发送交易
const txReceipt = await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);
console.log('Transaction Receipt:', txReceipt);

孟斯特

声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)进行许可,使用时请注明出处。

继续阅读

Web3连接以太网

1. Infura

Infura 是一种托管服务,提供对各种区块链网络的安全可靠访问,消除了管理区块链基础设施的复杂性,使开发者能够专注于构建创新的 Web3 应用程序。

继续阅读

HD钱包和BIP32、BIP44、BIP39

1. 钱包

1.1 数字钱包

数字钱包是一种让用户以数字方式存储、跟踪、转账和接收货币的系统。其货币可以是数字资产如比特币,道格币等等,也可以是数字化的法定货币如美元和欧元等。

继续阅读

WebSocket

什么是WebSocket?

WebSocket是一种网络通信协议,它提供了一种在单个长连接上进行全双工通讯的方式。与传统的HTTP请求只能由客户端发起并由服务器响应不同,WebSocket允许服务器主动向客户端发送消息,实现了真正的双向交互。这一协议在2009年被提出,并随后成为国际标准。

go
继续阅读

G4F

What is G4F?

G4F,即GPT4Free的简称,是一个强大的大型语言模型命令行界面(LLM-CLI),其使命是去中心化并提供免费访问先进AI技术的途径。G4F旨在通过提供一个用户友好且高效的工具来与最先进的语言模型进行互动,从而使AI大众化。

继续阅读