injection - How user can pay custom value of ETH with metamask API? - javascript

I want to give user possibility to choose his own value of Ether. How to do this?
How efficiently change the network when pressing connect to metamask (for example when user will press this button metamask should change network to binance smart chain (ID 56)
here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/web3#latest/dist/web3.min.js"></script>
</head>
<body>
<div>
<button class="enableEthereumButton btn">Enable Ethereum</button>
<button class="sendEthButton btn">Send Eth</button>
<div id="status"></div>
</div>
<script type="text/javascript">
// Running on the page, in the browser
if (typeof window.ethereum !== 'undefined') {
console.log('MetaMask is installed!');
}
if (!ethereum || !ethereum.isMetaMask) {
throw new Error('Please install MetaMask.')
}
/*********************************************************/
/* Handle chain (network) and chainChanged, per EIP 1193 */
/*********************************************************/
// Do this:
ethereum.on('chainChanged', (chainId) => {
/* handle the chainId */
});
const ethereumButton = document.querySelector('.enableEthereumButton');
const sendEthButton = document.querySelector('.sendEthButton');
let accounts = [];
//Sending Ethereum to an address
sendEthButton.addEventListener('click', () => {
ethereum
.request({
method: 'eth_sendTransaction',
params: [
{
from: accounts[0],
to: '0x6adress.................',
value: '0x00',
gasPrice: '0x0000001F6EA08600',
gas: '0x0001ADB0',
},
],
})
.then((txHash) => console.log(txHash))
.catch((error) => console.error);
});
ethereumButton.addEventListener('click', () => {
getAccount();
});
async function getAccount() {
accounts = await ethereum.request({ method: 'eth_requestAccounts' });
}
</script>
</body>
</html>
Metamask screenshot

Add an input field for the value and pass it in to your params. This is basic html form + javascript interactions, not specific to web3, so for more info on how to do that I would look here https://www.w3schools.com/html/html_forms.asp
To read the network the user is connecting with in your app you can listen for a chain change event: https://docs.metamask.io/guide/ethereum-provider.html#events
Then if they are not connected to a network your app supports you should show the user a notice.

Related

Saving local storage is being flaky - Cypress

I saw some other posts about local storage but they all relate to tokens and login.
We have an iframe that gets created and pops in from the right on our site upon first visit, I'm trying to keep this iframe from ever opening. A dev put an identifier in place for me to tell it's my Cypress test and to not fire the iframe but it's flaky.
I am using the plugin https://www.npmjs.com/package/cypress-localstorage-commands to handle my local storage.
This is in my Command file:
import "cypress-localstorage-commands";
In my test, I have the following:
beforeEach(() => {
cy.restoreLocalStorage();
cy.setLocalStorage('is_cypress_test', 'true');
})
afterEach(() => {
cy.saveLocalStorage();
})
However, this frequently fails and the iframe opens. When it works, it also prints out to console that Cypress was detected (this is something added on our sites code to verify it was working).
Here is the basic look of my test.
/// <reference types="Cypress" />
describe(`it browses to xxxx`, () => {
// sets up service cookie to preserve session
Cypress.Cookies.defaults({
preserve: 'foo',
});
beforeEach(() => {
cy.setLocalStorage('is_cypress_test', 'true');
cy.restoreLocalStorage();
})
afterEach(() => {
cy.saveLocalStorage();
})
it(`should log in via a POST, and browse xxx`, () => {
cy.serviceLoginByCSRF(Cypress.env('user_name'), Cypress.env('password'));
cy.visit('/#/asitepage');
});
describe(`it checks all xxxxx`, () => {
it(`should verify xxxxxx`, () => {
cy.get('h3').should('be.visible').invoke('text').then(data => {
let regex = /\n|\*|Back/g;
cy.textCleanup(data, regex).should('eq', 'bar');
});
});
});
describe(`it checks all yyyy`, () => {
it(`should verify yyyy`, () => {
cy.get('h3').should('be.visible').invoke('text').then(data => {
let regex = /\n|\*|Back/g;
cy.textCleanup(data, regex).should('eq', 'foo');
});
});
});
});
Beamer code
<!-- Beamer for product updates -->
<script>
var beamer_config = {
product_id: "foobar",
selector: "#beamer",
user_email: 'example#test.blogspot.gov',
user_firstname: 'Hank',
user_lastname: 'Williams',
filter: 'production',
onopen: function(){
// localStorage.setItem("is_cypress_test", "true") -- is test
if(localStorage.getItem("is_cypress_test")){
console.log("Skipping beamer load for Cypress");
return false;
}
}
};
</script>
<script type="text/javascript" src="https://asite.js" defer="defer"></script>
<!-- // Beamer for product updates -->
I'm wondering if I'm setting this in the wrong way, or wrong area?
Any help, or notes on how best to use this so it will always have that in localStorage before every test would be greatly appreciated.
Thoughts?
Thanks
Had the same issue, what fixed it for me was adding the following code to commands.js:
Cypress.LocalStorage.clear = function (keys, ls, rs) {
return;
}

Cannot get flask-talisman to allow Firebase to run

I cannot get the Firebase "Sign in with Google" button to work using flask-talisman. Here is my CSP:
I am not sure if I a missing the right items for 'script-src'. One thing I do know is that if I remove this CSP from my application completely, everything works as normal. So I believe the Firebase issue has to do with what I am putting into the csp.
app = Flask(__name__)
csp = {
'default-src': [
'\'self\'',
'\'unsafe-inline\'',
'cdnjs.cloudflare.com',
'maxcdn.bootstrapcdn.com',
'ajax.googleapis.com',
'cdn.datatables.net',
'fonts.googleapis.com',
'gstatic.com',
'https://js.stripe.com',
],
'script-src': [
'\'self\'',
'unsafe-eval',
'\'unsafe-inline\'',
'cdn.firebase.com',
'*.firebaseio.com'
],
'object-src': [
'\'self\''
]
}
talisman = Talisman(app, content_security_policy=csp)
Here is my relevant code in HTML where I use Firebase. It was taken from Google's example.
<div id="firebaseui-auth-container"></div>
<button id="sign-out" hidden=true>Sign Out</button>
<div id="login-info" hidden=true>
<script src="{{ url_for('static', filename='script.js') }}"></script>
Then file "script.js" is below:
window.addEventListener('load', function () {
document.getElementById('sign-out').onclick = function () {
firebase.auth().signOut();
};
// FirebaseUI config.
var uiConfig = {
signInSuccessUrl: '/',
signInOptions: [
// Comment out any lines corresponding to providers you did not check in
// the Firebase console.
firebase.auth.GoogleAuthProvider.PROVIDER_ID
//firebase.auth.EmailAuthProvider.PROVIDER_ID,
//firebase.auth.FacebookAuthProvider.PROVIDER_ID,
//firebase.auth.TwitterAuthProvider.PROVIDER_ID,
//firebase.auth.GithubAuthProvider.PROVIDER_ID,
//firebase.auth.PhoneAuthProvider.PROVIDER_ID
],
// Terms of service url.
// tosUrl: '/terms-of-service',
privacyPolicyUrl: '/privacy-policy'
};
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
// User is signed in, so display the "sign out" button and login info.
document.getElementById('sign-out').hidden = false;
document.getElementById('login-info').hidden = false;
console.log(`Signed in as ${user.displayName} (${user.email})`);
user.getIdToken().then(function (token) {
// Add the token to the browser's cookies. The server will then be
// able to verify the token against the API.
// SECURITY NOTE: As cookies can easily be modified, only put the
// token (which is verified server-side) in a cookie; do not add other
// user information.
document.cookie = "token=" + token;
});
} else {
// User is signed out.
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
// Show the Firebase login button.
ui.start('#firebaseui-auth-container', uiConfig);
// Update the login state indicators.
document.getElementById('sign-out').hidden = true;
document.getElementById('login-info').hidden = true;
// Clear the token cookie.
document.cookie = "token=";
}
}, function (error) {
console.log(error);
alert('Unable to log in: ' + error)
});
});
Does anyone know what I am missing?

