How to get cw20 token details from terra.js - web3js

I can get cw20 token balance using this code snippet
const response = await terraConfig.wasm.contractQuery(tokenAddress, {
balance: { address: walletAddress },
});
how can I get the token details like name, symbol and decimals details using terra.js

Related

WalletConnect :- Rainbow always show MATIC when transfer other coins by WalletConnect sendTransaction in react native

I am developing react native mobile application where user can transfer their amount by external wallet (Rainbow, MetaMask).
I am using 'polygon-rpc' network for my users.
The thing is working as expected but when execute transfer method by my contract by WalletConnect sendTransaction(txObj) library it navigate me to connected wallet and prompted the confirmation pop, where it show the my currency in MetaMask, but in Rainbow it always show Matic instead of POZ.
However it works well in Metamask and show the POZ, instead of MATIC.
I am using this code to procced transaction by WalletConnect external wallet
let toAddress = pozPouchFundWallet; // end address to transfer amount
let decimals = BigNumber(18);
let amount1 = new BigNumber(amountValue);
let value = amount1.times(new BigNumber(10).pow(decimals));
let contract = new Web3js.eth.Contract(App_ABI, POZ_TOKEN!);
try {
let dataa = await contract.methods
.transfer(toAddress, value.toString())
.encodeABI();
let txObj = {
// gas: Web3js.utils.toHex(100000),
data: Web3js.utils.toHex(dataa),
from: userWallet,
to: POZ_TOKEN, // Contractor token address
};
try {
const transactionHash = await connector
.sendTransaction(txObj)
.catch((_err: any) => {
Toast.show({
autoHide: true,
text1: t('topUpPoz.transactionFailed'),
type: 'error',
});
});
console.log('transactionHash is =', transactionHash);
resolve(transactionHash);
} catch (error) {
console.log('the connector error is = ', error);
reject(error);
}
} catch (err) {
console.log('contact error is = ', err);
reject(err);
}

Send image file and data in REACT JS to Codeigniter 3 with axios

