Ethers.js pancakeswap swapExactTokensForTokens invalid response - sendTransaction - binance-smart-chain

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

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)
}

Optimising Google Speed Insights API Script in Google Sheets

I have created a script in Google Apps Scripts and Google Sheets that returns some speed metrics from the urls that are pasted in the sheet.
The script works good, the only problem is that it takes forever to present the results in the sheet. It makes a call for each url, I suspect that's why it's slow.
Is there any way I can optimise this script so it gives me the results faster?
Screenshot
The code:
const sheet = SpreadsheetApp.getActiveSpreadsheet();
const API_STRING = sheet.getSheetByName("instructions").getRange("K10").getValues();
const PLATFORM = sheet.getSheetByName("urls").getRange("B1").getValues();
const OUTPUT_CELL = sheet.getSheetByName("urls").getRange("B5:" + ("K" + sheet.getLastRow()));
console.log(PLATFORM);
// KPI
const lighthouseMetrics = [
"first-contentful-paint",
"largest-contentful-paint",
'interactive',
"cumulative-layout-shift",
"speed-index",
"total-blocking-time"
]
const fieldData = [
"FIRST_CONTENTFUL_PAINT_MS",
"LARGEST_CONTENTFUL_PAINT_MS",
"FIRST_INPUT_DELAY_MS",
"CUMULATIVE_LAYOUT_SHIFT_SCORE"
]
// CALLING FUNCTION
async function fetch_array() {
let URLS_LIST = sheet.getSheetByName("urls").getRange("A5:" + ("A" + sheet.getLastRow())).getValues();
console.log(URLS_LIST)
let arrayData = [];
for (let element of URLS_LIST) {
let dataEl = await getPageSpeedInfo(PLATFORM, element);
let dataRow = produceArray(dataEl);
arrayData.push(dataRow);
}
return OUTPUT_CELL.setValues(arrayData);
}
// PRODUCE ARRAY WITH KPIS
function produceArray(data) {
let kpiArray = [];
fieldData.forEach(function(item) {
let fieldDataRoute = data.loadingExperience.metrics[item].category;
kpiArray.push(fieldDataRoute);
})
lighthouseMetrics.forEach(function(item) {
let lighthouseRoute = data.lighthouseResult.audits[item].displayValue;
kpiArray.push(lighthouseRoute);
})
return kpiArray;
}
// CALL TO API
async function getPageSpeedInfo(strategy, element) {
let pageSpeedUrl = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=' + element + '&key=' + API_STRING + '&strategy=' + strategy;
console.log(pageSpeedUrl);
let response = await UrlFetchApp.fetch(pageSpeedUrl);
let data = await response.getContentText();
return JSON.parse(data);
}

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;
}

How to use EnumProcesses in node-ffi

