Which language?
I can give a very basic example of calling functions using Web3 in Python. Web3 is available in pretty much all mainstream languages and method names are consistent in each.
I suggest you simply do the tutorial in whatever language are comfortable in and get connected with sending a transaction but the basic gist is
- make a connection to the chain
- create a contract object with the address and abi
- interact.
# example calling a normal (call) read function (decimals) that has no cost and
# a write (transaction) function (approve) that charges a fee so requires wallet
# credentials and a transaction to be built, signed and sent.
from web3 import Web3
# connect to harmony
wss_url = "wss://ws.s0.t.hmny.io"
w3 = Web3(Web3.WebsocketProvider(wss_url))
# ABI with 2 functions `decimals` and `approve` used for the demo
abi = [
{
"constant": True,
"inputs": [],
"name": "decimals",
"outputs": [{"internalType": "uint8", "name": "", "type": "uint8"}],
"payable": False,
"stateMutability": "view",
"type": "function",
},
{
"constant": False,
"inputs": [
{"internalType": "address", "name": "spender", "type": "address"},
{"internalType": "uint256", "name": "amount", "type": "uint256"},
],
"name": "approve",
"outputs": [{"internalType": "bool", "name": "", "type": "bool"}],
"payable": False,
"stateMutability": "nonpayable",
"type": "function",
},
]
# Setup wallet to use
p_key = "WALLET PRIVATE KEY"
wallet = w3.eth.account.privateKeyToAccount(p_key).address
print(wallet)
# Setup token address and create a contract object
token_address = "token contract address 0x..."
contract = w3.eth.contract(address=token_address, abi=abi)
# call decimals function
decimals = contract.functions.decimals().call()
print(decimals) # i.e. 18
def approve(
amount: int,
contract: str,
wallet_address: str,
private_key: str,
) -> str:
# Convret to Wei and get nonce
max_amount = w3.toWei(amount, "ether")
nonce = w3.eth.getTransactionCount(wallet_address)
# Build transaction using the function and arguments prior
tx = contract.functions.approve(wallet_address, max_amount).buildTransaction(
{
"from": wallet_address,
"nonce": nonce,
"chainId": 1666600000,
"gasPrice": 1000000000,
"gas": 25000,
"value": 0,
}
)
# Sign Tx and send
signed_tx = w3.eth.account.signTransaction(tx, private_key)
tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
return w3.toHex(tx_hash)
approved_tx_hash = approve(1000000000, contract, wallet, p_key)
print(approved_tx_hash)
# 0x8cda1fa7e08278dca299230c13a5146e4a13393fba235fe1a28d0d828a6c2daf