首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用erc20进行web3py传输

用erc20进行web3py传输
EN

Ethereum用户
提问于 2020-08-02 23:02:58
回答 2查看 2.1K关注 0票数 7

如何在erc20中发送web3py,我有:

tx_hash = contract.functions.transfer(destination_address, value).transact({'from': myaddress })

我得到了一个错误:

ValueError:{“代码”:-32601,“消息”:“方法eth_sendTransaction不存在/不可用”}

我想我错过了签约或者类似的事情,我怎样才能成功的进行erc20的转会。

EN

回答 2

Ethereum用户

回答已采纳

发布于 2020-08-04 00:15:25

transact()要求节点使用eth_sendTransaction对事务进行签名。因为他们没有你的钥匙。

相反,您可以使用使用契约对象创建未经签名的事务。,比如:

代码语言:javascript
运行
复制
contract_call = contract.functions.transfer(destination_address, value)
unsigned_txn = contract_call.buildTransaction({'chainId': 1, 'gasPrice': w3.toWei(100, 'gwei')})

然后,您可以使用您的私钥签署事务,并广播它:

代码语言:javascript
运行
复制
signed_txn = w3.eth.account.sign_transaction(unsigned_txn, private_key=private_key)
w3.eth.sendRawTransaction(signed_txn.rawTransaction)
票数 4
EN

Ethereum用户

发布于 2022-04-21 11:22:21

下面是一个在现代web3.py中执行ERC-20传输的脚本:

代码语言:javascript
运行
复制
"""Manual transfer script.

- For a hardcoded token, asks to address and amount where to transfer tokens.

- Waits for the transaction to complete
"""
import datetime
import os
import sys
from decimal import Decimal

from eth_account import Account
from eth_account.signers.local import LocalAccount
from web3 import HTTPProvider, Web3
from web3.middleware import construct_sign_and_send_raw_middleware

from eth_defi.abi import get_deployed_contract
from eth_defi.token import fetch_erc20_details
from eth_defi.txmonitor import wait_transactions_to_complete

# What is the token we are transferring.
# Replace with your own token address.
ERC_20_TOKEN_ADDRESS = "0x0aC7B3733cBeE5D87A80fbf331f4A0bD01f17386"

# Connect to JSON-RPC node
json_rpc_url = os.environ["JSON_RPC_URL"]
web3 = Web3(HTTPProvider(json_rpc_url))
print(f"Connected to blockchain, chain id is {web3.eth.chain_id}. the latest block is {web3.eth.block_number:,}")

# Read and setup a local private key
private_key = os.environ.get("PRIVATE_KEY")
assert private_key is not None, "You must set PRIVATE_KEY environment variable"
assert private_key.startswith("0x"), "Private key must start with 0x hex prefix"
account: LocalAccount = Account.from_key(private_key)
web3.middleware_onion.add(construct_sign_and_send_raw_middleware(account))

# Show users the current status of token and his address
erc_20 = get_deployed_contract(web3, "ERC20MockDecimals.json", ERC_20_TOKEN_ADDRESS)
token_details = fetch_erc20_details(web3, ERC_20_TOKEN_ADDRESS)

print(f"Token details are {token_details}")

balance = erc_20.functions.balanceOf(account.address).call()
eth_balance = web3.eth.getBalance(account.address)

print(f"Your balance is: {token_details.convert_to_decimals(balance)} {token_details.symbol}")
print(f"Your have : {eth_balance/(10**18)} ETH for gas fees")

# Ask for transfer details
decimal_amount = input("How many tokens to transfer? ")
to_address = input("Give destination Ethereum address? ")

# Some input validation
try:
    decimal_amount = Decimal(decimal_amount)
except ValueError as e:
    raise AssertionError(f"Not a good decimal amount: {decimal_amount}") from e

assert web3.isChecksumAddress(to_address), f"Not a valid address: {to_address}"

# Fat-fingering check
print(f"Confirm transfering {decimal_amount} {token_details.symbol} to {to_address}")
confirm = input("Ok [y/n]?")
if not confirm.lower().startswith("y"):
    print("Aborted")
    sys.exit(1)

# Convert a human-readable number to fixed decimal with 18 decimal places
raw_amount = token_details.convert_to_raw(decimal_amount)
tx_hash = erc_20.functions.transfer(to_address, raw_amount).transact({"from": account.address})

# This will raise an exception if we do not confirm within the timeout
print(f"Broadcasted transaction {tx_hash.hex()}, now waiting 5 minutes for mining")
wait_transactions_to_complete(web3, [tx_hash], max_timeout=datetime.timedelta(minutes=5))

print("All ok!")

有关详细信息,请参阅完整的ERC-20传输教程.

票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/86459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档