web3 bsc send transaction - javascript

I'm trying to send a transaction via bsc using WalletConnect and web3
This is the connection code
const provider = new WalletConnectProvider({
rpc: {
1: "https://bsc-dataseed.binance.org/",
2: "https://bsc-dataseed1.defibit.io/",
3: "https://bsc-dataseed1.ninicoin.io/",
// ...
},
});
async function() {
await provider.enable();
// Get Accounts
web3.eth.getAccounts((error, accounts) => {
if (error) alert(error)
this.account = accounts[0]
});
}
And this is the cransaction call
web3.eth.sendTransaction({
to: '0x...',
from: this.account,
value: 1000000000000, //test value
}, ((error, hash) => {
if (error) alert(error)
else console.log(hash)
}));
The problem is that on my trust wallet the transaction is on the ETH blockchain, even if I can read my bsc token balance correctly.
Any ideas?

Related

How to make a post request by SERVER not by user

Node.js CODE
exports.user = async (req, res) => {
try {
const { wallet } = req.body;
if (!wallet) {
res.status(400).json({ error: "Not logged in" });
return;
} else {
user = User.findone(wallet);
// if user is not found then create a new user and mark as loggged In
if (!user) {
User.create({
user: wallet,
});
}
// if user found then create a session token and mark as logged
in
res.send({
user: wallet,
});
}
} catch (error) {
console.log(`ERROR::`, error);
}
};
REACTJs CODE
// post call/update
const axiosCall = async () => {
// core login will give a unique username by fulling a transcation
// core.login i dont have any control
const userAccount = await core.login();
try {
const res = await Axios.post(`${API}/user`, userAccount, dataToken);
setData({
...data,
error: "",
success: res.data.message,
});
} catch (error) {
setData({
...data,
error: error.response.data.error,
});
}
};
Now here the problem occurs when some one could modify userAccount in the front-end or someone could send a body with wallet: anything to my route localhost:3000/api/user
There is no option for me to check if some actually used core.login(); to get the wallet address.
So is there any solution?
I was thinking to allow only my server IP or localhost to hit the route localhost:3000/api/user and is that even possible?
Also there is another issue anyone could modify userAccount in front-end.

NodeJS: Firebase Admin SDK is not initializing

I am trying to run the below cod which initialises the Firebase Admin SDK, and send a notification message.
const admin = require('firebase-admin/app');
const errorCodes = require('source/error-codes');
const PropertiesReader = require('properties-reader');
const prop = PropertiesReader('properties.properties');
exports.sendSingleNotification = async (event, context) => {
const params = event.queryStringParameters;
var serviceAccount = require("xxx-xxx-firebase-adminsdk-xxx-xxx.json");
try {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
console.log("INITIALIZED");
// This registration token comes from the client FCM SDKs.
const registrationToken = params.fcmtoken;
console.log()
const message = {
notification: {
title: 'FooCorp up 1.43% on the day',
body: 'FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin.getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
return {"response":response}
})
.catch((error) => {
console.log('Error sending message:', error);
return {"error 1":error}
});
} catch (error) {
console.log(error);
return {"error 2":error}
}
};
Here the serviceAccount means the path of the Firebase private key file which is in the root of this project.
However when I run this code I always end up with the following error.
START RequestId: e66ffdd9-ab9c-4a68-ade2-7cfa97f42c31 Version: $LATEST
at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)] (/var/task/source/fcm/send-single-notification.js:14:42)rt' of undefined
END RequestId: e66ffdd9-ab9c-4a68-ade2-7cfa97f42c31
Something is undefined and I can't figure out what it is or what the error is.
How can I fix this?

Web3js signTransation

I am following the documentation to be able to sign and send a transaction on the Kovan testnet. I am currently getting an undefined value when I console out the txHash.
web3.eth.getTransactionCount(account1, (err, txCount) => {
// 1)Build Transaction
const txObject = {
nonce: web3.utils.toHex(txCount),
to: account2,
value: web3.utils.toHex(web3.utils.toWei('0.05', 'ether')),
gasLimit: web3.utils.toHex(2100),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
}
// 2)Sign Transaction
const tx = new Tx(txObject,{'chain':42})
tx.sign(privateKey1)
const serializedTransaction = tx.serialize()
const raw = '0x' + serializedTransaction.toString('hex')
console.log("raw:", raw)
console.log("tx:", serializedTransaction)
// 3)Broadcast Transaction
web3.eth.sendSignedTransaction(raw, (err, txHash) =>{
console.log('txHash:', txHash)
})
// COMMENTED-OUT web3.eth.sendSignedTransaction('0x' + serializedTransaction .toString('hex'))
// .on('receipt', console.log);
})
signTransaction() only performs the signature. It doesn't broadcast the (signed) transaction to the network.
For that, you can use sendSignedTransaction() (docs), which submits the (signed and serialized) tx data to the provider, and the provider broadcasts it to the network.
web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('receipt', console.log);

