Get total amount of tokens received from a specific address using Web3.js - web3js

in a scenario, WalletA is receiving TokenB in a regular basis from AddressC.
AddressC only sends TokenB, nothing else.
in etherscan or bscscan it is simple to see how much of TokenB is received in WalletA and "from" field is there so you can do some math to get total.
How can this be done using web3? I couldn't find any relevant api call in web3 documents.
I can get total balance of TokenB in WalletA by web3.js but I need the count of tokens only sent from AddressC.
Thanks.

As per the ERC-20 standard, each token transfer emits a Transfer() event log, containing the sender address, receiver address and token amount.
You can get the past event logs using the web3js general method web3.eth.getPastLogs(), encode the inputs and decode the outputs.
Or you can supply ABI JSON of the contract (it's enough to use just the Transfer() event definition in this case) and use the web3js method web3.eth.Contract.getPastEvents(), which encodes the inputs and decodes the outputs for you based on the provided ABI JSON.
const Web3 = require('web3');
const web3 = new Web3('<provider_url>');
const walletA = '0x3cd751e6b0078be393132286c442345e5dc49699'; // sender
const tokenB = '0xdAC17F958D2ee523a2206206994597C13D831ec7'; // token contract address
const addressC = '0xd5895011F887A842289E47F3b5491954aC7ce0DF'; // receiver
// just the Transfer() event definition is sufficient in this case
const abiJson = [{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}];
const contract = new web3.eth.Contract(abiJson, tokenB);
const fromBlock = 10000000;
const toBlock = 13453500;
const blockCountIteration = 5000;
const run = async () => {
let totalTokensTranferred = 0;
for (let i = fromBlock; i <= (toBlock - blockCountIteration); i += blockCountIteration) {
//console.log("Requesting from block", i, "to block ", i + blockCountIteration - 1);
const pastEvents = await contract.getPastEvents('Transfer', {
'filter': {
'from': walletA,
'to': addressC,
},
'fromBlock': i,
'toBlock': i + blockCountIteration - 1,
});
}
for (let pastEvent of pastEvents) {
totalTokensTranferred += parseInt(pastEvent.returnValues.value);
}
console.log(totalTokensTranferred);
}
run();

Related

Sending SPL tokens on solana network

I am using solana web3.js to send SOL tokens. I am using below code to send SOL tokens to other address:
import * as web3 from '#solana/web3.js';
// ...
// later
const sendToAddress = async(param) => {
const connection = new web3.Connection(web3.clusterApiUrl('devnet'));
let accountFromSecret = web3.Keypair.fromSecretKey(param.privateKey);
let base58ToSend = new web3.PublicKey(param.toAddress);
var transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: accountFromSecret.publicKey,
toPubkey: base58ToSend,
lamports: Number(param.amount), // number of SOL to send
}),
);
var signature = await web3.sendAndConfirmTransaction(connection, transaction, [
accountFromSecret,
]);
}
With this I am able to successfully send SOL.
But I also want to send other SPL tokens like Raydium (RAY), Star Atlas (ATLAS), ORBS. How do I send these SPL tokens?

Send Token erc20 usign Web3.js( Private Key. Account unloked. SignTransaction )

If send to Avax but not my Erc20 Token. Thank you for your help
First we get the url of the rcp.
Then we create an instance of web3.js.
Then with our private key you create an account.
We create an instance of our contract by passing it the abi and the address of the contract as parameters.
We estimate the gas with estimateGas passing it an object that indicates the function of the abi that is going to be used, the address of the contract, to whom it is going to be sent.
We create a transfer object
We obtain the balance to know the initial balance
We sign the transaction with our private key
We send the transaction
We get the bottom line
My code
`
const transferToeknErc20 = async () => {
const amount = '1000000000000000';
const jsonInterface = [{"inputs":[],"stateMutability":....
const contractAddress = '0x7B9...';
const privateKeyWallet = '14f...';
const chainId = 43113;
const address_to = '0x86...';
//NODE
const NODE_URL = "https://api.avax-test.network/ext/bc/C/rpc";
//WEB3
const web3Global = new Web3( new Web3.providers.HttpProvider(NODE_URL));
//Creamos una cuenta con la llave privada
const account = web3Global.eth.accounts.privateKeyToAccount(privateKeyWallet);
//CONTRACT
const contract = new web3Global.eth.Contract(jsonInterface, contractAddress);
//////////////////////////////////////////////////////////////////////////////
let estimateGas = await web3Global.eth.estimateGas({
value: '0x0', // Only tokens
data: contract.methods.transfer(address_to, amount).encodeABI(),
from: account.address,
to: address_to
});
//////////////////////////////////////////////////////////////////////////////
const transactionObject = {
value:'0x0',
data:contract.methods.transfer(address_to, amount).encodeABI(),
from: account.address,
to: address_to,
gas:web3Global.utils.toHex(Math.round(estimateGas * 1.10)),
gasLimit:web3Global.utils.toHex(Math.round(estimateGas * 1.10)),
chainId,
}
//get balanace
let balance = await contract.methods.balanceOf(account.address).call();
console.log('balance init', balance)
//Sing
const signText = await web3Global.eth.accounts.signTransaction(transactionObject, privateKeyWallet);
//Send Transaction
const reciep = await web3Global.eth.sendSignedTransaction(signText.rawTransaction);
//get balanace
balance = await contract.methods.balanceOf(account.address).call();
console.log('balance end', balance)
return null;
///////////////////////////////////////////////////////////////////////////////////////
}
`

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

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

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 */)

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");

Resources