How does a User account own an ERC20 Token - ethereum

This question is a little conceptual, so hopefully this picture will help clear up my misunderstanding.
Image there is a crowdsale smart contract deployed on address 0x2. A User at address 0x01 buys a token.
Here is my understanding of what happens:
The crowdsale contract (# address: 0x2) accepts ether from the user account (# address: 0x1)
The crowdsale contract stores 0x1 as having purchased a token (important: this information is stored in the smart contract #address 0x2)
Now my Question: If 0x1 is a user account (and not a smart contract) there is no code at address 0x1. I thought a user account just consisted of an address + ether associated with the address, how can it also store the fact that 0x1 owns an ERC20 token? For example, I can login to MetaMask and (before clicking the "add token" option) MetaMask can see that I have a token... how is this possible?

Every ERC20 contract has the following function:
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
Your wallet just calls this function from the known token contracts with your address. Since it's a view function it doesn't cost any gas.
I recon most ERC20 token get added rather quickly to a wallet like Metamask or MEW. But if your balance doesn't automatically show, you can add the contract address manually (in MEW at least, not sure about Metamask) and it will show up afterwards.

In solidity there are two ways to get the address of the person who sent the transaction
tx.origin
msg.sender
In your example, in the method inside ERC20 Token.sol, the value tx.origin will be 0x1 and msg.sender will be 0x2
So to answer your question, how does the ERC20 token know about 0x2 is: it depends on how the token contract is written and whether it uses tx.origin or msg.sender. I would imagine it uses msg.sender, because that is the more prevalent one.
If it does use msg.sender you can still make the crowdsale contract work by first buying the tokens and then immediatelly transfering the tokens from the crowdsale contract to the caller.
For more information, refer to What's the difference between 'msg.sender' and 'tx.origin'?

how can it also store the fact that 0x1 owns an ERC20 token?
Token transfers, or transfers in accounting in general, are kept in a ledger. In this case, the ledger is ERC-20 smart contract that internally keeps balances who owns and what in its balances mapping. Or, the smart contract manage the storage (EVM SSTORE instructions) where the records of ownership are kept.
Note that some other blockchains, like Telos and EOS (and mayne Solana) might be opposite and there the storage is maintained on the user account (user account has associated RAM and tables for any token user owns).

Related

Transfer ERC20 token without ETH

I would like to transfer ERC20 tokens from a wallet who don't own ETH to another wallet who own ETH and who can pay gas fee.
Do you know if it is possible to made a transfer of ERC20 tokens and to let the receiver wallet pay fees ?
TLDR: Not possible, unless the token contract explicitly allows it. Or unless the token holder is also the block producer.
Transaction fees are paid in ETH (or generally, native currency of the network - for example BNB on Binance Smart Chain, MATIC on Polygon, ...). So in most cases, you need to pay ETH to execute either the transfer() function if you want to send the tokens from your address, or the approve() function if you want someone else to transfer tokens from your address.
Very few token contracts implement delegated transfer mechanism on top of the ERC20 standard. There's currently no standardized way to perform a delegated transfer, so each contract might have a different implementation. The token holder uses their private key to sign a predetermined message saying how many tokens they want to transfer to which address. The message also usually contains a nonce or a timestamp to prevent signature replay attack. Token holder passes the message offchain to the transaction sender, and then the transaction sender executes a function of the token contract built specifically for delegated transfers (note that the transaction sender pays the fee to execute this function). The contract validates the signature, and performs the transfer. Again, most token contracts do not implement this mechanism.
One more exception from the rule is a block producer. When you create a new block, you can fill it with transactions not only from the mempool but also with your own transactions. You can build a transaction with 0 gas price, and then include it in the block that you're producing. This way you're also able to send tokens for free.

ethereum token address in Remix

I am following a tutorial for a crowdfunding smart contract that accepts a token from users.
I have developed a simple ERC20 token, then I deploy the crowdfunding smart contract giving the address of the ERC20 token as the token accepted from users.
I would like to use the same smart contract with ethers. In other words, I would like people to fund the smart contract with ethers (using ganache and remix, my 10 users have 100 ethers each). Therefore, I need to deploy the smart contract giving the ethereum token address. What is the ether's address?
I am working with remix and ganache under web3 provider.
The native token of any EVM network (in your case Ether) does not have any address.
In Solidity, you can:
Accept ETH with the payable function modifier
Validate the amount sent by the user stored in the msg.value global property. The variable is read-only, the sender chooses how much they send and your contract can only validate that.
Send ETH with the native .transfer() function of address payable (extension of address) type. Do not confuse with the ERC20 custom transfer() function - these are two separate functions even though they have the same name.
pragma solidity ^0.8;
contract MyContract {
address owner = address(0x123);
// `payable` modifier allows the function to accept ETH
function foo() external payable {
// validate that the received amount is 1e18 wei (1 ETH)
require(msg.value == 1e18);
// typecast `address` variable (name `owner`)
// to `address payable` and effectively redirect the received value
// with the native `transfer()` function of the `address payable` type
payable(owner).transfer(msg.value);
}
}
If you need to work with approvals and other ERC-20 features, many contracts use WETH (Wrapped Ether) token that uses tokenomics supposed to maintain the same WETH price as ETH has, instead of using the regular ETH. Its production address depends on the network where its deployed. For example:
Ethereum: 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Polygon: 0x7ceb23fd6bc0add59e62ac25578270cff1b9f619

How to approve Token to self-deployed contract

My ultimate purpose is to swap some tokens across pancakeswap babyswap apeswap atomicly. So I build a contract(called ContractA) to run a bunch of swaps in a transaction. I transfer some USDT token into ContractA. But ContractA is not approved to transfers USDT by the USDT contract.
I known how to approve Metamask address to transfer USDT, but how to do it for a Contract?
In order to control an ERC20 token from a smart contract, first you need to create an instance of it. To do that, first you need to import ERC20 to your contract, and then just create an ERC20 type function giving it the token address you want to manage. It would be something like this:
// Some code...
import "#openzeppelin/contract/token/ERC20/ERC20.sol";
// Some more code...
contract exampleContract {
// Example of an ERC20 token instance
ERC20 USDTToken = ERC20("USDT Contract Address Here");
// Approve USDT
USDTToken.approve(address(this), _amount);
}
Then you will be able to manage the token, always following the ERC20 standard, as you want.
Hope you find this information useful :)

How do Ethereum ERC-20 Contracts for Tokens Interact

Learning Solidity along with token development.
I'm having a hard time understanding how tokens with multiple smart contracts interact with each other.
I've read through other tokens with multiple contracts on GitHub and reviewed contracts on OpenZeppelin but they all appear somewhat orphaned.
Let's say we developed a token that has a supply and tracks wallet address to amount using a map. The contract is released and is given an address. Admin or privilege methods are protected via owner address validation. Then we release a second contract that needs to make apply a fee for transactions.
How does the second (token transaction fees) contract interact with the data stored on the first (token contract)? Does the second contract need to also verify ownership?
Any contract on Ethereum can interact with any other contract by using Interfaces. You can call methods from the second contract on the first contract for an ERC20 token as below:
Define ERC20 Interface
interface ERC20 {
function balanceOf(address account) external view returns (uint256);
}
Use the interface and token contract address to call methods on the first contract:
ERC20(tokenContractAddress).balanceOf(0xabcd....);
The similar approach can be used for any contracts

Can third party send an ERC20 token transaction to ethereum blockchain?

I want to create a smart contract which people can transfer tokens without ether in their wallet.
Suppose A want to transfer ERC20 tokens to B, but he does not have ether in his wallet.
Does third party C can send the transaction for A and therefore pay the gas? Is it possible to create a function in the contract for this usgae?
I have searched online for a soloution and could not find one.
This is a key issue of Ethereum dApp development, but also of tokens. Here is a very old thread on Ethereum Stack Exchange, and also this one.
There are 2 options with their pros and cons:
Use signatures
Every function in your smart contract must have signature parameter.
People who want to interact with the smart contract must sign the function parameters with their account's private key and send it to the smart contract owner (via any communication channel).
The owner then submits the parameters along with the signature to the blockchain, paying for gas. The signature guarantees that the message was approved by the user.
Refund used gas at the end of the transaction. A modifier refundGasCost can be used for this (see below).
But (1) is really hard to apply to token transfers where you just don't know who uses the token and (2) does not really address the issue.
There is a lot happening recently, there is this blog post about How to save your Ethereum Dapp users from paying gas for transactions, and since you ask about tokens, there is an ERC that suggests to Pay transfers in tokens instead of gas, in one transaction which would be nice if you have tokens but no ETH.
I hope this helps.
Exactly this case is already defined in the ERC20 standard. Its this function:
function transferFrom(address from, address to, uint tokens) public returns (bool success);
But before party C could use it and send tokens from A to B, A would have to approve C to do this via the following function, which is also defined in the ERC20 standard:
function approve(address spender, uint tokens) public returns (bool success);
No, in a standard ERC20 token contract, the token holder must initiate at least one transaction (to call transfer() or approve()), and a transaction must always be paid for by its initiator.