Ich versuche, Token Balance mit einfachem Javascript zu erhalten, ohne nodejs oder web3.
Mit web3 und nodejs kann ich tun:
exports.getTokenConfirmedBalance = function(node, query, abi) {
return new Promise((resolve, reject) => {
try {
var provider = new web3.providers.HttpProvider(node.url);
var w3 = new web3(provider);
var tokenContract = new w3.eth.Contract(abi, query.token_address, {from: query.pub_address});
tokenContract.methods.balanceOf(query.pub_address).call().then(function (balance) {
resolve(balance);
}).catch(function(error) {
reject(error)
})
} catch(error) {
console.log(error);
reject(error.message);
}
})
}
Irgendwelche Vorschläge?
Verwendung eth_call
:
const tokenAddress = "0x123abc";
const account = "0x456def";
// Hex encoding needs to start with 0x.
// First comes the function selector, which is the first 4 bytes of the
// keccak256 hash of the function signature.
// ABI-encoded arguments follow. The address must be left-padded to 32 bytes.
const data = '0x' +
keccak_256.hex('balanceOf(address)').substr(0, 8) +
'000000000000000000000000' + account.substr(2); // chop off the 0x
// You can send this to any node.
fetch('https://mainnet.infura.io/APIKeyGoesHere', {
method: 'POST',
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "eth_call",
params: [{
to: tokenAddress,
data: data,
}, 'latest'],
}),
headers: new Headers({
'Content-Type': 'application/json'
}),
}).then(response =>
response.json()
).then(json =>
console.log(json.result)
);
getTokenBalance
?balanceOf
das verfügbar ist, da es Teil der Schnittstelle eines ERC20-Tokens ist.d
und 4
gegen Ende. Aber vorausgesetzt, das ist ein seltsames Artefakt des Kopierens / Einfügens und Sie haben tatsächlich 66 Zeichen ( 0x
und dann 64 Zeichen danach), dann haben Sie, was Sie wollen. Analysieren Sie es einfach als Hexadezimalzahl. parseInt('0x00...', 16)
sollte arbeiten.0x
Präfix hat. In diesem Fall möchten Sie verwenden keccak_256.hex('balanceOf(address)').substr(0, 10)
, um den richtigen Funktionsselektor zu erhalten, nämlich 0x70a08231
.Sie können auch die Etherscan-API verwenden!
Benutzer19510
keccak256("balanceOf(address)")
gefolgt von der Adresse sein, alles hex-kodiert.