web3.js を Python で使えるようにした web3.py というのがあったので使ってみた。
send_token.py
from web3 import Web3, HTTPProvider
import json
def load_abi(self, file_path):
artifact = open(file_path, 'r')
json_dict = json.load(artifact)
abi = json_dict['abi']
return abi
file_path = 'Token.json'
contract_address = ''
from_address = '0x...'
from_address_password = ''
to_address = '0x...'
amount = 10
web3 = Web3(HTTPProvider('http://localhost:8545'))
abi = load_abi(file_path)
Token = web3.eth.contract(abi=abi, address=contract_address)
# Get balance of Token
balance = Token.call().balanceOf(from_address)
print('balance:', balance)
# Send Token
if web3.personal.unlockAccount(from_address, from_address_password, duration=hex(300)): # 300秒後にロック
print('Account unlocked')
tx_hash = Token.transact({'from': from_address}).transfer(to_address, amount)
print('tx_hash:', tx_hash)
print('Transaction complete!')
else:
print('Failed to unlock account.')
web3.js と地味に書き方が違うところがあるけど、ほぼそのまま Python で使える感じですな。感謝。