Is this how to efficiently run a function in a For Loop?

Code : https://rinkeby.etherscan.io/address/0x87660f32382de6cd36b685ae76a54f389af016a4#code

Question :

  1. Is it normal to expect each iteration of the for loop to require a separate 'confirmation' from MetaMask?
  2. Is this very inefficient in terms of gas?

Objective : Change TokenURI in batches. Example: id=0-9999 set to URI1, id=10000-19999 has URI2

Problem : Code works (pasted below), but it appears I have to manually confirm each iteration of the for loop. Also concerned this approach is not gas-efficient.

My Solution

Running below code from browser + MetaMask:

var contract = null;
const ABI = ...
const ADDRESS = "0x87660F32382De6Cd36B685ae76A54f389AF016a4";
contract = new web3.eth.Contract(ABI, ADDRESS);

for (var i = 0; i < 10000; i++) {
var transaction = await contract.methods.setTokenUri(i,"https://URI1/").send({ from: account });
}
for (var j = 10000; j < 20000; j++) {
var transaction = await contract.methods.setTokenUri(j,"https://URI2/").send({ from: account });
}

1 - yes, since for each iteration it is making a new call to the smart contract function.

2 - it is totally inefficient to perform that action in that way

The best thing would be to create an api call to which you pass the id and it will return the data you need

1 Like

Thanks Asmel. I'm a newbie, can you point me to a basic example? Is your idea to make 1 call to the contract then making many thousands of API call which results in only "1 transaction"?

Excuse me, but it is a somewhat broad example to give you an explanation here

1 Like

Understood. Sounds like this is not a simple quick solution. Appreciate the input.