-
Notifications
You must be signed in to change notification settings - Fork 5k
/
Copy pathwallet.provider.ts
249 lines (229 loc) · 7.36 KB
/
wallet.provider.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
246
247
248
249
import {
elizaLogger,
IAgentRuntime,
Memory,
Provider,
State,
} from "@elizaos/core";
import NodeCache from "node-cache";
import * as fcl from "@onflow/fcl";
import type { CompositeSignature, Account } from "@onflow/typedefs";
import type { FlowConnector } from "./utils/flow.connector";
import { IFlowScriptExecutor, IFlowSigner } from "../types";
import { getFlowConnectorInstance } from "./connector.provider";
import PureSigner from "./utils/pure.signer";
import Exception from "../types/exception";
import * as queries from "../queries";
/**
* Flow wallet Provider
*/
export class FlowWalletProvider implements IFlowSigner, IFlowScriptExecutor {
runtime: IAgentRuntime;
private readonly privateKeyHex?: string;
public readonly address: string;
// Runtime data
private account: Account | null = null;
public maxKeyIndex = 0;
constructor(
runtime: IAgentRuntime,
private readonly connector: FlowConnector,
private readonly cache: NodeCache = new NodeCache({ stdTTL: 300 }) // Cache TTL set to 5 minutes
) {
this.address = getSignerAddress(runtime);
this.runtime = runtime;
const privateKey = runtime.getSetting("FLOW_PRIVATE_KEY");
if (!privateKey) {
elizaLogger.warn(
`The default Flow wallet ${this.address} has no private key`
);
} else {
this.privateKeyHex = privateKey.startsWith("0x")
? privateKey.slice(2)
: privateKey;
}
}
/**
* Get the network type
*/
get network() {
return this.connector.network;
}
/**
* Send a transaction
* @param code Cadence code
* @param args Cadence arguments
*/
async sendTransaction(
code: string,
args: fcl.ArgumentFunction,
authz?: fcl.FclAuthorization
) {
return await this.connector.sendTransaction(
code,
args,
authz ?? this.buildAuthorization()
);
}
/**
* Execute a script
* @param code Cadence code
* @param args Cadence arguments
*/
async executeScript<T>(
code: string,
args: fcl.ArgumentFunction,
defaultValue: T
): Promise<T> {
return await this.connector.executeScript(code, args, defaultValue);
}
/**
* Build authorization
*/
buildAuthorization(accountIndex = 0, privateKey = this.privateKeyHex) {
if (this.account) {
if (accountIndex > this.maxKeyIndex) {
throw new Exception(50200, "Invalid account index");
}
}
const address = this.address;
if (!privateKey) {
throw new Exception(50200, "No private key provided");
}
return (account: any) => {
return {
...account,
tempId: `${address}-${accountIndex}`,
addr: fcl.sansPrefix(address),
keyId: Number(accountIndex),
signingFunction: (
signable: any
): Promise<CompositeSignature> => {
return Promise.resolve({
f_type: "CompositeSignature",
f_vsn: "1.0.0",
addr: fcl.withPrefix(address),
keyId: Number(accountIndex),
signature: this.signMessage(
signable.message,
privateKey
),
});
},
};
};
}
/**
* Sign a message
* @param message Message to sign
*/
signMessage(message: string, privateKey = this.privateKeyHex) {
return PureSigner.signWithKey(privateKey, message);
}
// ----- methods -----
/**
* Sync account info
*/
async syncAccountInfo() {
this.account = await this.connector.getAccount(this.address);
this.maxKeyIndex = this.account.keys.length - 1;
this.cache.set("balance", this.account.balance / 1e8);
elizaLogger.debug("Flow account info synced", {
address: this.address,
balance: this.account.balance,
maxKeyIndex: this.maxKeyIndex,
keys: this.account.keys,
});
}
/**
* Get the wallet balance
* @returns Wallet balance
*/
async getWalletBalance(forceRefresh = false): Promise<number> {
const cachedBalance = await this.cache.get<number>("balance");
if (!forceRefresh && cachedBalance) {
return cachedBalance;
}
await this.syncAccountInfo();
return this.account ? this.account.balance / 1e8 : 0;
}
/**
* Query the balance of this wallet
*/
async queryAccountBalanceInfo() {
return await queries.queryAccountBalanceInfo(this, this.address);
}
}
// ----- Helpers -----
/**
* Check if an address is a Flow address
* @param address Address to check
*/
export function isFlowAddress(address: string) {
const regExp = /^0x[a-fA-F0-9]{16}$/gi;
return regExp.test(address);
}
/**
* Check if an address is an EVM address
* @param address Address to check
*/
export function isEVMAddress(address: string) {
const regExp = /^0x[a-fA-F0-9]{40}$/gi;
return regExp.test(address);
}
/**
* Check if a string is a Cadence identifier
* @param str String to check
*/
export function isCadenceIdentifier(str: string) {
const cadenceIdentifier = /^A\.[0-9a-fA-F]{16}\.[0-9a-zA-Z_]+/;
return cadenceIdentifier.test(str);
}
/**
* Get the signer address
*/
function getSignerAddress(runtime: IAgentRuntime): string {
const signerAddr = runtime.getSetting("FLOW_ADDRESS");
if (!signerAddr) {
elizaLogger.error("No signer address");
throw new Exception(50200, "No signer info");
}
return signerAddr;
}
const flowWalletProvider: Provider = {
get: async (
runtime: IAgentRuntime,
_message: Memory,
_state?: State
): Promise<string | null> => {
// Check if the user has an Flow wallet
if (
!runtime.getSetting("FLOW_ADDRESS") ||
!runtime.getSetting("FLOW_PRIVATE_KEY")
) {
elizaLogger.error(
"FLOW_ADDRESS or FLOW_PRIVATE_KEY not configured, skipping wallet injection"
);
return null;
}
try {
const connector = await getFlowConnectorInstance(runtime);
const walletProvider = new FlowWalletProvider(runtime, connector);
const info = await walletProvider.queryAccountBalanceInfo();
if (!info || info?.address !== walletProvider.address) {
elizaLogger.error("Invalid account info");
return null;
}
let output = `Here is user<${runtime.character.name}>'s wallet status:\n`;
output += `Flow wallet address: ${walletProvider.address}\n`;
output += `FLOW balance: ${info.balance} FLOW\n`;
output += `Flow wallet's COA(EVM) address: ${info.coaAddress || "unknown"}\n`;
output += `FLOW balance in COA(EVM) address: ${info.coaBalance ?? 0} FLOW`;
return output;
} catch (error) {
elizaLogger.error("Error in Flow wallet provider:", error.message);
return null;
}
},
};
// Module exports
export { flowWalletProvider };