# 學習solidity的一個簡單智慧合約（2）——對衝

30天后，允許A或B“重新啟用“合約以傳送價值x美元的以太幣（重新查詢資料提供合約，以獲取新價格並計算）給A並將剩餘的以太幣傳送給B。

``````pragma solidity ^0.4.0;
//完成金融衍生品對衝合約
/*等待A輸入1000以太幣。.

30天后，允許A或B“重新啟用“合約以傳送價值x美元的以太幣
（重新查詢資料提供合約，以獲取新價格並計算）給A並將剩餘的以太幣傳送給B。*/``````

``````contract hedge{
struct giver{
bool yn;//是否投票
uint amount;//金額
}
struct reciever{
bool yn;//是否投票
uint amount;//金額
}
``````
``````function initializeA(address giverA){
// A方人初始化
givers[giverA].amount = 1000 ether;
givers[giverA].yn = true;
p1 = giverA;
givers[giverA].amount = 0 ether;
}
// B方人初始化
recievers[recieverB].amount = 1000 ether;
recievers[recieverB].yn = true;
p2 = recieverB;
recievers[recieverB].amount = 0 ether;
}``````

``````uint  hedgevalue;
function hedging1(uint exchangerate) returns (uint){
hedgevalue = 1000 ether /exchangerate ;
return  hedgevalue;
}``````

bool success; function hedging2(uint exchangerate , uint time) returns(bool success){ if(time != 30) return false ; if(givers[p1].yn == false) return false; if(recievers[p2].yn == false) return false; givers[p1].amount = hedgevalue * exchangerate; recievers[p2].amount
= 2000 ether – hedgevalue * exchangerate; return true ; } function checkA(address giverA)returns(uint){ if(success) givers[giverA].amount = givers[p1].amount ; else givers[giverA].amount = 1000 ether; return givers[giverA].amount; } function checkB(address
recieverB)returns(uint){ if(success) recievers[recieverB].amount = recievers[p2].amount; else recievers[recieverB].amount = 1000 ether; return recievers[p2].amount; }}

``````struct giver{
bool yn;//是否投票
uint amount;//金額
}
struct reciever{
bool yn;//是否投票
uint amount;//金額
}``````

``````function initializeA(address giverA){
// A方人初始化
givers[giverA].amount = 1000 ether;
givers[giverA].yn = true;
p1 = giverA;
givers[giverA].amount = 0 ether;
}
// B方人初始化
recievers[recieverB].amount = 1000 ether;
recievers[recieverB].yn = true;
p2 = recieverB;
recievers[recieverB].amount = 0 ether;
}``````

``````uint  hedgevalue;
function hedging1(uint exchangerate) returns (uint){
hedgevalue = 1000 ether /exchangerate ;
return  hedgevalue;
}``````

`````` bool success;
function hedging2(uint exchangerate , uint time) returns(bool success){
if(time != 30) return false ;
if(givers[p1].yn == false) return false;
if(recievers[p2].yn == false) return false;
givers[p1].amount = hedgevalue * exchangerate;
recievers[p2].amount = 2000 ether - hedgevalue * exchangerate;
return true ;
}``````