How to detect microphone permissions state

I'm looking to show different modals to the user to guide them to allow their permission when trying to use a microphone requiring task in my app - based on whether they have not yet been requested for microphone permissions, granted permissions, or blocked permissions.
How can I reliably find out which state of permissions the user is in? Preferably with an onChange handler to know if the user revokes their permission at any point and something that would work for Chrome, Firefox, and Safari.
The inspiration comes from voice.google.com where they show different screen on the call widget when trying to call the Google voice number with the microphone permission set to "ask", "allow", or "block".
I've gone through https://developers.google.com/web/updates/2015/04/permissions-api-for-the-web but I can't seem to find a solution for how I would like to implement this.
Edit:
<div id="button">Click me</div>
<script>
const button = document.getElementById("button")
button.addEventListener('click', () => {
navigator.mediaDevices.getUserMedia({
audio: true
})
.then(function(stream) {
console.log('You let me use your mic!')
console.log(stream)
navigator.permissions.query({
name: 'microphone'
}, ).then(function(permissionStatus) {
console.log("PermissionStatus: ", permissionStatus.state); // granted, denied, prompt
permissionStatus.onchange = function() {
console.log("Permission changed to " + this.state);
}
})
})
.catch(function(err) {
console.error(err)
console.log('No mic for you!')
});
})
navigator.permissions.query({
name: 'microphone'
})
.then(function(permissionStatus) {
console.log("PermissionStatus: ", permissionStatus.state); // granted, denied, prompt
permissionStatus.onchange = function() {
console.log("Permission changed to " + this.state);
}
})
</script>
The name is "microphone" and you'll get "granted", "prompt" or "denied" as the state.
https://developers.google.com/web/fundamentals/media/recording-audio#use_the_permissions_api_to_check_if_you_already_have_access

