contract FixedRateSwap {
uint256 rate_;
IERC20 token_;
function swap() notReentrant /* because of msg.value being unsafe */ {
token_.transfer(msg.sender, msg.value * rate_);
}
}
function useSimulatedTokenAmount(inputTokenAmount) {
const [rate, setRate] = useState();
useEffect(() => {
const rate = await myContract.rate_();
setRate(rate);
}, [])
const result = useMemo(() => {
if (rate !== undefined) {
return inputTokenAmount * rate;
}
}, [rate, inputTokenAmount]);
return result;
}
contract FixedRateSwap {
uint256 rate_;
IERC20 token_;
function swap() notReentrant /* because of msg.value being unsafe */ returns (uint256) {
uint256 tokenToSend = msg.value * rate_;
token_.transfer(msg.sender, tokenToSend);
return tokenToSend;
}
}
function useSimulatedTokenAmount(inputTokenAmount) {
const [result, setResult] = useState();
useEffect(() => {
let detached = false;
initiateFetching();
return () => { detached = true; }
async function initiateFetching() {
const resultFromContract = await contract.swap.staticCall(inputTokenAmount);
if (detached) return;
setResult(resultFromContract);
}
}, [inputTokenAmount])
result
}
def create_fork():
"""
Each simulation session should start from fork creation.
:returns fork_id
"""
response = requests.post(
f'https://api.tenderly.co/api/v1/account/{TENDERLY_USER}/project/{TENDERLY_PROJECT}/fork',
json={
"network_id": '1',
"chain_config": {
"chain_id": 11,
"shanghai_time": 1677557088,
},
},
headers={
'X-Access-Key': TENDERLY_ACCESS_KEY,
},
)
response.raise_for_status()
return response.json()['simulation_fork']['id']
def create_transaction_in_fork(fork_id, from_address, to_address, data, value):
url = f'https://api.tenderly.co/api/v1/account/{TENDERLY_USER}/project/{TENDERLY_PROJECT}/fork/{fork_id}/simulate'
resp = requests.post(url, json={
"from": from_address,
"to": to_address,
"input": data,
"save": True,
"skip_fork_head_update": False,
"gas": 8000000,
"value": str(value),
}, headers={
'X-Access-Key': TENDERLY_ACCESS_KEY,
},)
resp.raise_for_status()
create_transaction_in_fork(fork_id,
"0x3E3C51857c381307e295780f0B6b5654A3717743",
"0x4cfF0951253cAD983b29F5ca994D4d7dc81D94Fc",
"0x",
1_000_000_000)
# now you can observe results, all of the state variables etc using the following
fork_rpc = f'https://rpc.tenderly.co/fork/{fork_id}'
function useExpectedUSDCbalance(transactionV0) {
const [simulationResults, setSimulationResults]
useEffect(() => {
let detached = false;
initiateSimulation();
return () => { detached = true; }
async function initiateSimulation() {
const result = await connection.simulateTransaction(transactionV0, {
accounts: {
addresses: [usersAccountForUSDC],
encoding: "base64"
}
})
if (detached) return;
if (result.value.err) {
setSimulationResults({ ok: false })
} else {
setSimulationResults({
ok: true,
newBalances: [
parseBalance(result.value.accounts[0]),
]
})
}
}
}, [transactionV0]);
return simulationResults;
}