86 lines
2.8 KiB
Erlang
86 lines
2.8 KiB
Erlang
-module(toy_caller).
|
|
|
|
-export([new_keys/0, get_source/0, deploy/3]).
|
|
|
|
|
|
new_keys() ->
|
|
#{public := PubKey, secret := SecKey = <<K:32/binary, _/binary>>} = ecu_eddsa:sign_keypair(),
|
|
Phrase = gd_key_master:encode(K),
|
|
ID = gmser_api_encoder:encode(account_pubkey, PubKey),
|
|
{ID, SecKey, Phrase}.
|
|
|
|
get_source() ->
|
|
file:read_file("counter.aes").
|
|
|
|
|
|
deploy(Source, PubKey, SecKey) ->
|
|
case compile(Source) of
|
|
{ok, Build} -> deploy2(Build, PubKey, SecKey);
|
|
Error -> Error
|
|
end.
|
|
|
|
deploy2(Build, PubKey, SecKey) ->
|
|
{ok, #{"network_id" := ChainID}} = hz:status(),
|
|
NetworkID = list_to_binary(ChainID),
|
|
{ok, Height} = hz:top_height(),
|
|
{ok, Nonce} = hz:next_nonce(PubKey),
|
|
TTL = Height + 10000,
|
|
GasPrice = hz:min_gas_price(),
|
|
Gas = 5000000,
|
|
Amount = 0,
|
|
InitArgs = [], % NOTE: This would be a list of strings, had this contract arguments
|
|
case hz:contract_create_built(PubKey,
|
|
Nonce, Amount, TTL, Gas, GasPrice,
|
|
Build, InitArgs) of
|
|
{ok, CreateTX} -> deploy3(SecKey, CreateTX, NetworkID);
|
|
Error -> gd_v_devman:trouble(Error)
|
|
end.
|
|
|
|
deploy3(SecKey, CreateTX, ChainID) ->
|
|
SignedTX = sign_tx_hash(CreateTX, SecKey, ChainID),
|
|
case hz:post_tx(SignedTX) of
|
|
{ok, Data = #{"tx_hash" := TXHash}} ->
|
|
ok = io:format("The transaction hash is: ~p", [TXHash]),
|
|
deploy4(Data);
|
|
{ok, WTF} ->
|
|
gd_v_devman:trouble({error, WTF});
|
|
Error ->
|
|
gd_v_devman:trouble(Error)
|
|
end.
|
|
|
|
deploy4(#{"tx_hash" := TXHash}) ->
|
|
case hz:tx_info(TXHash) of
|
|
{ok, #{"call_info" := #{"return_type" := "ok", "contract_id" := ConID}}} ->
|
|
gd_v_devman:open_contract(ConID);
|
|
{error, "Tx not mined"} ->
|
|
gd_v_devman:trouble({tx_hash, TXHash});
|
|
{ok, Reason = #{"call_info" := #{"return_type" := "revert"}}} ->
|
|
gd_v_devman:trouble({error, Reason});
|
|
Error ->
|
|
gd_v_devman:trouble(Error)
|
|
end.
|
|
|
|
|
|
|
|
compile(Source) ->
|
|
Options = [{aci, json}],
|
|
so_compiler:from_string(Source, Options).
|
|
|
|
|
|
|
|
sign_tx_hash(Unsigned, SecKey, NetworkID) ->
|
|
{ok, TX_Data} = gmser_api_encoder:safe_decode(transaction, Unsigned),
|
|
{ok, Hash} = eblake2:blake2b(32, TX_Data),
|
|
NetworkHash = <<NetworkID/binary, Hash/binary>>,
|
|
Signature = ecu_eddsa:sign_detached(NetworkHash, SecKey),
|
|
SigTxType = signed_tx,
|
|
SigTxVsn = 1,
|
|
SigTemplate =
|
|
[{signatures, [binary]},
|
|
{transaction, binary}],
|
|
TX =
|
|
[{signatures, [Signature]},
|
|
{transaction, TX_Data}],
|
|
SignedTX = gmser_chain_objects:serialize(SigTxType, SigTxVsn, SigTemplate, TX),
|
|
gmser_api_encoder:encode(transaction, SignedTX).
|