Trust wallet dapp connect and sign transfer message

I connect trust wallet like this:
//**Connect wallet:**
import WalletConnect from "#walletconnect/client";
import QRCodeModal from "#walletconnect/qrcode-modal";
const connector = new WalletConnect({
bridge: "https://bridge.walletconnect.org", // Required
qrcodeModal: QRCodeModal,
});
document.onreadystatechange = () => {
// Create a connector
// Check if connection is already established
if (!connector.connected) {
// create new session
connector.createSession();
}
}
When wallet connected I tried to sign a transfer message to transfer coins (I've tried with binance chain and thorchain - not working)
This is example how I sign msg:
const network = 931; // thorchain(rune)
const tx = {
fee: {
amounts: [
{
denom: "rune",
amount: "0.01"
}
],
gas: "2000000"
},
memo:"test",
"messages":[{
"sendCoinsMessage": {
fromAddress: 'thor1mkda02h8hsevykxwnnxs93tgtvgtz5djxteat0',
toAddress: "thor1mkda02h8hsevykxwnnxs93tgtvgtz5djxteat0",
amounts: [
{
denom: "rune",
amount: "1"
}
],
}
}]//end
};
Then I format request and sign it:
const request = self.connector._formatRequest({
method: 'trust_signTransaction',
params: [
{
network,
transaction: JSON.stringify(tx),
},
],
});
connector
._sendCallRequest(request)
.then(result => {
// Returns transaction signed in json or encoded format
console.log(result);
})
.catch(error => {
// Error returned when rejected
console.log('error')
console.error(error);
});
},
This is what I see in my trust wallet:
As a response I get from console this:
{"mode":"block","tx":{"fee":{"amount":[],"gas":"0"},"memo":"","msg":[],"signatures":[{"pub_key":{"type":"tendermint/PubKeySecp256k1","value":"A2yB9NhfIeEwTEDbs0ssZQcqtL/OWGuHqooeFllERot3"},"signature":"+kO2W2MfcSBwgLUF3zJUQK4e01YvIGXK8juzojEkE/RrVgrZJPRsthweuto4FJ1QK/MjUWuGlJiC+MjktlBexA=="}]}}
But the transaction is not sent to blockchain (If I go to blockchain exlorer I will not find it)
Also as you can notice in the response from console fee and gas always 0
What do I do?
UPD I have also tried method trust_sendTransaction instead of trust_signTransaction but didn't help

Unable to connect to Room: Invalid Access Token issuer/subject twilio

I do want to create an access token in the backend and need to pass to the front end to connect to the video chat room.
This is my back-end code
const twilioAccountSid = process.env.twilioAccountSid;
const twilioApiKey = process.env.twilioApiKey;
const twilioApiSecret = process.env.twilioApiSecret;
const room = "cool room";
app.post("/access-token", (req, res) => {
try {
console.log(
"sid",
twilioAccountSid,
"key",
twilioApiKey,
"secret",
twilioApiSecret
);
const identity = "user";
// Create Video Grant
const videoGrant = new VideoGrant({
room,
});
// Create an access token which we will sign and return to the client,
// containing the grant we just created
const token = new AccessToken(
twilioAccountSid,
twilioApiKey,
twilioApiSecret,
{ identity: identity }
);
token.addGrant(videoGrant);
// Serialize the token to a JWT string
console.log(token.toJwt());
res.status(200).json(token.toJwt());
} catch (error) {
console.warn(error);
res.sendStatus(500);
}
});
For the Twilio account SID I used my dashboard's SID which is starting from AC
For the API key I added the friendly name I gave to the API key when I created it.
API secret is that API key's secret id.
A token is crearted succefully and passed to the front-end.
This is my front-end code
const connectRoom = async () => {
try {
const token = await axios.post("http://localhost:5000/access-token");
connect(token.data, { name: roomName, video: { width: 640 } }).then(
(room) => {
console.log(`Successfully joined a Room: ${room}`);
room.on("participantConnected", (participant) => {
console.log(`A remote Participant connected: ${participant}`);
participant.tracks.forEach((publication) => {
console.log("for each");
if (publication.isSubscribed) {
const track = publication.track;
document
.getElementById("remote-media-div")
.appendChild(track.attach());
}
});
participant.on("trackSubscribed", (track) => {
document
.getElementById("remote-media-div")
.appendChild(track.attach());
});
});
},
(error) => {
console.error(`Unable to connect to Room: ${error.message}`);
}
);
} catch (error) {
console.log(error);
}
Then I get this error
Unable to connect to Room: Invalid Access Token issuer/subject
How do I solve this problem?
Any help!
Thanks in advance
You can create an API Key here (or via the Console). Note, the API Key starts with SK....
REST API: API Keys

Categories