Bot Get Channel Data

Team,
I have developed a bot using bot framework SDK4.
I am using Directline channel to communicate with my bot.
My requirement is based on channeldata on 'requestWelcomeDialog' message I have to show welcome message.
Code from my bot client:
BotChat.App({
botConnection: botConnection,
user: userOption,
bot: { id: model.botId, name: model.botName },
resize: 'window',
speechOptions: speechOptions,
locale: 'en',
sendTypingIndicator: true,
}, document.getElementById('BotChatElement'));
PostBotConfiguration();
botConnection
.postActivity({
from: user,
name: 'requestWelcomeDialog',
type: 'event',
value: { 'BotType': 'abcd' }
})
.subscribe(function (id) {
setWCScreenChatPosition();
model.botRender = true;
console.log('"trigger requestWelcomeDialog" sent');
});
In the above code i am sending BotType as 'abcd'.
I am trying to read this value from my bot.
My code in bot.
protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
Utility util = new Utility();
try
{
foreach (var member in membersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
BotChannelData cdata = new BotChannelData();
turnContext.Activity.TryGetChannelData(out cdata);
}
}
}
catch
{
}
}
In this I am always getting null reference exception.
May I know what I am missing in this?
The first problem is that you're using Bot Chat. Bot Chat is Web Chat v3 and it's deprecated. You should be using Web Chat v4 according to the instructions in the repo.
The second problem is that you're trying to respond to a custom event using OnMembersAddedAsync which is only triggered by conversation update activities. You can see how to send and respond to welcome events by following the instructions in this issue and this sample. The C# equivalent would look like this:
if (turnContext.Activity.Name == "webchat/join")
{
await turnContext.SendActivityAsync("Back Channel Welcome Message!");
}
If you use Direct Line channel, you should use Web Chat v4. Because Web Chat v3 is now deprecated.
You could get the sending welcome message code from this official sample.
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Send welcome event</title>
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
html, body { height: 100% }
body { margin: 0 }
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat"></div>
<script>
(async function () {
const res = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' });
const { token } = await res.json();
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: { language: window.navigator.language }
}
});
}
return next(action);
});
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
store
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>

