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
Related
As the title suggests, I am trying to implement Stripe into my flutter app using the stripe extension for Firebase and using Javascript Firebase Cloud Functions for the server side. I believe the issue is on the server side when I try to create a customer and create a payment intent.
The server side code is here:
const functions = require("firebase-functions");
const stripe = require("stripe")("my test secret key"); // this works fine for the other stripe functions I am calling
exports.stripePaymentIntentRequest = functions.https.onRequest(
async (req, res) => {
const {email, amount} = req.body;
try {
let customerId;
// Gets the customer who's email id matches the one sent by the client
const customerList = await stripe.customers.list({
email: email,
limit: 1,
});
// Checks the if the customer exists, if not creates a new customer
if (customerList.data.length !== 0) {
customerId = customerList.data[0].id;
} else {
const customer = await stripe.customers.create({
email: email,
});
customerId = customer.data.id;
}
// Creates a temporary secret key linked with the customer
const ephemeralKey = await stripe.ephemeralKeys.create(
{customer: customerId},
{apiVersion: "2022-11-15"},
);
// Creates a new payment intent with amount passed in from the client
const paymentIntent = await stripe.paymentIntents.create({
amount: parseInt(amount),
currency: "gbp",
customer: customerId,
});
res.status(200).send({
paymentIntent: paymentIntent.client_secret,
ephemeralKey: ephemeralKey.secret,
customer: customerId,
success: true,
});
} catch (error) {
res.status(404).send({success: false, error: error.message});
}
},
);
Then my client-side code is:
try {
// 1. create payment intent on the server
final response = await http.post(
Uri.parse(
'https://us-central1-clublink-1.cloudfunctions.net/stripePaymentIntentRequest'),
headers: {"Content-Type": "application/json"},
body: json.encode({
'email': email,
'amount': amount.toString(),
}),
);
final jsonResponse = json.decode(response.body);
if (jsonResponse['error'] != null) {
throw Exception(jsonResponse['error']);
}
log(jsonResponse.toString());
//2. initialize the payment sheet
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: jsonResponse['paymentIntent'],
merchantDisplayName: 'Clublink UK',
customerId: jsonResponse['customer'],
customerEphemeralKeySecret: jsonResponse['ephemeralKey'],
style: ThemeMode.dark,
),
);
await Stripe.instance.presentPaymentSheet();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Payment completed!')),
);
} catch (e) {
if (e is StripeException) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error from Stripe: ${e.error.localizedMessage}'),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error: $e')),
);
}
}
}
I basically copied the flutter_stripe documentation to create the payment sheet with the necessary changes. Any help would be greatly appreciated!
Ok so I found what worked! I was being given a 403 status error with reason "forbidden". This meant I had to go to the google cloud console and update the permissions in the cloud functions tab.
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?
I am attempting to create a button on my dapp to send Ethereum. I would like to log a bit of the data in my own database after the transaction is successful. I don't want to log the data in my db until AFTER I know the transaction was successful. Is there a way to do this in Javascript?
Here is my code:
sendEthButton.addEventListener('click', () => {
let userETH = document.getElementById("inputId").value;
var wei_val = userETH*10e17;
var hexString = wei_val.toString(16);
ethereum
.request({
method: 'eth_sendTransaction',
params: [
{
from: accounts[0],
to: my_address,
//value: '0x6f05b59d3b20000',
value: hexString,
gasPrice: '',
gas: '',
},
],
})
.then((txHash) => console.log(txHash))
.catch((error) => console.error);
});
I know that I can test for the txHash, but that doesn't indicate whether or not the transaction was successful, just whether or not it was successfully initiated.
How can I test for a successful transaction through JS?
I'm creating a dapp that charges users a specific amount of eth depending on their input.
Whenever I attempt to create the transaction, I specify the amount of Eth in Wei. It throws an Error with no description as to why it couldn't fulfill the transaction
Error: Error Minting New NFT
at MintNewNFT (Transactions.js:68)
at Object.onClick (index.js:62)
(Line 62 is the catch block)
AmountIn is 0.02166 ETH
Here is my code :
export const MintNewNFT = async (WalletABI,address, network, mediaID, amountIn) => {
try {
//adjust this to take an argument for media id
const web3 = new Web3('https://rinkeby.infura.io/v3/key');
const weiValue = Web3.utils.toWei(amountIn.toString(), 'ether');
console.log(weiValue , mediaID);
const transactionParameters = {
to: WalletABI._address, // Required except during contract publications.
from: address, // must match user's active address.
value: weiValue.toString(),
data: web3.eth.abi.encodeFunctionCall(
{
"inputs": [
{
"internalType": "bytes32",
"name": "mediaID",
"type": "bytes32"
}
],
"name": "mintNewNFT",
"outputs": [],
"stateMutability": "payable",
"type": "function",
"payable": true
},[mediaID]),
chainId: `0x${network}`, // Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
};
// txHash is a hex string
// As with any RPC call, it may throw an error
await window.ethereum.request({
method: 'eth_sendTransaction',
params: [transactionParameters],
}).then((result) => {
// The result varies by by RPC method.
// For example, this method will return a transaction hash hexadecimal string on success.
console.log(`Transaction Result ${result}`)
})
.catch((error) => {
// If the request fails, the Promise will reject with an error.
console.log(`Transaction ERROR : ${error.message}`)
});
} catch (error) {
throw Error("Error Minting New NFT", error)
}
}
Any indication as to what I may be doing wrong would be very much appreciated
It was failing because I was using a bytes32 instead of a string for the argument. I don't know why this was a problem.
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