Solana Non-base58 character - solana

I'm trying to sign a transaction on solana with this piece of code:
const txs = [];
const { recentBlockhash, instructions, feePayer } = tx;
const newTx = new SolTransaction({
feePayer,
recentBlockhash,
});
for (const ins of instructions) {
newTx.add(ins);
}
newTx.sign({ publicKey: this._signer.publicKey, secretKey: this._signer.secretKey });
txs.push(newTx);
but for some reason when i sign the transaction i get this error:
Non-base58 character any idea why?

Related

how to create a transaction to burn SPL tokens in react app?

I wrote a function burnSplToken which takes two inputs:
(account(wallet address): string, {account(token address): string, amount: number(token amount)})
I am trying to create a transaction to burn specific amount of tokens. But it's giving me a buffer error at the getOrCreateAssociatedTokenAccount function saying buffer not found error. What am I doing wrong here? I am using react for the frontend.
export const burnSplToken = async (walletAddress, assetAddress) => {
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
let senderAddress = new PublicKey(walletAddress)
const mintPubkey = new PublicKey(assetAddress.tokenAddress);
let ataSender = await getOrCreateAssociatedTokenAccount(
connection, // connection
senderAddress, // fee payer
mintPubkey, // mint
senderAddress // owner,
);
console.log(`ATASender: ${ataSender}`);
// calculate ATA
let ata1 = await getAssociatedTokenAddress(
mintPubkey, // mint
senderAddress // owner
);
const message = `Sign below to authenticate with Rifters Adventure`;
const encodedMessage = new TextEncoder().encode(message);
const signedMessage = await window.solana.signMessage(encodedMessage, "utf8");
let blockhash = (await connection.getLatestBlockhash('finalized')).blockhash;
let tx = new Transaction().add(
createBurnCheckedInstruction(
ataSender.address, // token account
mintPubkey, // mint
senderAddress, // owner of token account
1e9, // amount, if your deciamls is 8, 10^8 for 1 token
9 // decimals
)
);
tx.recentBlockhash = blockhash;
tx.feePayer = senderAddress
const signedTransaction = await window.solana.signTransaction(tx);
console.log("signedTransaction", signedTransaction);
const signature = await connection.sendRawTransaction(signedTransaction.serialize());
console.log(signature)
}

Creating a KeyPair for a integration test against NEAR using the near-js-api

I'm trying to write an integration test to call a method on a Near Protocol contract.
I've got as far as creating the account object, and now need to set the key pair to be able to make the call.
I can see that I can get the private key value by logging in on the near-cli and getting the key from the .nearcredentials folder. But it seems like I need to encode this before setting the key in the store.
const keyStore = new keyStores.InMemoryKeyStore();
const config = {
keyStore,
networkId: "testnet",
nodeUrl: "https://rpc.testnet.near.org",
};
const near = await connect(config);
const account = await near.account("my_account.testnet");
const keyPair = ???
await keyStore.setKey(config.networkId, "my_account.testnet", keyPair);
const result = await account.functionCall({
contractId: "nft-example.my_account.testnet",
methodName: "nft_metadata"
})
I've figured out how to generate the KeyPair from the private key, full code example is here, but it's basically the first line of the example using the near utils function
const { connect, keyStores, utils, Contract } = require("near-api-js");
const keyPair = new utils.key_pair.KeyPairEd25519(process.env.TEST_ACCOUNT_PRIVATE_KEY);
const keyStore = new keyStores.InMemoryKeyStore();
await keyStore.setKey(networkId, "my_account.testnet", keyPair);
const near = await connect({
keyStore,
networkId,
nodeUrl: "https://rpc.testnet.near.org",
});
const account = await near.account("my_account.testnet");
const contract = new Contract(
account,
'nft-example.my_account.testnet',
{
viewMethods: ['nft_metadata'],
changeMethods: []
}
);
const result = await contract.nft_metadata();
expect(result.spec).toBe("nft-1.0.0");

Ethers.js pancakeswap swapExactTokensForTokens invalid response - sendTransaction

