function sendTransaction() {
const CHAIN_NAME = 'near';
const [accounts, setAccounts] = React.useState(null);
const [txHash, setTxHash] = React.useState(null);
const getSerializedTransaction = async () => {
try {
const rpc = 'https://rpc.testnet.near.org';
const provider = new providers.JsonRpcProvider(rpc);
const signerId = accounts.address;
const publicKey = accounts.pubKey;
const accessKey = await provider.query(`access_key/${signerId}/${publicKey}`, '');
const actions = [
transactions.functionCall(
'increment',
{ count: 5 },
new BN('30000000000000'),
new BN(0),
),
];
const recentBlockHash = utils.serialize.base_decode(accessKey.block_hash);
const transaction = transactions.createTransaction(
signerId,
utils.PublicKey.fromString(publicKey),
'mycontract.myaccount8.testnet',
accessKey.nonce + 1,
actions,
recentBlockHash,
);
const bytes = transaction.encode();
return Buffer.from(bytes).toString('base64');
} catch (error) {
console.log(error);
}
};
async function handleGetAccount() {
try {
const accounts = await dapp.request(CHAIN_NAME, {
method: 'dapp:accounts',
});
setAccounts(accounts[CHAIN_NAME]);
} catch (error) {
alert(error.message);
}
}
async function handleSendTransaction() {
try {
const serializedTransaction = await getSerializedTransaction();
const response = await dapp.request(CHAIN_NAME, {
method: 'dapp:sendTransaction',
params: [`${serializedTransaction}`],
});
const txHash = response;
setTxHash(txHash);
} catch (error) {
console.log(error);
alert(`Error Message: ${error.message}\nError Code: ${error.code}`);
}
}
return (
<>
{accounts ? (
<>
<Button onClick={handleSendTransaction} type="button">
Send a Transaction
</Button>
<ResultTooltip style={{ background: '#3B48DF' }}>
<b>Accounts:</b> {accounts.address}
</ResultTooltip>
</>
) : (
<>
<Button onClick={handleGetAccount} type="button">
Get Account
</Button>
<div>You have to get account first!</div>
</>
)}
{txHash && (
<ResultTooltip style={{ background: '#F08080' }}>
<b>Transaction Hash:</b> {txHash}
</ResultTooltip>
)}
</>
);
}