I was trying to use EnumProcesses with node-ffi. I got code below:
import ffi from 'ffi'
export const psapi = ffi.Library('psapi', {
EnumProcesses: ['bool', ['ulong', 'ulong', 'uint16*']]
})
export class Win32ProcessManager {
public async getProcessList () {
let lpidProcess = ref.alloc('ulong*')
const cb = 1024
const lpcbNeeded = ref.alloc('uint16*')
const res = psapi.EnumProcesses(lpidProcess, cb, lpcbNeeded)
const ulongSize = (ref as any).sizeof.ulong
const totalBytesReturned = lpcbNeeded.readInt16LE()
const processCount = totalBytesReturned / ulongSize
console.log(`processCount: ${processCount}`)
// ??? How to get the value from the lpidProcess?
return lpidProcess
}
}
I tried with ref.get but I encountered errors:
let processId = ref.get(array, 0, ref.types.ulong)
console.log(processId)
const pointerSize = (ref as any).sizeof.pointer
console.log(pointerSize)
let processId2 = ref.get(array, (ref as any).sizeof.pointer, ref.types.ulong)
console.log(processId2)
Errors:
RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to write outside buffer bounds
Anyone knows how to use node-ffi read the array data from dll?
Thanks #DrakeWu-MSFT, I finally got my code works, here are how they looks finally:
import ffi from 'ffi';
import ref from 'ref';
import ArrayType from "ref-array";
export const psapi = ffi.Library('psapi', {
EnumProcesses: ['bool', ['ulong*', 'ulong', 'uint16*']],
});
export class Win32ProcessManager {
public getProcessIdList (): number[] {
const processIdLength = 1024;
const ulongSize = (ref as any).sizeof.ulong;
const cb = processIdLength * ulongSize;
let processIdArray = ArrayType('ulong', processIdLength);
let lpidProcess = ref.alloc(processIdArray);
const lpcbNeeded = ref.alloc('uint16*');
const res = psapi.EnumProcesses(lpidProcess, cb, lpcbNeeded);
if (res) {
const totalBytesReturned = lpcbNeeded.readInt16LE();
const processCount = totalBytesReturned / ulongSize;
const processArray = (lpidProcess as any).deref();
let resultProcessArray: number[] = [];
for (let i = 0; i < processCount; i++) {
resultProcessArray.push(processArray[i]);
}
return resultProcessArray;
} else {
console.error(`Get process list failed with result from EnumProcess: ${res}`);
return [];
}
}
}
I was struggled with getting array data from the pointer, and that was wrong, as #DrakeWu-MSFT said in the comment, because I didn't allocate enough spaces for the buffer, no data can be write into that. With ref-array and a pointer to the array, it works like a charm.

Creating new participant and adding array of assets by reference to it

