Skip to content

Instantly share code, notes, and snippets.

@w3kim
Created October 1, 2019 02:17
Show Gist options
  • Save w3kim/f6a24385e2016413e95aec141bc743be to your computer and use it in GitHub Desktop.
Save w3kim/f6a24385e2016413e95aec141bc743be to your computer and use it in GitHub Desktop.
Using bytes32 with caver-js
const Caver = require('caver-js');
const caver = new Caver('https://api.baobab.klaytn.net:8651');
const acct = caver.klay.accounts.privateKeyToAccount('your_private_key')
caver.klay.accounts.wallet.add(acct)
/*
We will use the following contract to demonstrate the use of bytes32:
pragma solidity 0.4.24;
contract StringStorage {
bytes32 storedData;
function set(bytes32 x) public {
storedData = x;
}
function get() public view returns (bytes32) {
return storedData;
}
}
*/
// Use the following ABI for the above contract
const ABI = [
{
"constant": false,
"inputs": [
{
"name": "x",
"type": "bytes32"
}
],
"name": "set",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "get",
"outputs": [
{
"name": "",
"type": "bytes32"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
];
// assume there is a StringStorage contract deployed at 0x9252098B64E6904Fe9Cf4C8F5785e567869F4a21
async function test() {
const contract = new caver.klay.Contract(ABI, '0x9252098B64E6904Fe9Cf4C8F5785e567869F4a21');
const hexText = caver.utils.asciiToHex('test'); // Note that `fromAscii` is deprecated
const padded = caver.utils.padRight(hexText, 64); // Right padding
const txSet = contract.methods.set(padded);
txSet.send({
from: acct.address,
gas: 3000000
})
.on('transactionHash', function(hash) {
console.log(">>> tx_hash: ", hash);
})
.on('receipt', function(receipt) {
console.log(">>> receipt: ", receipt);
})
.on('error', function (err) {
console.log(err);
})
}
test();
@aeharvlee
Copy link

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment