TypeError: this is undefined in rect js while passing BigNumber in solana RPC Request - reactjs

i am getting this is undefined at BN while making RPC request to a function in solana smart contract
'''
let token1Amount = BN(token1_amount);
let token2Amount = BN(token2_amount)
const add_liquidity = await router_program.rpc.addLiquidity(
token1Amount,
token2Amount,
{
accounts: {
// poolAccount: pool_Account.publicKey, //account which stores the individual pair data
userToken1Account: usetoken1_account,
userToken2Account: usetoken2_account,
poolToken1Account: new PublicKey(tokenaccount_1),
poolToken2Account: new PublicKey(tokenaccount_2),
owner: provider.wallet.publicKey,
tokenProgram: TOKEN_PROGRAM_ID,
// systemProgram : SystemProgram.programId ,
// associatedTokenProgram: spl.ASSOCIATED_TOKEN_PROGRAM_ID,
// rent: anchor.web3.SYSVAR_RENT_PUBKEY,
tokensProgram: TOKEN_ID,
// poolProgram: pair.programId,
// pairAccount: pairAccount.publicKey
},
// signers: [provider]
}
);
'''

This is a shot in the dark, but I think you need new so that your BNs have a this context, so instead try:
let token1Amount = new BN(token1_amount);
let token2Amount = new BN(token2_amount);

Related

How to get a reference to a former created Token in Solana (client side, JS)

I'm able to create a token and mint it into an spl account address.
But when I restart my program, how do I get a reference to that Token, so that I mint again?
const web3 = require("#solana/web3.js");
const splToken = require('#solana/spl-token');
const { PublicKey, Keypair, Transaction, SystemProgram, LAMPORTS_PER_SOL, sendAndConfirmTransaction, clusterApiUrl } = require("#solana/web3.js");
let secretKey = Uint8Array.from([233, 65, 11, rest of my secret]);
let fromWindowsWallet = Keypair.fromSecretKey(secretKey);
let connection = new web3.Connection(clusterApiUrl('devnet'));
(async () => {
//create my new token mint
let SWAB = await splToken.Token.createMint(
connection,
fromWindowsWallet,
fromWindowsWallet.publicKey,
fromWindowsWallet.publicKey,
2,
splToken.TOKEN_PROGRAM_ID,
);
console.log(SWAB.publicKey) // -> PublicKey {
_bn: <BN: 2643549b60882496a15407c2f1a6139dd2c4128879480b1d56fdd464550db22b>
}
// ... continue with that Token SWAB
}
So when I restart my program, how can I get a reference to the Token SWAB again? I tried:
let pubKey = new PublicKey("<BN: 6ddf6e1d765a193d9cbe146ceeb79ac1cb485ed5f5b37913a8cf5857eff00a9>");
let SWAB = new splToken.Token(
connection,
pubKey,
splToken.TOKEN_PROGRAM_ID,
fromWindowsWallet
)
but that throws: Error: Non-base58 character
After creating the Token I can get the pubKey with:
console.log(SWAB.publicKey.toBase58()) // 3aN3KP6kQdBvTHTeK785Uuykddram97B844RoJc19VNS
Then I can get a reference to the Token like this and continue minting:
let pubKey = new PublicKey('3aN3KP6kQdBvTHTeK785Uuykddram97B844RoJc19VNS');
let SWAB = new splToken.Token(
connection,
pubKey,
splToken.TOKEN_PROGRAM_ID,
fromWindowsWallet
)
(connection and fromWindowsWallet are defined in the code of my question)

TypeError: Cannot read property 'send' of undefined discord.js v12