I'm trying to execute an Pancakeswap swapExactTokensForTokens using ethers.js but i just keep getting the error invalid response - sendTransaction. Unfortunatly the error doesnt contain any more usefull information then that :(
My code:
const provider = new ethers.providers.WebSocketProvider(config.network);
const tradeWallet = ethers.Wallet.fromMnemonic(config.mnemonic);
const account = tradeWallet.connect(provider);
const router = new ethers.Contract(
'0x10ED43C718714eb63d5aA57B78B54704E256024E',
[
'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
],
account
);
[snip]
var amountIn = ethers.utils.parseUnits('0.001', 'ether');
var tokenIn = '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c';
var tokenOut = '0xd2de3fd31b5c9e1557cf329032615a2870a29ccd';
var gasPrice = '5000000000';
var gasLimit = '231795'
var amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut])
const amountOutMin = amounts[1].sub(amounts[1].div(10));
// values at the time where:
// tokenIn: 100000000000000 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c (WBNB)
// tokenOut: 1810636794711288351 0xd2de3fd31b5c9e1557cf329032615a2870a29ccd
var tx = router.swapExactTokensForTokens(
amountIn,
amountOutMin,
[tokenIn, tokenOut],
addresses.recipient,
Date.now() + 1000 * 60 * 3, //10 minutes
{ gasPrice: gasPrice,
gasLimit: gasLimit
}
);
const receipt = await tx.wait();
use 'swapExactTokensForETHSupportingFeeOnTransferTokens',Because your 'tokenOut' token has a tax function

Google Users: List users data of a specific group

