forked from MergeFi/contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvoke.mjs
More file actions
81 lines (70 loc) · 2.5 KB
/
Copy pathinvoke.mjs
File metadata and controls
81 lines (70 loc) · 2.5 KB
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
import {
Keypair,
TransactionBuilder,
Networks,
BASE_FEE,
Contract,
Address,
nativeToScVal,
rpc,
} from "@stellar/stellar-sdk";
const NETWORK_PASSPHRASE =
process.env.STELLAR_NETWORK_PASSPHRASE ||
(process.env.STELLAR_NETWORK === "mainnet" ? Networks.PUBLIC : Networks.TESTNET);
const RPC_URL =
process.env.STELLAR_RPC_URL ||
(process.env.STELLAR_NETWORK === "mainnet"
? "https://soroban-rpc.mainnet.stellar.org"
: "https://soroban-testnet.stellar.org");
const server = new rpc.Server(RPC_URL);
let secret = process.env.MERGEFI_SIGNER_SECRET || process.env.STELLAR_SECRET_KEY;
let contractId, method, args;
if (secret) {
[, , contractId, method, ...args] = process.argv;
} else {
[, , secret, contractId, method, ...args] = process.argv;
}
if (!secret || !contractId || !method) {
console.error("Usage: node invoke.mjs [secret] <contractId> <method> [args as address:G... or u32:123]");
console.error("Or provide signer secret via MERGEFI_SIGNER_SECRET / STELLAR_SECRET_KEY environment variable.");
process.exit(1);
}
function parseArg(raw) {
const [type, value] = raw.split(":");
if (type === "address") return nativeToScVal(new Address(value), { type: "address" });
if (type === "u32") return nativeToScVal(parseInt(value, 10), { type: "u32" });
if (type === "i128") return nativeToScVal(BigInt(value), { type: "i128" });
throw new Error(`Unknown arg type: ${type}`);
}
const kp = Keypair.fromSecret(secret);
const contract = new Contract(contractId);
const scArgs = args.map(parseArg);
async function main() {
const account = await server.getAccount(kp.publicKey());
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call(method, ...scArgs))
.setTimeout(60)
.build();
const prepared = await server.prepareTransaction(tx);
prepared.sign(kp);
const sendResult = await server.sendTransaction(prepared);
if (sendResult.status === "ERROR") {
throw new Error(`Send failed: ${JSON.stringify(sendResult.errorResult)}`);
}
let getResult = await server.getTransaction(sendResult.hash);
while (getResult.status === "NOT_FOUND") {
await new Promise((r) => setTimeout(r, 1500));
getResult = await server.getTransaction(sendResult.hash);
}
if (getResult.status !== "SUCCESS") {
throw new Error(`Tx failed: ${JSON.stringify(getResult)}`);
}
console.log(`${method} succeeded. hash: ${sendResult.hash}`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});