Skip to content

Instantly share code, notes, and snippets.

@ohac
Created January 1, 2021 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohac/99b3d38ec15246891e6f0e83167e529e to your computer and use it in GitHub Desktop.
Save ohac/99b3d38ec15246891e6f0e83167e529e to your computer and use it in GitHub Desktop.
import React, { useEffect, useState } from "react"
function useMpurse() {
const [mpurse, setMpurse] = useState(null);
const [addr, setAddr] = useState(null);
useEffect(() => {
if (mpurse === null) {
const mp = window.mpurse;
if (mp) {
setMpurse(mp);
mp.getAddress().then((addr) => {
setAddr(addr);
});
} else {
//setAddr('MCj6QFbD7Gwy64qbzKonFbF5NTcsakwiXe'); // debug
}
}
}, [mpurse]);
return [mpurse, addr];
}
const apis = [
'https://monapa.electrum-mona.org/_api',
'https://mpchain.info/api/cb',
'https://wallet.monaparty.me/_api',
];
export default function Broadcast(props) {
const [mpurse, addr] = useMpurse();
const [msg, setMsg] = useState('@b.m "test"');
const [tx, setTx] = useState('');
function msgChanged(ev) {
const v = ev.target.value;
setMsg(v);
}
function createtx(api, command, params) {
const prms = { method: command, params };
//console.log(prms); // TODO
callApi(api, 'proxy_to_counterpartyd', prms)
.then(res => res.json())
.then(response => {
//console.log(response); // TODO
const result = response.result;
if (result) {
//console.log(result); // TODO
//mpurse.signRawTransaction(result) // TODO debug
mpurse.sendRawTransaction(result)
.then(tx2 => {
//console.log(tx2); // TODO
setTx(tx2);
});
}
});
}
function prepare(api, address, message) {
if (Buffer.byteLength(message) >= 55) {
console.log('error!'); // TODO
return;
}
const params = {
'source': address,
'fee_fraction': 0,
'text': message,
'timestamp': Math.floor(new Date().getTime() / 1000),
'value': -1,
};
createtx(api, 'create_broadcast', params);
}
function clicked() {
prepare(apis[0], addr, msg);
}
if (addr) {
return (
<>
メッセージ(54バイト以内)
<br />
<input type="text" value={msg} onChange={msgChanged}
style={{width: '100%'}} />
<br />
{tx}<br />
<button onClick={clicked}>Broadcastする</button>
</>
);
} else {
return (
<>Mpurse検出中...</>
);
}
}
function callApi(api, command, params) {
const body = { jsonrpc: '2.0', id: 0, method: command, params };
const params2 = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(body),
};
return fetch(api, params2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment