-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNearContract.js
89 lines (73 loc) · 2.36 KB
/
NearContract.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
const { Contract, utils, keyStores, connect } = require("near-api-js");
const { NEAR_CONTRACT_CONTEXT } = require("./config.js");
const near_config = {
testnet: {
networkId: "testnet",
nodeUrl: "https://rpc.testnet.near.org",
},
mainnet: {
networkId: "mainnet",
nodeUrl: "https://rpc.mainnet.near.org",
},
};
module.exports = function (RED) {
function NearContract(config) {
(async () => {
RED.nodes.createNode(this, config);
const node = this;
const nearConnectionCfg = near_config[config.network];
function setError(error) {
node.error(error);
node.trace(error);
node.status({ fill: "red", shape: "dot", text: error.message });
}
try {
if (!node.credentials.userPrivateKey)
throw Error("Private key is not filled in");
const flowContext = this.context().flow;
let nearContracts = flowContext.get(NEAR_CONTRACT_CONTEXT);
if (!nearContracts) nearContracts = new Map();
const keyPair = utils.KeyPair.fromString(
node.credentials.userPrivateKey
);
const keyStore = new keyStores.InMemoryKeyStore();
keyStore.setKey(nearConnectionCfg.networkId, config.accountId, keyPair);
const connectionConfig = {
keyStore,
...nearConnectionCfg,
};
const near = await connect(connectionConfig);
const NearAccount = await near.account(config.accountId);
const contractMethods = {
changeMethods:
config.methods
?.filter((method) => method.type === "call")
?.map((method) => method.name) || [],
viewMethods:
config.methods
?.filter((method) => method.type === "view")
?.map((method) => method.name) || [],
};
const NearContract = new Contract(
NearAccount,
config.contract,
contractMethods
);
nearContracts.set(config.id, NearContract);
flowContext.set(NEAR_CONTRACT_CONTEXT, nearContracts);
node.status({
fill: "green",
shape: "dot",
text: config.accountId,
});
} catch (error) {
setError(error);
}
})();
}
RED.nodes.registerType("Near Contract", NearContract, {
credentials: {
userPrivateKey: { type: "password" },
},
});
};