1/ how will this be stored?
tokens["DAI","USDT","aakash"] = [0x6B17..., 0xA0b8...., 0xD2ee52...];
2/ best way to achieve access to such a mapping from my contract. And if not how?
to access the tokens[]
you need two things:
- Solidity function: e.g.
function getTokenAddress(string memory TokenName) public view returns(address){
return tokens[TokenName];
}
- Call solidity functions with your favorate programming language. e.g. use modules web3JS, ether, etc. Use call() & send() functions to interact with smart contract. take reference from docs: https://web3js.readthedocs.io/en/v1.7.3/web3-eth-contract.html
To upgrade your smart contract, add 2 more functions:-
- function to rewrite & add new address for a tokenName:
function addToken(string memory TokenName,address TokenAddress) public {
tokens[TokenName]=TokenAddress;
}
- function to Delete Token and Address:
function deleteTokenAndAddress(string memory TokenName) public{
delete tokens[TokenName];
}
Complete correct solidity codes:-
//SPDX-License-Identifier: MIT
pragma solidity >0.8.0 <0.9.0;
contract calculate{
mapping (string => address) public tokens;
constructor() {
setUpTokens();
}
function setUpTokens() public {
tokens["DAI"] = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
tokens["USDC"] = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
tokens["USDT"] = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
tokens["BUSD"] = 0x4Fabb145d64652a948d72533023f6E7A623C7C53;
}
// eg. getTokenAddress("DAI") will return DAI address above
function getTokenAddress(string memory TokenName) public view returns(address){
return tokens[TokenName];
}
function addToken(string memory TokenName,address TokenAddress) public {
tokens[TokenName]=TokenAddress;
}
function deleteTokenAndAddress(string memory TokenName) public{
delete tokens[TokenName];
}
}