/
Cip30Mock.purs
228 lines (217 loc) · 7.64 KB
/
Cip30Mock.purs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
module Ctl.Internal.Wallet.Cip30Mock
( withCip30Mock
, WalletMock
( MockFlint
, MockGero
, MockNami
, MockLode
, MockNuFi
, MockGenericCip30
)
) where
import Prelude
import Cardano.AsCbor (decodeCbor, encodeCbor)
import Cardano.Types
( Credential(PubKeyHashCredential)
, StakeCredential(StakeCredential)
)
import Cardano.Types.Address (Address(RewardAddress))
import Cardano.Types.NetworkId (NetworkId(MainnetId, TestnetId))
import Cardano.Types.PrivateKey as PrivateKey
import Cardano.Types.PublicKey as PublicKey
import Cardano.Types.TransactionUnspentOutput as TransactionUnspentOutput
import Contract.Monad (Contract)
import Control.Monad.Error.Class (liftMaybe, try)
import Control.Monad.Reader (ask)
import Control.Monad.Reader.Class (local)
import Control.Promise (Promise, fromAff)
import Ctl.Internal.Contract.Monad (getQueryHandle)
import Ctl.Internal.Helpers (liftEither)
import Ctl.Internal.Wallet
( Wallet
, WalletExtension
( LodeWallet
, NamiWallet
, GeroWallet
, FlintWallet
, NuFiWallet
, GenericCip30Wallet
)
, mkWalletAff
)
import Ctl.Internal.Wallet.Key
( KeyWallet(KeyWallet)
, PrivatePaymentKey
, PrivateStakeKey
, privateKeysToKeyWallet
)
import Data.Array as Array
import Data.ByteArray (byteArrayToHex, hexToByteArray)
import Data.Either (hush)
import Data.Foldable (fold, foldMap)
import Data.Function.Uncurried (Fn2, mkFn2)
import Data.Map as Map
import Data.Maybe (Maybe(Just), maybe)
import Data.Newtype (unwrap, wrap)
import Data.UInt as UInt
import Effect (Effect)
import Effect.Aff (Aff)
import Effect.Aff.Class (liftAff)
import Effect.Class (liftEffect)
import Effect.Exception (error)
import Effect.Unsafe (unsafePerformEffect)
import Partial.Unsafe (unsafePartial)
data WalletMock
= MockFlint
| MockGero
| MockNami
| MockLode
| MockNuFi
| MockGenericCip30 String
-- | Construct a CIP-30 wallet mock that exposes `KeyWallet` functionality
-- | behind a CIP-30 interface and uses Ogmios to submit Txs.
-- | The wallet is injected directly to `window.cardano` object, under the
-- | name corresponding to provided `WalletMock`. It works even in NodeJS
-- | (we introduce a global `window` object and delete it afterwards).
-- |
-- | Note that this function will refuse to overwrite existing wallet
-- | with the mock, so the users should disable their browser extensions
-- | before running it in the browser.
-- |
-- | Note that this function implements single-address light wallet logic, so
-- | it will have to be changed a lot to successfully mimic the behavior of
-- | multi-address wallets, like Eternl.
withCip30Mock
:: forall (a :: Type)
. KeyWallet
-> WalletMock
-> Contract a
-> Contract a
withCip30Mock (KeyWallet keyWallet) mock contract = do
cip30Mock <- mkCip30Mock keyWallet.paymentKey
keyWallet.stakeKey
deleteMock <- liftEffect $ injectCip30Mock mockString cip30Mock
wallet <- liftAff mkWalletAff'
res <- try $ local _ { wallet = Just wallet } contract
liftEffect deleteMock
liftEither res
where
mkWalletAff' :: Aff Wallet
mkWalletAff' = case mock of
MockFlint -> mkWalletAff FlintWallet
MockGero -> mkWalletAff GeroWallet
MockNami -> mkWalletAff NamiWallet
MockLode -> mkWalletAff LodeWallet
MockNuFi -> mkWalletAff NuFiWallet
MockGenericCip30 name -> mkWalletAff (GenericCip30Wallet name)
mockString :: String
mockString = case mock of
MockFlint -> "flint"
MockGero -> "gerowallet"
MockNami -> "nami"
MockLode -> "LodeWallet"
MockNuFi -> "nufi"
MockGenericCip30 name -> name
type Cip30Mock =
{ getNetworkId :: Effect (Promise Int)
-- we ignore both the amount parameter and pagination:
, getUtxos :: Effect (Promise (Array String))
-- we ignore the amount parameter:
, getCollateral :: Effect (Promise (Array String))
, getBalance :: Effect (Promise String)
-- we ignore pagination parameter:
, getUsedAddresses :: Effect (Promise (Array String))
, getUnusedAddresses :: Effect (Promise (Array String))
, getChangeAddress :: Effect (Promise String)
, getRewardAddresses :: Effect (Promise (Array String))
-- we ignore the 'isPartial' parameter
, signTx :: String -> Promise String
, signData ::
Fn2 String String (Promise { key :: String, signature :: String })
}
mkCip30Mock
:: PrivatePaymentKey -> Maybe PrivateStakeKey -> Contract Cip30Mock
mkCip30Mock pKey mSKey = do
env <- ask
queryHandle <- getQueryHandle
let
getCollateralUtxos utxos = do
let
pparams = unwrap env.ledgerConstants.pparams
coinsPerUtxoByte = pparams.coinsPerUtxoByte
maxCollateralInputs = UInt.toInt $
pparams.maxCollateralInputs
mbCollateral = fold $
(unwrap keyWallet).selectCollateral coinsPerUtxoByte
maxCollateralInputs
utxos
pure mbCollateral
ownUtxos = do
let ownAddress = (unwrap keyWallet).address env.networkId
liftMaybe (error "No UTxOs at address") <<< hush =<< do
queryHandle.utxosAt ownAddress
keyWallet = privateKeysToKeyWallet pKey mSKey
addressHex =
byteArrayToHex $ unwrap $ encodeCbor
((unwrap keyWallet).address env.networkId :: Address)
mbRewardAddressHex = mSKey <#> \stakeKey ->
let
stakePubKey = PrivateKey.toPublicKey (unwrap stakeKey)
stakePubKeyHash = PublicKey.hash stakePubKey
rewardAddress = RewardAddress
{ networkId: env.networkId
, stakeCredential:
StakeCredential $ PubKeyHashCredential stakePubKeyHash
}
in
byteArrayToHex $ unwrap $ encodeCbor rewardAddress
pure $
{ getNetworkId: fromAff $ pure $
case env.networkId of
TestnetId -> 0
MainnetId -> 1
, getUtxos: fromAff do
utxos <- ownUtxos
collateralUtxos <- getCollateralUtxos utxos
let
collateralOutputs = collateralUtxos <#> unwrap >>> _.input
-- filter out UTxOs that will be used as collateral
utxoMap =
Map.filterKeys (not <<< flip Array.elem collateralOutputs) utxos
pure $ byteArrayToHex <<< unwrap <<< encodeCbor <$>
TransactionUnspentOutput.fromUtxoMap utxoMap
, getCollateral: fromAff do
utxos <- ownUtxos
collateralUtxos <- getCollateralUtxos utxos
pure $ byteArrayToHex <<< unwrap <<< encodeCbor <$> collateralUtxos
, getBalance: unsafePartial $ fromAff do
utxos <- ownUtxos
let value = foldMap (_.amount <<< unwrap) $ Map.values utxos
pure $ byteArrayToHex $ unwrap $ encodeCbor value
, getUsedAddresses: fromAff do
pure [ addressHex ]
, getUnusedAddresses: fromAff $ pure []
, getChangeAddress: fromAff do
pure addressHex
, getRewardAddresses: fromAff do
pure (maybe [] pure mbRewardAddressHex)
, signTx: \str -> unsafePerformEffect $ fromAff do
txBytes <- liftMaybe (error "Unable to convert CBOR") $ hexToByteArray
str
tx <- liftMaybe (error "Failed to decode Transaction CBOR")
$ decodeCbor
$ wrap txBytes
witness <- (unwrap keyWallet).signTx tx
pure $ byteArrayToHex $ unwrap $ encodeCbor witness
, signData: mkFn2 \_addr msg -> unsafePerformEffect $ fromAff do
msgBytes <- liftMaybe (error "Unable to convert CBOR") $
hexToByteArray msg
{ key, signature } <- (unwrap keyWallet).signData env.networkId
(wrap msgBytes)
pure
{ key: byteArrayToHex $ unwrap key
, signature: byteArrayToHex $ unwrap signature
}
}
-- returns an action that removes the mock.
foreign import injectCip30Mock :: String -> Cip30Mock -> Effect (Effect Unit)