here is my front end code :
const api = axios.create({
baseURL: Backend_url+`Mode_ticketing_react/Ticketing/`
});
const Ticketing_rest = {
async post_nouveau_ticketing(
nouveau_ticket_fichier_joint,
email,
objet,
description,
categorie,
id_user
) {
try {
const result = await api.post(
"set_nouveau_ticketing/", {
email : email,
objet : objet,
description : description,
categorie : categorie,
id_user : id_user,
nouveau_ticket_fichier_joint : nouveau_ticket_fichier_joint
}
);
console.log("resultat envoye fichier ------", result)
return result.data;
}catch (error) {
console.log("erreur survenue" + error)
}
},
and take this services into view
function handleClick_soumettre_nouveau_ticket(e){
e.preventDefault();
setSpinner_button(true);
Ticketing_rest.post_nouveau_ticketing( champ_file_nouveau,
champ_email,
champ_objet,
champ_description,
champ_categorie,
flexi_auth.user_id
).then((result)=>{
//console.log(result)
});
}
all parameter is take from input field, and my problem is that ALL DATA is submited apart from the "champ_file_nouveau" field which is a file data.
function handleChange_champ_file_nouveau(e){
e.preventDefault();
setChamp_file_nouveau(e.target.files[0]);
console.log("selected file ------",e.target.files[0])
}
my backend is write in Codeigniter and I test it from Postman and it work!! so i think that the problem does not come from Backend but comes from FRONT END!
Any suggestions please.
I already try with FormData() class but does not work!

VM Exception while processing transaction: revert error while testing createRequest method

I am doing the following test from a udemy ethereum course.
I found VM Exception while processing transaction: revert error while testing the following method in Campaign.test.js file.
it('allows a manager to make a payment request', async () => {
const recipientAddress = accounts[1];
await campaign.methods
.createRequest('Buy batteries', '100', recipientAddress)
.send({
from: accounts[0],
gas: '1000000'
});
const request = await campaign.methods.requests(0).call();
console.log(request.description);
assert(true);
});
method in campaign.sol file is given below
function createRequest(string description, uint value, address recipient) public restricted {
Request memory newRequest = Request({
description: description,
value: value,
recipient: recipient,
complete: false,
approvalCount: 0
});
requests.push(newRequest);
}

Posting Form data as json to nested serializer from ReactJS

I am getting this error {"user":["This field is required."]} in reactjs when posting data to an endpoint which has the following serializer
class ProfileSerializer(serializers.ModelSerializer):
user = UserProfileSerializer()
class Meta:
model = models.Profile
fields = ['user',
'address',
'city',
'country',
'user_type',
'telephone_Number',
'organisation_name',
]
def create(self, validated_data):
print(validated_data)
user_data = validated_data.pop('user')
user = UserProfile.objects.create(**user_data)
profile = Profile.objects.create(user=user, **validated_data)
return profile
On the network tab of the browser i can see all the data is captured as shown
user: [{"name":"Testing user"},{"email":"test#gmail.com"},{"password":"*****"},{"is_active":true}]
user_type: 2
organisation_name: Testing company
address: N/A
city: N/A
country: Test
telephone_Number: 8888763
This is how i am posting the data from reactjs
let data = this.state.data;
let user = [
{ name: data.name },
{ email: data.email },
{ password: data.password },
{ is_active: data.is_active },
];
let form_data = new FormData();
form_data.append("user", JSON.stringify(user));
form_data.append("user_type", data.user_type.value);
form_data.append("organisation_name", data.organisation_name);
form_data.append("address", data.address);
form_data.append("city", data.city);
form_data.append("country", data.country);
form_data.append("telephone_Number", data.telephone_Number);
await saveUser(form_data);
Edits
Upon further checks i am noticing the issue is on this await saveUser(form_data);
The data object on the http post requst is empty as shown data: FormData {} So the issue seems to be how to convert form data to json object. How do i convert this?
Please help what could be wrong with this? Kindly assist
FormData was really causing me lots of problem My problem was the format i was using to post data to the server. I created javascript objects from my state objects and i was able to successfully post data to the server as shown below. I had to give an answer so that if in future someone encounters same issue, s/he doesn't suffer like i did. lol
let data = this.state.data;
let user = {
name: data.name,
email: data.email,
password: data.password,
is_active: data.is_active,
};
const userData = {
user,
organisation_name: data.organisation_name,
name: data.name,
address: data.address,
city: data.city,
country: data.country,
telephone_number: data.telephone_Number,
user_type: data.user_type.value,
};
await saveUser(userData);

gmail API for sending users messages in nodejs javascript failes

My nodejs program fails to send messages using the Gmail api.
The solution from Gmail API for sending mails in Node.js does not work for me.
I encode an email with
var {google} = require('googleapis');
// to and from = "some name <blaw.blaw.com"
function makeBody(to, from, subject, message) {
var str = ["Content-Type: text/plain; charset=\"UTF-8\"\r\n",
"MIME-Version: 1.0\r\n",
"Content-Transfer-Encoding: 7bit\r\n",
"to: ", to, "\r\n",
"from: ", from, "\r\n",
"subject: ", subject, "\r\n\r\n",
message
].join('');
encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
return encodedMail;
}
Then go to the Google API explorer
https://developers.google.com/apis-explorer/#p/
enter gmail.users.messages.send and the string generated from the above make_body.
An email will be successfully sent. So I know the above encoding is
ok.
When my program tried to send using the following, it fails with error
Error: 'raw' RFC822 payload message string or uploading message via
/upload/* URL required
function sendMessage(auth) {
var gmail = google.gmail('v1');
var raw = makeBody('john g <asdfasdf#hotmail.com>', 'john g<asfasdgf#gmail.com>', 'test subject', 'test message #2');
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: raw
}
}, function(err, response) {
console.log(err || response)
});
}
The auth token is good since I can call gmail.users.labels.list and I use the same authorization when using the API explorer.
Q1: Does anyone know why the above does not work?
Q2: Gmail API for sending mails in Node.js does not explain why the raw email message is wrapped inside a resource field. I tried simply raw and it did not help.
This fails.
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: raw
}
}, function(err, response) {
console.log(err || response)
});
and so does
gmail.users.messages.send({
auth: auth,
userId: 'me',
raw: raw
}, function(err, response) {
console.log(err || response)
});
and so does this GMAIL API for sending Email with attachment
gmail.users.messages.send({
auth: auth,
userId: 'me',
data: raw
}, function(err, response) {
console.log(err || response)
});
Does anyone know where its documented how to pass the "requested body" the api explorer is asking for?
Q3: Why does the google api need substitutions in the base64 encoding?
I tried encoding using
const Base64 = require("js-base64").Base64
var encodedMail = Base64.encode(str);
When I feed this into the API explorer, I get the error
"message": "Invalid value for ByteString:
Ohai! For others that stumble here, a few things. First - we have a complete end to end sample of sending mail now here:
https://github.com/google/google-api-nodejs-client/blob/master/samples/gmail/send.js
Second, the answer above is mostly right :) Instead of installing the latest version of google-auth-library... just remove it from your package.json all together. The getting started guide was very, very wrong (it has since been fixed). googelapis brings in it's own compatible version of google-auth-library, so you really don't want to mess with that by installing your own version :)
The quickstart specifies:
npm install google-auth-library#0.* --save
When I changed this to
npm install google-auth-library -- save
it pulled in version 1.3.1 vs 0.12.0. Everything started working once I changed the code to account for the breaking changes. The latest version of googleapis also has breaking changes. Here is my tweaks to the quickstart:
package.json
....
"dependencies": {
"google-auth-library": "^1.3.1",
"googleapis": "^26.0.1"
}
quickstart.js
var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
const {GoogleAuth, JWT, OAuth2Client} = require('google-auth-library');
var SCOPES = [
'https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.send'
];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new GoogleAuth();
var oauth2Client = new OAuth2Client(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function (err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function (code) {
rl.close();
oauth2Client.getToken(code, function (err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
function makeBody(to, from, subject, message) {
var str = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
"MIME-Version: 1.0\n",
"Content-Transfer-Encoding: 7bit\n",
"to: ", to, "\n",
"from: ", from, "\n",
"subject: ", subject, "\n\n",
message
].join('');
var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
return encodedMail;
}
function sendMessage(auth) {
var gmail = google.gmail('v1');
var raw = makeBody('xxxxxxxx#hotmail.com', 'xxxxxxx#gmail.com', 'test subject', 'test message');
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: raw
}
}, function(err, response) {
console.log(err || response)
});
}
const secretlocation = 'client_secret.json'
fs.readFile(secretlocation, function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Gmail API.
authorize(JSON.parse(content), sendMessage);
});
Now when I run, I get the response
Object {status: 200, statusText: "OK", headers: Object, config: Object, request: ClientRequest, …}

Resources