i have this reaction role system everything works up to the last part where the coulour slection happens
async run(message, client, con) {
await message.channel.send("Give the color for the embed.")
answer = await message.channel.awaitMessages(answer => answer.author.id === message.author.id,{max: 1});
var color = (answer.map(answers => answers.content).join()).toUpperCase()
if(color.toUpperCase()==='CANCEL') return (message.channel.send("The Process Has Been Cancelled!"))
function embstr(){
var finalString = '';
for(var i =0;i<n;i++){
finalString += b[i]+ ' - '+a[i] +'\n';
}
return finalString;
}
const botmsg = message.client.channels.cache.get(channel => channel.id === reactChannel)
const embed = new MessageEmbed()
.setTitle(embtitle)
.setColor(color)
.setDescription(embstr());
botmsg.send(embed);
message.channel.send("Reaction Role has been created successfully")
here is the error message
{
"stack": "TypeError: Cannot read property 'send' of undefined
at SlowmodeCommand.run (B:\\stuff\\Downloads\\Admeeeeeen bot\\src\\commands\\reactionroles\\createreactionrole.js:100:22)
at processTicksAndRejections (node:internal/process/task_queues:93:5)"
}
The .get() method takes in a snowflake as its parameter. AKA an ID of a certain object. It is not an iterator, meaning that what you're currently attempting to do is not right JavaScript wise.
Instead of passing in a parameter to represent a channel object, we'll just want to pass in the ID of the channel that we'd like to get. Alternatively, you could replace .get() with .find() there, which is in fact an iterator that uses this form of a callback, although it's insufficient in our case considering we can just use .get() which is more accurate when it comes to IDs.
/**
* Insufficient code:
* const botmsg = message.client.channels.cache.find(channel => channel.id === reactChannel)
*/
const botmsg = message.client.channels.cache.get(reactChannel /* assuming that reactChannel represents a channel ID */)

TypeError: Cannot read property 'fetchMembers' of undefined

i got this erroe even the command is working fine
(node:1907) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fetchMembers' of undefined
client.on('message', async message => {
let guild = await message.guild.cache.fetchMembers();
let roleID= '644235497169748037';
let roleID1= '615852982734684181';
let roleID2= '615852983330013212';
let roleID3= '615852992230588427';
let roleID4= '722513324151144552';
let memberCount = guild.roles.get(roleID).members.size;
let memberCount1 = guild.roles.get(roleID1).members.size;
let memberCount2 = guild.roles.get(roleID2).members.size;
let memberCount3 = guild.roles.get(roleID3).members.size;
let memberCount4 = guild.roles.get(roleID4).members.size;
let memberCountChannel = guild.channels.get("733035179756486737")
let memberCountChannel1 = guild.channels.get("732530240420839464")
let memberCountChannel2 = guild.channels.get("732530312713863178")
let memberCountChannel3 = guild.channels.get("732530713898909746")
let memberCountChannel4 = guild.channels.get("732530791686602833")
memberCountChannel.setName("Guild Members: " + memberCount)
memberCountChannel1.setName("Wizard: " + memberCount1)
memberCountChannel2.setName("Witch: " + memberCount2)
memberCountChannel3.setName("Shai: " + memberCount3)
memberCountChannel4.setName("Compass: " + memberCount4)
});
Discord JS v12 introduces the concept of managers, you will no longer be able to directly use collection methods such as Collection#get on data structures like Client#users. You will now have to directly ask for a cache on a manager before trying to use collection methods.
You need to change:
guild.roles.get(roleID)
// to
guild.roles.cache.get(roleID)
and:
guild.channels.get(channelID)
// to
guilds.channels.cache.get(channelID)
Another error I saw in your code is that you are trying to access the property cache of Guild, which is nonexistent (message.guild.cache.fetchMembers()).
You'll have to use:
message.guild.members.fetch()

How to send encrypted (3DES) data into aqueduct without getting any error?

I m using Aqueduct 3.0. I need to learn How to capture post request in Aqueduct 3.0?
My Request: http://127.0.0.1:8888/login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjM+oHROYz/YTHnd3NH1XfHRULY0jaHU
Get a Response:
[INFO] aqueduct: GET /login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjM+oHROYz/YTHnd3NH1XfHRULY0jaHU 11ms 404
my channel.dart routing
// TODO: connect to Socket **********
router.route('/login/[:value]').link(() {
return new LoginController();
//..contentType = ContentType.TEXT;
});
my LoginController.dart
import 'package:aqueduct/aqueduct.dart';
import 'package:niyaziapi/niyaziapi.dart';
import 'package:niyaziapi/util/niyaziGetPrivate.dart';
import 'package:niyaziapi/util/niyaziSetPrivate.dart';
class LoginController extends Controller {
String _xCustomerToken;
String _xCustomerName;
String _xPrivate;
String _xResult;
String _xRequestValue;
String _xReply;
#override
Future<RequestOrResponse> processRequest(Request request) async {
String tempData = request.toString();
print("tempDate: $tempData"); // can’t print
try {
if (request.path.variables.containsKey('value')) {
_xPrivate = (request.path.variables['value']).trim();
print("_xPrivate: $_xPrivate");
var decryptedData = await getPrivate(_xPrivate);
var decryptedList = decryptedData.split(":_:");
decryptedData = null;
decryptedData = "Q101:_:" + decryptedList[2].toString() + ":_:" + decryptedList[3].toString();
print(decryptedData);
var socket = await Socket.connect('192.168.1.22', 1024);
socket.write("$decryptedData\r\n");
await for (var data in socket) {
_xReply = new String.fromCharCodes(data).trim();
var list = _xReply.split(":_:");
_xCustomerToken = list[2].toString();
_xCustomerName = list[3].toString();
});
_xResult = "$_xCustomerToken:_:$_xCustomerName";
var encryptedData = await setPrivate(_xResult);
return new Response.ok("$encryptedData");
}
} else {
return new Response.ok("404: Wrong Request");
}
} catch (e) {
return new Response.ok("404: $e.errorMessage");
}
}
}
when I testing I found that my code works. Only reason that I am sending 3DES data and has + and / character in it.
If you look at closely in first request, there is a + and / character in data which give me an error.
/login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjM+oHROYz/YTHnd3NH1XfHRULY0jaHU 19ms 404
on the other hand if I remove those character than I get perfect response.
/login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjMoHROYzYTHnd3NH1XfHRULY0jaHU 13 ms 200
So, question comes how to send encrypted (3DES) data into aqueduct without getting any error?
Going to Like Aqueduct twice :)
It was very simple:
var _xPrivate = (request.path.variables['value']).trim(); change to:
var _xPrivate = request.path.remainingPath;
print("request: $_xPrivate");

