Eth 中 gas gasPrice gasLimit 的关系

Gas 是一个交易费用的基本单位(unit),类似电的单位“度”,比如一次链上交易可能消耗 5 度电,也就是理解为 5 Gas 电,由运行的程序决定。

GasPrice 是一个 Gas 的单价,一般用 Gwei 来形象表示 ( 但注意实际在应用程序中都是使用 Wei ),GasPrice 由用户自己设置,其大小会决定交易被处理的速度。

可以使用:Contract.GAS_PRICE

这是一张来自 https://ethgasstation.info/ 的信息,展示了 GasPrice 大小与速度的关系,它是实时变动的。

GasLimit  用户愿意为执行某个操作,或确认交易支付的最大Gas量(最少21,000)。至于花费这些Gas量是否能完成工作是不确定的(是对 Gas 大小的限制),防止一些合约 bug 比如无限循环而消耗掉账户中的所有的 ETH,Gas 消耗超过 GasLimit 时,交易会执行失败。

GasLimit 由用户自己设置,但是必须大于等于 21000 Gas unit。 

可以使用:Contract.GAS_LIMIT

(注意实际在 web3 应用程序中,调用合约方法时传递的选项 gas 代表的是 GasLimit,这点容易引起混淆)

交易费用 = 程序消耗的 Gas unit * 用户设置的 GasPrice。

( ETH 与 Gas 之间的价格转换关系 与 Ethereum Gas Price Chart )

1 ETH = 10^9 Gwei(9个0)= 10^18 Wei(18个0)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于Python的Eth代币转账实现代码示例,需要使用web3.py库: ```python from web3 import Web3 import json # 1. 连接到以太坊节点 web3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/{your-infura-project-id}')) # 2. 加载代币合约ABI with open('abi.json', 'r') as abi_definition: abi = json.load(abi_definition) # 3. 获取代币合约 contract_address = '0x1234567890123456789012345678901234567890' contract = web3.eth.contract(address=contract_address, abi=abi) # 4. 发送代币转账交易 token_sender_address = '0x1234567890123456789012345678901234567890' token_sender_private_key = '{your-private-key}' token_receiver_address = '0x0987654321098765432109876543210987654321' token_amount = 1000 gas_limit = 100000 gas_price = web3.toWei('20', 'gwei') # 获取nonce值 nonce = web3.eth.getTransactionCount(token_sender_address) # 构造交易数据 transaction = { 'nonce': nonce, 'to': contract_address, 'value': 0, 'gas': gas_limit, 'gasPrice': gas_price, 'data': contract.functions.transfer(token_receiver_address, token_amount).buildTransaction({'from': token_sender_address}).hex(), } # 对交易进行签名 signed_txn = web3.eth.account.signTransaction(transaction, private_key=token_sender_private_key) # 发送交易 tx_hash = web3.eth.sendRawTransaction(signed_txn.rawTransaction) # 等待交易被打包 tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash) # 打印交易信息 print(f'Transaction sent: {tx_hash.hex()}') print(f'Transaction receipt: {tx_receipt}') ``` 其,需要将代码的以下参数替换为实际的值: - `{your-infura-project-id}`:Infura项目ID - `abi.json`:代币合约ABI文件路径 - `contract_address`:代币合约地址 - `token_sender_address`:代币发送者地址 - `token_sender_private_key`:代币发送者私钥 - `token_receiver_address`:代币接收者地址 - `token_amount`:代币数量 - `gas_limit`:交易的gas限制 - `gas_price`:交易的gas价格 需要注意的是,这只是一个简单的示例代码,实际使用需要根据具体情况进行调整和完善。同时,在使用时需要非常小心,以免出现错误导致代币丢失。建议在测试环境进行充分的测试,确保代码的正确性和安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值