I am in the need of listing the users data belonging to a specific group within the organization. The documentation does not specify if this is possible. I was really hoping there could be some kind of query that would allow this. For example email in (1#domain.com,2#domain.com). However, I don't see that being possible. The only way I could think to accomplish this would be:
Get a list of all the members in the group (https://developers.google.com/admin-sdk/directory/reference/rest/v1/members/list)
Get each user data by email (https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/get)
The problem with the above approach is that if a group contains 50+ members, this means that I have to make all that amount of requests, which is counter productive. Imagine how long that would take.
Any ideas? Greatly appreciate it.
Unfortunately I don’t think you can skip this two step process, but you can speed it up using batch requests. This
allows you to request up to 1000 calls in a single request. The steps would be:
Make a batch request to get all the members of all the groups you want (using members.list).
Make a batch request to get all the user info that you need using their id (using user.get).
Notice that the data in the result won’t be sorted, but they will be tagged by Content-ID.
References
Sending Batch Requests (Directory API)
Method: members.list (Directory API)
Method: users.get (Directory API)
I thought about the batching request a couple of hours after I posted the question. The problem with Node JS is that it does not has built in support for batch requests, unlike the php client library for example; Therefore, I had to spent some time implementing support for it on my own since I was not able to find any example. I'll share the solution in case it helps someone else or for my future reference.
async function getGroupMembersData(){
const groupEmail = "group#domain.com"; //google group email
const groupMembers = await getGroupMembers(groupEmail).catch(error=>{
console.error(`Error querying group members: ${error.toString()}`);
});
if(!groupMembers){ return; }
const url = "https://www.googleapis.com/batch/admin/directory_v1";
const scopes = ["https://www.googleapis.com/auth/admin.directory.user.readonly"];
const requests = [];
for(let i=0; i<groupMembers.length; ++i){
const user = groupMembers[i];
const request = {
email: user,
endpoint: `GET directory_v1/admin/directory/v1/users/${user}?fields=*`
};
requests.push(request);
}
const batchRequestData = await batchProcess(url, scopes, requests).catch(error=>{
console.error(`Error processing batch request: ${error.toString()}`);
});
if(!batchRequestData){ return; }
const usersList = batchRequestData.map(i=>{
return i.responseBody;
});
console.log(usersList);
}
//get group members using group email address
async function getGroupMembers(groupKey){
const client = await getClient(scopes); //function to get an authorized client, you have to implement on your own
const service = google.admin({version: "directory_v1", auth: client});
const request = await service.members.list({
groupKey,
fields: "members(email)",
maxResults: 200
});
const members = !!request.data.members ? request.data.members.map(i=>i.email) : [];
return members;
}
//batch request processing in groups of 100
async function batchProcess(batchUrl, scopes, requests){
const client = await getClient(scopes); //function to get an authorized client, you have to implement on your own
let results = [];
const boundary = "foobar99998888"; //boundary line definition
let batchBody = ""; const nl = "\n";
const batchLimit = 100; //define batch limit (max supported = 100)
const totalRounds = Math.ceil(requests.length / batchLimit);
let batchRound = 1;
let batchItem = 0;
let roundLimit = batchLimit;
do{
roundLimit = roundLimit < requests.length ? roundLimit : requests.length;
//build the batch request body
for(batchItem; batchItem<roundLimit; batchItem++){
const requestData = requests[batchItem];
batchBody += `--${boundary}${nl}`;
batchBody += `Content-Type: application/http${nl}`;
batchBody += `Content-Id: <myapprequest-${requestData.email}>${nl}${nl}`;
batchBody += `${requestData.endpoint}${nl}`;
}
batchBody += `--${boundary}--`;
//send the batch request
const batchRequest = await client.request({
url: batchUrl,
method: "POST",
headers: {
"Content-Type": `multipart/mixed; boundary=${boundary}`
},
body: batchBody
}).catch(error=>{
console.log("Error processing batch request: " + error);
});
//parse the batch request response
if(!!batchRequest){
const batchResponseData = batchRequest.data;
const responseBoundary = batchRequest.headers["content-type"].split("; ")[1].replace("boundary=", "");
const httpResponses = batchResponseParser(batchResponseData, responseBoundary);
results.push(...httpResponses);
}
batchRound++;
roundLimit += batchLimit;
} while(batchRound <= totalRounds);
return results;
};
//batch response parser
function batchResponseParser(data, boundary){
const nl = "\r\n";
data = data.replace(`--${boundary}--`,"");
const responses = data.split(`--${boundary}`);
responses.shift();
const formattedResponses = responses.map(i=>{
const parts = i.split(`${nl}${nl}`);
const responseMetaParts = (parts[0].replace(nl, "")).split(nl);
let responseMeta = {};
responseMetaParts.forEach(part=>{
const objectParts = part.split(":");
responseMeta[objectParts[0].trim()] = objectParts[1].trim();
});
const responseHeadersParts = parts[1].split(nl);
let responseHeaders = {};
responseHeadersParts.forEach(part=>{
if(part.indexOf("HTTP/1.1") > -1){
responseHeaders.status = part;
} else {
const objectParts = part.split(":");
responseHeaders[objectParts[0].trim()] = objectParts[1].trim();
}
});
const reg = new RegExp(`${nl}`, "g");
const responseBody = JSON.parse(parts[2].replace(reg, ""));
const formatted = {
responseMeta: responseMeta,
responseHeaders: responseHeaders,
responseBody: responseBody
};
return formatted;
});
return formattedResponses;
}

502 on AWS Cognito ListUsers with PaginationToken

Using AWSMibileHub to set up my backend. Working on an admin page that shows all the users from AWS Cognito.
I’m using ListUsers to get user list and noticed 502 error on the request with a PagenationToken and it seems to be happening randomly.
In CloudWatch shows this error below.
InvalidParameterException: 1 validation error detected: Value 'CAISlAIIARLtAQgDEugBADSdLB5dZXQEaQjoL8y8CE1RGGT3PZ4FpCqxFwJkNuhIeyJAbiI6IlBhZ2luYXRpb25Db250aW51YXRpb25EVE8iLCJuZXh0S2V5IjoiQUFBQUFBQUFCZHM4QVFFQmJBZmU5OFgzUnJTM1BHcnYzVmRiVWNScVdIck82VXFZaTdlZklleVRCSEZsYm1ZN01UVTRPV1k0TVRNdE9UYzVZUzAwWTJKakxUazROekl0TkdRek9UYzROMlpoWmpVM093PT0iLCJwcmV2aW91c1JlcXVlc3RUaW1lIjoxNTQzMDkzODIyNDk5fRogNk7FThSKBOuwQGi DoZBnmNN85UY5oFiSAbHWfOzreY=' at 'paginationToken' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+
Does anybody have the same issue or any idea how to fix this issue?
Store the pagination Token in a variable and then add this .replace(/\ /g,'+') to the variable to change the space back to +.
e.g:
const pagination = 'TOKEN FROM COGNITO'.replace(/\ /g,'+')
The pagination_token consists of non alphanumeric characters, so its better to encrypt and decrypt when required.
Encrypt?decrypt utility file
const crypto = require("crypto");
const algorithm = "aes-256-ctr";
const password = "sassed";
class Util {
static encrypt_aes(text) {
let cipher = crypto.createCipher(algorithm, password);
let crypted = cipher.update(text, "utf8", "hex");
crypted += cipher.final("hex");
return crypted;
}
static decrypt_aes(text) {
let decipher = crypto.createDecipher(algorithm, password);
let dec = decipher.update(text, "hex", "utf8");
dec += decipher.final("utf8");
return dec;
}
}
module.exports = Util;
PaginationToken encryption/decription
const Util = require("./utils");
class Users {
static async getUsersAttributes(params) {
let listparams = {
UserPoolId: userPoolID /* required */,
Limit: params.limit || 10,
};
if (params.paginationToken) {
listparams.PaginationToken = Util.decrypt_aes(params.paginationToken);
}
let response = await cognitoISPClient.listUsers(listparams).promise();
response.PaginationToken = Util.encrypt_aes(response.PaginationToken);
return response;
}
}

Resources