TokenCache: No matching token was found in the cache, Azure AD Api

I'd like to use Azure AD Api and I couldn't acquire token some reason. I have two methods, and I got this after calling:
TokenCache: No matching token was found in the cache iisexpress.exe Information: 0
Here's my code:
public string GetToken()
{
string authority = "https://login.microsoftonline.com/{tenantId}/";
string clientId = "";
string secret = "";
string resource = "https://graph.windows.net/";
var credential = new ClientCredential(clientId, secret);
AuthenticationContext authContext = new AuthenticationContext(authority);
//I think the problem is here:
var token = authContext.AcquireTokenAsync(resource, credential).Result.AccessToken;
return token;
}
public string MakeRequest()
{
string accessToken = GetToken();
var tenantId = "";
string graphResourceId = "https://graph.windows.net/";
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient client = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));
foreach (var user in client.Users.ExecuteAsync().Result.CurrentPage)
Console.WriteLine(user.DisplayName);
var client1 = new HttpClient();
var uri = "https://graph.windows.net/" + tenantId + "/users?api-version=1.6";
client1.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var response = client1.GetAsync(uri).Result;
var result = response.Content.ReadAsStringAsync().Result;
return result;
}
I don't know what's the problem, and I didn't find any great hint, under other questions and a little explanation would be helpful. I'd like to understand this part, of course.
//When you are calling
Main() { Method_A() }
aync Method_A() { await Method_B() }
Task < T > Method_B() { return T; }
//It will through the error. //Need to keep Mehtod_B in another Task and run.
// Here I am avoiding few asyncs
Main() { Method_A() }
Method_A() { Method_B().Wait() }
Task Method_B() { return T; }
There is no output using the Console.WriteLine in a IIS progress. If you want to output the result in a output window for the web project, you can use System.Diagnostics.Debug.WriteLine() method.

Resources