Spotify web player gives Websocket error on raspberry pi

I am trying to set up spotify player to my raspberry pi. I have codes that work's like a charm on my macbook/chrome but the same codes wont work on raspbian/chromium.
I am getting following errors:
Error while parsing the 'allow' attribute: 'encrypted-media' is an invalid feature name.
{message: "Failed to initialize player"} script.js:44
WebSocket connection to 'wss://gew-dealer.spotify.com/?access_token=removed_my_token'
failed: Error in connection establishment: net:: ERR_NOT_IMPLEMENTED
{message: "Authentication failed"} script.js:45
Here is my script.js:
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
if (item) {
var parts = item.split('=');
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = '';
// Set token
let _token = hash.access_token;
const authEndpoint = 'https://accounts.spotify.com/authorize';
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = 'removed_my_client_id';
const redirectUri = 'http://localhost:1337';
const scopes = [
'streaming',
'user-read-birthdate',
'user-read-private',
'user-read-email',
'user-modify-playback-state'
];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token&show_dialog=true`;
}
// Set up the Web Playback SDK
window.onSpotifyPlayerAPIReady = () => {
const player = new Spotify.Player({
name: 'Web Playback SDK Template',
getOAuthToken: cb => { cb(_token); }
});
// Error handling
player.on('initialization_error', e => console.error(e));
player.on('authentication_error', e => console.error(e));
player.on('account_error', e => console.error(e));
player.on('playback_error', e => console.error(e));
// Playback status updates
player.on('player_state_changed', state => {
console.log(state)
$('#current-track').attr('src', state.track_window.current_track.album.images[0].url);
$('#current-track-name').text(state.track_window.current_track.name);
});
// Ready
player.on('ready', data => {
console.log('Ready with Device ID', data.device_id);
// Play a track using our new device ID
play(data.device_id);
});
// Connect to the player!
player.connect();
}
// Play a specified track on the Web Playback SDK's device ID
function play(device_id) {
$.ajax({
url: "https://api.spotify.com/v1/me/player/play?device_id=" + device_id,
type: "PUT",
data: '{"uris": ["spotify:track:5ya2gsaIhTkAuWYEMB0nw5"]}',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
success: function(data) {
console.log(data)
}
});
}
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Spotify Web Playback SDK Template</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://sp-bootstrap.global.ssl.fastly.net/8.0.0/sp-bootstrap.min.css" rel="stylesheet" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<!-- Include the Web Playback SDK -->
<script src="https://sdk.scdn.co/spotify-player.js"></script>
<!-- Include our Javascript -->
<script src="script.js" defer></script>
</head>
<body class="container">
<h1 class="text-salmon">Spotify Web Playback SDK Template</h1>
<h4>This app uses the implicit grant authorization flow to get an access token and initialise the Web Playback SDK. It then uses the Spotify Connect Web API to play a song.</h4>
<p>If everything is set up properly, you should hear some music!</p>
<img id="current-track"/>
<h3 id="current-track-name"></h3>
<a class="btn btn-salmon btn-lg" href="https://glitch.com/edit/#!/spotify-web-playback">Get started!</a>
</body>
</html>
This code should do:
Initialize the web player
Select one hard coded song
Play the song
Show the image
I have absolutely no idea what could be the problem here. I have been trying a lot of things to fix this but the problem is that i don't know what causes this so i have been just doing stuff without any idea is it going to help. So my question is how i can make this work on raspberry?

Categories