The Token contract has a function that allows the token owner to approve an address for a certain amount. This other address will be able to send up to this amount of the approver's tokens:
function approve(address _spender, uint256 _value) {}
So let's say you have 2 people Alice and Bob. Alice has 3 TokenA and Bob has 4 TokenB. They agree to exchange them. You create the re-usable Trade
contract to make that happen.
contract Trade {
function exchange(address alice,
address tokenA,
uint qtyTokenA,
address bob,
address tokenB,
uint qtyTokenB)
returns (bool success) {
success = Token(tokenA).transferFrom(alice, bob, qtyTokenA)
&& Token(tokenB).transferFrom(bob, alice, qtyTokenB);
if (!success) throw;
}
}
In TokenA, Alice approves the trade contract for 3
. In TokenB, Bob approves the trade contract for 4
. Then someone calls the exchange
function with the proper values.
I understand that, as it stands, there is a security risk whereby Carol calls the method before others, to steal from Alice. IRL, you would have Alice and Bob to both approve the exchange
function call.
Best Answer
To get the price
First you'll have to get the price. You can get price easily by using Chainlink Price Feeds.
Otherwise you can use an oracle to make an API call to an API with the price.
To make it dynamic
You'll need some off-chain service making a call to update periodically. You could use something like the Chainlink alarm clock, or Chainlink cron initiator for it to be automatic. You'd set one of these up to call your price updating contract (deployed from above) at the intervals you'd please.
Hope it helps.