-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
207 lines (182 loc) · 6.5 KB
/
api.js
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
import { WsProvider, ApiPromise } from "https://cdn.jsdelivr.net/npm/@polkadot/[email protected]/+esm";
let singletonApi;
let singletonProvider;
let PREFIX = 42;
let UNIT = "UNIT";
let DECIMALS = 8;
let isConnected = false;
let providerUrl = "";
export function getDecimals() {
return DECIMALS;
}
export function getUnit() {
return UNIT;
}
export function getPrefix() {
return PREFIX;
}
export function getIsConnected() {
return isConnected;
}
export function getProviderUrl() {
return providerUrl;
}
// Load up the api for the given provider uri
export async function loadApi(providerUri) {
// Singleton
if (!providerUri && singletonApi) return singletonApi;
// Just asking for the singleton, but don't have it
if (!providerUri) {
return null;
}
// Handle disconnects
if (providerUri) {
if (singletonApi) {
await singletonApi.disconnect();
} else if (singletonProvider) {
await singletonProvider.disconnect();
}
}
// Singleton Provider because it starts trying to connect here.
singletonProvider = new WsProvider(providerUri);
singletonApi = await ApiPromise.create({ provider: singletonProvider, throwOnConnect: true });
const chain = await singletonApi.rpc.system.properties();
PREFIX = Number(chain.ss58Format.toString());
UNIT = chain.tokenSymbol.toHuman();
DECIMALS = chain.tokenDecimals.toJSON()[0];
providerUrl = providerUri;
document.querySelectorAll(".unit").forEach((e) => (e.innerHTML = UNIT));
return singletonApi;
}
// Connect to the wallet and blockchain
const connect = (postConnect) => async (event) => {
event.preventDefault();
const connectError = document.getElementById("connectError");
const connectButton = document.getElementById("connectButton");
connectError.innerHTML = "";
connectError.style.display = "none";
connectButton.innerHTML = "Connecting...";
connectButton.disabled = true;
let provider = document.getElementById("provider").value;
if (provider === "custom") {
provider = document.getElementById("providerCustom").value;
}
try {
await loadApi(provider);
isConnected = true;
connectError.innerHTML = "";
connectError.style.display = "none";
await postConnect();
toggleConnectedVisibility(true, provider);
} catch (_e) {
connectError.style.display = "block";
connectError.innerHTML = "Failed to connect. Check the connection URL: " + provider;
}
connectButton.innerHTML = "Connect to Node";
connectButton.disabled = false;
};
// Reset
async function disconnect(event) {
event.preventDefault();
const api = await loadApi();
isConnected = false;
await api.disconnect();
toggleConnectedVisibility(false);
}
function customProviderToggle(value = null) {
value = value ?? document.getElementById("provider").value;
const customContainer = document.getElementById("providerCustomContainer");
customContainer.style.display = value === "custom" ? "block" : "none";
}
function toggleConnectedVisibility(isConnected, provider = "...") {
document.getElementById("currentProvider").innerHTML = provider;
document.querySelectorAll(".showConnected").forEach((e) => (e.style.display = isConnected ? "block" : "none"));
document.querySelectorAll(".hideConnected").forEach((e) => (e.style.display = isConnected ? "none" : "block"));
}
export function initConnection(postConnect) {
document.getElementById("connectButton").addEventListener("click", connect(postConnect));
document.getElementById("provider").addEventListener("input", (e) => {
toggleConnectedVisibility(false);
customProviderToggle(e.target.value);
});
document.getElementById("disconnectButton").addEventListener("click", disconnect);
customProviderToggle();
}
let relayBlockNumberCache = [0, null];
export async function getCurrentRelayChainBlockNumber() {
const [cacheTime, cachedNumber] = relayBlockNumberCache;
if (cacheTime + 60_000 > Date.now()) {
return cachedNumber;
}
const relayEndpoint = {
42: "wss://paseo-rpc.dwellir.com",
90: "wss://rpc.polkadot.io",
};
const api = await ApiPromise.create({ provider: new WsProvider(relayEndpoint[PREFIX]) });
await api.isReady;
const blockData = await api.rpc.chain.getBlock();
const result = await blockData.block.header.number.toNumber();
relayBlockNumberCache = [Date.now(), result];
return result;
}
// Balance to decimal UNIT
export function toDecimalUnit(balance) {
const DECIMALS = getDecimals();
// Some basic formatting of the bigint
balance = balance.toString();
if (balance.length >= DECIMALS) {
return `${BigInt(balance.slice(0, -DECIMALS)).toLocaleString()}.${balance.slice(-DECIMALS)}`;
}
return balance > 0
? (Number(balance) / 10 ** DECIMALS).toLocaleString(undefined, { minimumFractionDigits: DECIMALS })
: "0";
}
// This will only get Time Release Transfers
export async function getPendingMultisigs(address) {
const api = await loadApi();
const multisigEntries = await Promise.all(
(await api.query.multisig.multisigs.entries(address)).map(async (entry) => {
const [_multisig, hash] = entry[0].toHuman();
const entryData = entry[1].toJSON();
const blockHash = await api.rpc.chain.getBlockHash(entryData.when.height);
const signedBlock = await api.rpc.chain.getBlock(blockHash);
const innerCallTx = signedBlock.block.extrinsics[entryData.when.index]?.method?.args[3] || null;
const innerCall = innerCallTx.toHuman();
if (innerCall.method !== "transfer" || innerCall.section !== "timeRelease") {
throw new Error("Unable to process original data");
}
const { dest, schedule } = innerCall.args;
return {
hash,
schedule: {
start: schedule.start.toNumber(),
perPeriod: schedule.perPeriod.toBigInt(),
period: schedule.period.toNumber(),
periodCount: schedule.periodCount.toNumber(),
},
dest: {
id: dest.Id,
},
callData: innerCallTx.toHex(),
approvals: entryData.approvals,
};
}),
);
return multisigEntries;
}
export async function getBalance(address) {
const api = await loadApi();
const resp = await api.query.system.account(address);
const total = BigInt(resp.data.free.toJSON());
return {
decimal: toDecimalUnit(total),
plancks: BigInt(total).toLocaleString(),
free: resp.data.free.toHuman(),
frozen: resp.data.frozen.toHuman(),
};
}
export function hasSuccess(status) {
const events = status.events.map((x) => x.toHuman());
const success = events.find((x) => x.event.method === "ExtrinsicSuccess");
return !!success;
}