-
Notifications
You must be signed in to change notification settings - Fork 7
/
algorand.ts
245 lines (225 loc) · 7.92 KB
/
algorand.ts
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { default as AlgoSdk } from "algosdk";
import axios from "axios";
import * as PATH from "path";
import urlJoin from "url-join";
import { TFClient } from "../clients/tf-grid/client";
import { GridClientConfig } from "../config";
import { validateInput } from "../helpers";
import { expose } from "../helpers/expose";
import { appPath, BackendStorage, BackendStorageType, StorageUpdateAction } from "../storage";
import blockchainInterface, { blockchainType } from "./blockchainInterface";
import {
AlgorandAccountAssetsFromAddressModel,
AlgorandAccountCreateModel,
AlgorandAccountInitModel,
AlgorandCreateTransactionModel,
AlgorandSignatureModel,
AlgorandTransferModel,
BlockchainAssetModel,
BlockchainAssetsModel,
BlockchainCreateResultModel,
BlockchainDeleteModel,
BlockchainGetModel,
BlockchainGetResultModel,
BlockchainListResultModel,
BlockchainSignModel,
} from "./models";
class Algorand implements blockchainInterface {
baseUrl = "http://node.testnet.algoexplorerapi.io/";
backendStorage: BackendStorage;
fileName = "algorand.json";
tfClient: TFClient;
constructor(public config: GridClientConfig) {
this.backendStorage = new BackendStorage(
config.backendStorageType,
config.substrateURL,
config.mnemonic,
config.storeSecret,
config.keypairType,
config.backendStorage,
config.seed,
);
this.tfClient = new TFClient(
this.config.substrateURL,
this.config.mnemonic,
this.config.storeSecret,
this.config.keypairType,
);
}
private async saveIfKVStoreBackend(extrinsics) {
if (this.config.backendStorageType === BackendStorageType.tfkvstore && extrinsics && extrinsics.length > 0) {
extrinsics = extrinsics.filter(e => e !== undefined);
if (extrinsics.length > 0) {
await this.tfClient.connect();
await this.tfClient.applyAllExtrinsics(extrinsics);
}
}
}
async save(name: string, value: string) {
const [path, data] = await this._load();
if (data[name]) {
throw Error(`A wallet with the same name ${name} already exists`);
}
const updateOperations = await this.backendStorage.update(path, name, value);
await this.saveIfKVStoreBackend(updateOperations);
}
async _load() {
const path = PATH.join(appPath, this.fileName);
let data = await this.backendStorage.load(path);
if (!data) {
data = {};
}
return [path, data];
}
@expose
async list(): Promise<BlockchainListResultModel[]> {
const [, data] = await this._load();
const accounts = [];
for (const [name] of Object.entries(data)) {
const account = await AlgoSdk.mnemonicToSecretKey(data[name]);
accounts.push({
name: name,
public_key: account.addr,
blockchain_type: blockchainType.algorand,
});
}
return accounts;
}
@expose
@validateInput
async exist(options: BlockchainGetModel) {
return (await this.list()).map(account => account.name == options.name).includes(true);
}
@expose
@validateInput
async delete(options: BlockchainDeleteModel) {
const [path, data] = await this._load();
if (!data[options.name]) {
throw Error(`Couldn't find a wallet with name ${options.name}`);
}
const updateOperations = await this.backendStorage.update(path, options.name, "", StorageUpdateAction.delete);
await this.saveIfKVStoreBackend(updateOperations);
return "Deleted";
}
@expose
@validateInput
async create(options: AlgorandAccountCreateModel): Promise<BlockchainCreateResultModel> {
const account_exists = await this.exist({ name: options.name });
if (account_exists) throw Error(`Name ${options.name} already exists`);
const account = await AlgoSdk.generateAccount();
const account_mnemonic = AlgoSdk.secretKeyToMnemonic(account.sk);
console.log(account);
await this.save(options.name, account_mnemonic);
return {
name: options.name,
public_key: account.addr,
mnemonic: account_mnemonic,
blockchain_type: blockchainType.algorand,
};
}
@expose
@validateInput
async init(options: AlgorandAccountInitModel) {
const account = await AlgoSdk.mnemonicToSecretKey(options.secret);
await this.save(options.name, options.secret);
return account.addr;
}
@expose
@validateInput
async assets(options: BlockchainGetModel): Promise<BlockchainAssetsModel> {
const account_mnemonics = await this.get({ name: options.name });
const account = await AlgoSdk.mnemonicToSecretKey(account_mnemonics.mnemonic);
const assets = await this.assetsByAddress({ address: account.addr });
return {
name: options.name,
public_key: account.addr,
blockchain_type: blockchainType.algorand,
assets: assets ?? [],
};
}
@expose
@validateInput
async assetsByAddress(options: AlgorandAccountAssetsFromAddressModel): Promise<BlockchainAssetModel[]> {
const assets = await axios
.get(urlJoin(this.baseUrl, `v2/accounts/${options.address}/`))
.then(res => res.data.assets);
assets.forEach(asset => {
asset["asset"] = asset["asset-id"];
delete asset["asset-id"];
});
return assets;
}
@expose
@validateInput
async get(options: BlockchainGetModel): Promise<BlockchainGetResultModel> {
const [, data] = await this._load();
if (!data[options.name]) {
throw Error(`Couldn't find a wallet with name ${options.name}`);
}
const mnemonic = data[options.name];
const account = await AlgoSdk.mnemonicToSecretKey(mnemonic);
return {
name: options.name,
public_key: account.addr,
mnemonic: mnemonic,
blockchain_type: blockchainType.algorand,
};
}
async sign_txn(options: AlgorandSignatureModel) {
const accountMnemonicsFromName = await this.get({ name: options.name });
const account = await AlgoSdk.mnemonicToSecretKey(accountMnemonicsFromName.mnemonic);
const signed_txn = await AlgoSdk.signTransaction(options.txn, account.sk);
return signed_txn;
}
@expose
@validateInput
async sign(options: BlockchainSignModel) {
const accountMnemonicsFromName = await this.get({ name: options.name });
const account = await AlgoSdk.mnemonicToSecretKey(accountMnemonicsFromName.mnemonic);
const message = Uint8Array.from(Buffer.from(options.content, "hex"));
await AlgoSdk.signBytes(message, account.sk);
const messageSent = Buffer.from(message).toString("hex");
return messageSent;
}
@validateInput
async createTransaction(options: AlgorandCreateTransactionModel) {
const params_fetched = await axios.get(urlJoin(this.baseUrl, `v2/transactions/params`)).then(res => res.data);
console.log("transaction params fetched");
const request_params = {
flatFee: true,
fee: 1000,
firstRound: params_fetched["last-round"],
lastRound: params_fetched["last-round"] + 1000,
genesisID: params_fetched["genesis-id"],
genesisHash: params_fetched["genesis-hash"],
};
const note = AlgoSdk.encodeObj(options.description as unknown as Record<string | number | symbol, any>);
const accountMnemonics = await this.get({ name: options.name });
const account = AlgoSdk.mnemonicToSecretKey(accountMnemonics.mnemonic);
const txn = AlgoSdk.makePaymentTxnWithSuggestedParams(
account.addr,
options.address_dest,
options.amount,
undefined,
note,
request_params,
);
console.log("transaction binary built");
return txn;
}
@expose
@validateInput
async pay(options: AlgorandTransferModel) {
const txn = await this.createTransaction(options);
console.log("transaction binary built", txn);
const signedTxn = await this.sign_txn({ txn: txn, name: options.name });
console.log("transaction signed");
try {
const submitted_txn = await axios.post(urlJoin(this.baseUrl, `v2/transactions`), signedTxn?.blob);
return submitted_txn.data;
} catch (error) {
throw error.response.data.message;
}
}
}
export { Algorand as algorand };