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

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

Related

Solana SPL Token: Signature Undefined

I'm facing some issue when sending NFT with solana, Signature verification failed,
const transaction = new Transaction().add(
createTransferInstruction(
fromAccount.address, // ?? Is this suppose be the publicKey or Keypair publicKey
toAccount.address,// ?? Is this wallet address ??
tokenMintAddress, // SLP token PublicKey
1,
[],
TOKEN_PROGRAM_ID
)
)
I'm not really sure what parameters need to pass to this function to verify the signature.
Here is my full snippets
const key = process.env.NEXT_PUBLIC_PRIVATE_KEY;
const myKeypair = Keypair.fromSecretKey(bs58.decode(key));
const tokenMintAddress = new PublicKey('wallet_address'); // NFT tokenAddress
const nftReceiver = new PublicKey('ntf_token_'); // target wallet address
const fromAccount: Account = await getOrCreateAssociatedTokenAccount(
connection,
myKeypair,
tokenMintAddress,
myKeypair.publicKey,
)
const toAccount = await getOrCreateAssociatedTokenAccount(
connection,
myKeypair.publicKey,
tokenMintAddress,
nftReceiver
)
console.log('fromAccount', fromAccount.address.toString())
console.log('toAccount', toAccount.address)
const randKey = Keypair.generate();
const transaction = new Transaction().add(
createTransferInstruction(
fromAccount.address,
toAccount.address,
tokenMintAddress,
1,
[],
TOKEN_PROGRAM_ID
)
)
const {
context: { slot: minContextSlot },
value: { blockhash, lastValidBlockHeight }
} = await connection.getLatestBlockhashAndContext();
const signature = await sendTransaction(transaction, connection, {minContextSlot, maxRetries: 4}).catch(e => console.log('Signature Catch: ', e))
but based on the docs, this is some params but not sure what is the correct value for this
#param source — Source account
#param destination — Destination account
#param owner — Owner of the source account
#param amount — Number of tokens to transfer
#param multiSigners — Signing accounts if owner is a multisig
#param programId — SPL Token program account
#return — Instruction to add to a transaction

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

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