I have a problem when trying to add a new asset to an array of assets which are part of the participant as a reference.
Here I have SharedAccount participant controlled by its members who are connected via their share in the account.
I want to write a transaction for creating a new SharedAccount by one person. When a person submits a transaction, it should create a share asset if that person and add it to SharedAccount's shares array.
Here's how my code looks like
.cto:
...
participant SharedAccount identified by sharedAccountId {
o String sharedAccountId
--> Share[] shares
o Double balance
o Double originalBalance
}
asset Share identified by shareId {
o String shareId
--> Person shareHolder
o Double amount
}
transaction CreateSharedAccount {
--> Person creator
o String accountName
o Integer amount
}
...
.js:
...
/**
* #param {org.mistral.bulliongrower.CreateSharedAccount} createSharedAccount
* #transaction
*/
async function CreateSharedAccount(createSharedAccount) {
const factory = getFactory();
const NS = 'org.mistral.bulliongrower';
// create share
const share = factory.newResource(NS, 'Share', createSharedAccount.creator.personId + 'SHARE');
share.amount = createSharedAccount.amount;
share.shareHolder = createSharedAccount.creator;
share.shareHolder.balance -= createSharedAccount.amount;
const sharesRegistry = await getAssetRegistry(NS + '.Share');
await sharesRegistry.add(share);
const personRegistry = await getParticipantRegistry(NS + '.Person');
await personRegistry.update(share.shareHolder);
// create sharedAccount
const sharedAcc = factory.newResource(NS, 'SharedAccount', createSharedAccount.accountName);
sharedAcc.shares.push(share);
sharedAcc.balance = createSharedAccount.amount;
sharedAcc.originalBalance = createSharedAccount.amount;
const sharedAccRegistry = await getAssetRegistry(NS + '.SharedAccount');
await sharedAccRegistry.add(sharedAcc);
}
...
I'm not sure if I should use factory.newRelationship and how, when adding a share Asset to SharedAccount.
The error I get in the playground when trying to execute the transaction is
TypeError: Cannot read property 'push' of undefined
try to do this:
/**
* #param {org.mistral.bulliongrower.CreateSharedAccount} createSharedAccount
* #transaction
*/
async function CreateSharedAccount(createSharedAccount) {
const factory = getFactory();
const NS = 'org.mistral.bulliongrower';
// create share
const share = factory.newResource(NS, 'Share', createSharedAccount.creator.personId + 'SHARE');
//const share = factory.newRelationship(NS, 'Share', createSharedAccount.creator.personId + 'SHARE');
share.amount = createSharedAccount.amount;
//share.shareHolder = factory.newRelationship(NS, 'Share', createSharedAccount.creator.personId);
share.shareHolder = createSharedAccount.creator;
share.shareHolder.balance -= createSharedAccount.amount;
const sharesRegistry = await getAssetRegistry(NS + '.Share');
await sharesRegistry.add(share);
const personRegistry = await getParticipantRegistry(NS + '.Person');
await personRegistry.update(share.shareHolder);
// create sharedacc
const sharedAcc = factory.newResource(NS, 'SharedAccount', createSharedAccount.accountName);
//sharedAcc.shares = factory.newRelationship(NS, 'Share', createSharedAccount.creator.personId);
//sharedAcc.shares[0] = factory.newRelationship(NS, 'Share', share.shareId);
// define an array
let sharesArray = [];
sharesArray.push(share);
sharedAcc.shares = sharesArray;
sharedAcc.balance = createSharedAccount.amount;
sharedAcc.originalBalance = createSharedAccount.amount;
// use getParticipantRegistry not getAssetRegistry
const sharedAccRegistry = await getParticipantRegistry(NS + '.SharedAccount');
await sharedAccRegistry.add(sharedAcc);
}
your transaction code should be something like below - some of your references weren't right (take too long to point out all the changes, so you can refer below).
I added a test string (for 'Person') just to show what you would do (to have a reason to update that particular participant registry).
Seems to me that SharedAccount is an asset not a participant. And you would use the appropriate JS API to update that type of registry.
balance is not a field on Person (it is on SharedAccount), but your code was trying to refer to it.
I've left comments for 'alternative ways' for declarations and such like - just by way of info.
/**
* #param {org.mistral.bulliongrower.CreateSharedAccount} createSharedAccount
* #transaction
*/
async function CreateSharedAccount(createSharedAccount) {
const factory = getFactory();
const NS = 'org.example.trading';
// create share
const share = factory.newResource(NS, 'Share', createSharedAccount.creator.personId + 'SHARE');
share.amount = createSharedAccount.amount;
console.log("amount is " + share.amount);
share.shareHolder = createSharedAccount.creator;
// share.shareHolder.balance -= createSharedAccount.amount; // won't work - balance is a field on SharedAccount not Person - moved it below
const sharesRegistry = await getAssetRegistry(NS + '.Share');
await sharesRegistry.add(share);
share.shareHolder.newstr = "123"; // setting 'SOME' field (I added 'newstr' in my model, see below - so as to have a reason to update / give an example
const personRegistry = await getParticipantRegistry(NS + '.Person');
await personRegistry.update(share.shareHolder);
// create sharedAccount
const sharedAcc = factory.newResource(NS, 'SharedAccount', createSharedAccount.accountName);
//let idsArray = new Array(); // alternative, or use implicit below.
let idsArray = [] ;
let shareAssetRelationship = factory.newRelationship(NS, 'Share', share.getIdentifier());
idsArray.push(shareAssetRelationship); // only one element anyway
sharedAcc.shares = idsArray;
sharedAcc.balance = createSharedAccount.amount; // this is a new resource - so balance is eq to trxn amount ?
sharedAcc.originalBalance = createSharedAccount.amount; // original balance is nothing or 'balance' ?....anyway....
const sharedAccRegistry = await getAssetRegistry(NS + '.SharedAccount');
await sharedAccRegistry.add(sharedAcc);
}
The model I used is this:
participant Person identified by personId {
o String personId
o String newstr
}
asset SharedAccount identified by sharedAccountId {
o String sharedAccountId
--> Share[] shares
o Double balance
o Double originalBalance
}
asset Share identified by shareId {
o String shareId
--> Person shareHolder
o Double amount
}
transaction CreateSharedAccount {
--> Person creator
o String accountName
o Integer amount
}

Resources