Direct calling of swap in my smart contract always fails with token transfer errors

Hello, I'm writing a custom smart contract that calls swaps directly. I have a series of operations to perform, the first "swap" goes through, calls back as standard and then ... the balance either doesn't land in my account, or doesn't get transfered to target I'm literally getting every single possible error that has to do with transfer of tokens

[
"execution reverted: Pancake: K",
"execution reverted: BEP20: transfer amount exceeds balance",
"execution reverted: AnyswapV3ERC20: transfer amount exceeds balance",
"execution reverted: SafeMath: subtraction overflow"
and some more...
]

because that's so simple let me just write a dummy for my logic:

function foo(){
//have tokens already from swap number 0
    **transfer (next_pair, coin.balanceOf(address(this)))** //doesn't work
   //also tried:
  **safeTransferFrom(...)** //doesn't work either)
   
//and so
    do_next_swap(...) 
//reverts 99.99% of the time
}

I've gradually fixed bug by bug in my code, and so I don't think I understand fully how this works.

I'm sending the tokens directly to the pair I'm about to swap on then call its swap(), correct?

I could rewrite to something easier, sure, but I need to make this logic happen.

Also, few things...

  • how does the pair even know it's me. It always baffled me about how this system works:
  • there's no mapping by pair contract to keep track of who sends it funds
  • pair calls self.balanceOf() and self.getReserves() -> how doesn't that create a major security issue? There's 100s of transactions per second so something is there that I can't find studying this for hours and hours that makes it not get wrong reads each time. Does it clone the state of the blockchain and perform simulations for each interacting contract? I can't think of any other way to prevent major collusion because it literally doesn't map that address x sent it y tokens, it just calls self.balance. How does pair contract know that the swap caller is the one who has just sent it 5000 of token x? I can't see any mapping there, so how does it correlate those two actions? In most code I've seen there's a ; between sending funds to pair and calling swap. If the system worked in real time, and not as it does, obviously this could be a major security risk. So where's the code that ensures a cluster of transactions doesn't mess up pair's self.balance calls and the like??

Could someone knowledgable enough clue me in as to how to successfully transfer the funds to the pair account so that it 'registers' or something. Also, I'm very worried about overflow error there, I'm literally transferring self.balanceOf - > HOW can that result in a sub overflow?