diff --git a/go-util/builtin-cid-generator/go.mod b/go-util/builtin-cid-generator/go.mod new file mode 100644 index 0000000..3abee97 --- /dev/null +++ b/go-util/builtin-cid-generator/go.mod @@ -0,0 +1,23 @@ +module builtin-cid-generator.com/m/v2 + +go 1.18 + +require ( + github.com/filecoin-project/go-bitfield v0.2.4 + github.com/ipfs/go-cid v0.0.5 + github.com/multiformats/go-multihash v0.0.13 +) + +require ( + github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1 // indirect + github.com/minio/sha256-simd v0.1.1-0.20190913151208-6de447530771 // indirect + github.com/mr-tron/base58 v1.1.3 // indirect + github.com/multiformats/go-base32 v0.0.3 // indirect + github.com/multiformats/go-multibase v0.0.1 // indirect + github.com/multiformats/go-varint v0.0.5 // indirect + github.com/spaolacci/murmur3 v1.1.0 // indirect + github.com/whyrusleeping/cbor-gen v0.0.0-20200414195334-429a0b5e922e // indirect + golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8 // indirect + golang.org/x/sys v0.0.0-20190412213103-97732733099d // indirect + golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 // indirect +) diff --git a/go-util/builtin-cid-generator/go.sum b/go-util/builtin-cid-generator/go.sum new file mode 100644 index 0000000..bd37ade --- /dev/null +++ b/go-util/builtin-cid-generator/go.sum @@ -0,0 +1,47 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/filecoin-project/go-bitfield v0.2.4 h1:uZ7MeE+XfM5lqrHJZ93OnhQKc/rveW8p9au0C68JPgk= +github.com/filecoin-project/go-bitfield v0.2.4/go.mod h1:CNl9WG8hgR5mttCnUErjcQjGvuiZjRqK9rHVBsQF4oM= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/gxed/hashland/keccakpg v0.0.1/go.mod h1:kRzw3HkwxFU1mpmPP8v1WyQzwdGfmKFJ6tItnhQ67kU= +github.com/gxed/hashland/murmur3 v0.0.1/go.mod h1:KjXop02n4/ckmZSnY2+HKcLud/tcmvhST0bie/0lS48= +github.com/ipfs/go-cid v0.0.3/go.mod h1:GHWU/WuQdMPmIosc4Yn1bcCT7dSeX4lBafM7iqUPQvM= +github.com/ipfs/go-cid v0.0.5 h1:o0Ix8e/ql7Zb5UVUJEUfjsWCIY8t48++9lR8qi6oiJU= +github.com/ipfs/go-cid v0.0.5/go.mod h1:plgt+Y5MnOey4vO4UlUazGqdbEXuFYitED67FexhXog= +github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1 h1:lYpkrQH5ajf0OXOcUbGjvZxxijuBwbbmlSxLiuofa+g= +github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1/go.mod h1:pD8RvIylQ358TN4wwqatJ8rNavkEINozVn9DtGI3dfQ= +github.com/minio/sha256-simd v0.0.0-20190131020904-2d45a736cd16/go.mod h1:2FMWW+8GMoPweT6+pI63m9YE3Lmw4J71hV56Chs1E/U= +github.com/minio/sha256-simd v0.1.1-0.20190913151208-6de447530771 h1:MHkK1uRtFbVqvAgvWxafZe54+5uBxLluGylDiKgdhwo= +github.com/minio/sha256-simd v0.1.1-0.20190913151208-6de447530771/go.mod h1:B5e1o+1/KgNmWrSQK08Y6Z1Vb5pwIktudl0J58iy0KM= +github.com/mr-tron/base58 v1.1.0/go.mod h1:xcD2VGqlgYjBdcBLw+TuYLr8afG+Hj8g2eTVqeSzSU8= +github.com/mr-tron/base58 v1.1.3 h1:v+sk57XuaCKGXpWtVBX8YJzO7hMGx4Aajh4TQbdEFdc= +github.com/mr-tron/base58 v1.1.3/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc= +github.com/multiformats/go-base32 v0.0.3 h1:tw5+NhuwaOjJCC5Pp82QuXbrmLzWg7uxlMFp8Nq/kkI= +github.com/multiformats/go-base32 v0.0.3/go.mod h1:pLiuGC8y0QR3Ue4Zug5UzK9LjgbkL8NSQj0zQ5Nz/AA= +github.com/multiformats/go-multibase v0.0.1 h1:PN9/v21eLywrFWdFNsFKaU04kLJzuYzmrJR+ubhT9qA= +github.com/multiformats/go-multibase v0.0.1/go.mod h1:bja2MqRZ3ggyXtZSEDKpl0uO/gviWFaSteVbWT51qgs= +github.com/multiformats/go-multihash v0.0.1/go.mod h1:w/5tugSrLEbWqlcgJabL3oHFKTwfvkofsjW2Qa1ct4U= +github.com/multiformats/go-multihash v0.0.13 h1:06x+mk/zj1FoMsgNejLpy6QTvJqlSt/BhLEy87zidlc= +github.com/multiformats/go-multihash v0.0.13/go.mod h1:VdAWLKTwram9oKAatUcLxBNUjdtcVwxObEQBtRfuyjc= +github.com/multiformats/go-varint v0.0.5 h1:XVZwSo04Cs3j/jS0uAEPpT3JY6DzMcVLLoWOSnCxOjg= +github.com/multiformats/go-varint v0.0.5/go.mod h1:3Ls8CIEsrijN6+B7PbrXRPxHRPuXSrVKRY101jdMZYE= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= +github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/whyrusleeping/cbor-gen v0.0.0-20200414195334-429a0b5e922e h1:JY8o/ebUUrCYetWmjRCNghxC59cOEaili83rxPRQCLw= +github.com/whyrusleeping/cbor-gen v0.0.0-20200414195334-429a0b5e922e/go.mod h1:Xj/M2wWU+QdTdRbu/L/1dIZY8/Wb2K9pAhtroQuxJJI= +golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8 h1:1wopBVtVdWnn03fZelqdXTqk7U7zPQCb+T4rbU9ZEoU= +golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190219092855-153ac476189d/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/go-util/builtin-cid-generator/main.go b/go-util/builtin-cid-generator/main.go new file mode 100644 index 0000000..f19977d --- /dev/null +++ b/go-util/builtin-cid-generator/main.go @@ -0,0 +1,61 @@ +package main + +import ( + "fmt" + + "github.com/ipfs/go-cid" + mh "github.com/multiformats/go-multihash" +) + +var builtinActors map[cid.Cid]*actorInfo + +var ( + SystemActorCodeID cid.Cid + InitActorCodeID cid.Cid + CronActorCodeID cid.Cid + AccountActorCodeID cid.Cid + StoragePowerActorCodeID cid.Cid + StorageMinerActorCodeID cid.Cid + StorageMarketActorCodeID cid.Cid + PaymentChannelActorCodeID cid.Cid + MultisigActorCodeID cid.Cid + RewardActorCodeID cid.Cid + VerifiedRegistryActorCodeID cid.Cid + CallerTypesSignable []cid.Cid +) + +type actorInfo struct { + name string + signer bool +} + +func main() { + builder := cid.V1Builder{Codec: cid.Raw, MhType: mh.IDENTITY} + builtinActors = make(map[cid.Cid]*actorInfo) + + for id, info := range map[*cid.Cid]*actorInfo{ //nolint:nomaprange + &SystemActorCodeID: {name: "fil/6/system"}, + &InitActorCodeID: {name: "fil/6/init"}, + &CronActorCodeID: {name: "fil/6/cron"}, + &StoragePowerActorCodeID: {name: "fil/6/storagepower"}, + &StorageMinerActorCodeID: {name: "fil/6/storageminer"}, + &StorageMarketActorCodeID: {name: "fil/6/storagemarket"}, + &PaymentChannelActorCodeID: {name: "fil/6/paymentchannel"}, + &RewardActorCodeID: {name: "fil/6/reward"}, + &VerifiedRegistryActorCodeID: {name: "fil/6/verifiedregistry"}, + &AccountActorCodeID: {name: "fil/6/account", signer: true}, + &MultisigActorCodeID: {name: "fil/6/multisig", signer: true}, + } { + c, err := builder.Sum([]byte(info.name)) + if err != nil { + panic(err) + } + *id = c + builtinActors[c] = info + } + + for k, v := range builtinActors { + fmt.Println(k, "value is", v.name) + } + +} diff --git a/src/providers/Types.ts b/src/providers/Types.ts index 1415502..541764f 100644 --- a/src/providers/Types.ts +++ b/src/providers/Types.ts @@ -1191,6 +1191,15 @@ export class MsigVesting { export type NetworkVersion = number; +export class MessagePrototype { + Message!: Message; + ValidNonce!: boolean; +} + +export class MessageCheckStatus { + Cid!: Cid; + CheckStatus!: any; +} export class MessageMatch { To?: Address; @@ -1203,6 +1212,16 @@ export class DataCIDSize { PieceCID!: Cid; } +export type IpldObject = { + Cid: Cid; + Obj: any; +} + +export type PruneOpts = { + MovingGC: boolean + RetainState: number +} + /** * Interface to be implemented by all providers. * diff --git a/src/providers/method-groups/chain.ts b/src/providers/method-groups/chain.ts index c5b3099..60269e2 100644 --- a/src/providers/method-groups/chain.ts +++ b/src/providers/method-groups/chain.ts @@ -4,9 +4,11 @@ import { BlockMessages, ChainEpoch, Cid, HeadChange, + IpldObject, Message, MessageReceipt, ObjStat, + PruneOpts, TipSet, TipSetKey, WrappedMessage, } from '../Types'; @@ -24,41 +26,6 @@ export class JsonRpcChainMethodGroup { this.conn = conn; } - /** - * reads ipld nodes referenced by the specified CID from chain blockstore and returns raw bytes. - * @param cid - */ - public async readObj(cid: Cid): Promise { - const ret = await this.conn.request({ method: 'Filecoin.ChainReadObj', params: [cid] }); - return ret as string; - } - - /** - * deletes node referenced by the given CID - * @param cid - */ - public async deleteObj(cid: Cid): Promise { - const error = await this.conn.request({ method: 'Filecoin.ChainDeleteObj', params: [cid] }); - return error as string; - } - - /** - * returns messages stored in the specified block. - * @param blockCid - */ - public async getBlockMessages(blockCid: Cid): Promise { - const ret = await this.conn.request({ method: 'Filecoin.ChainGetBlockMessages', params: [blockCid] }); - return ret as BlockMessages; - } - - /** - * returns the current head of the chain - */ - public async getHead(): Promise { - const ret = await this.conn.request({ method: 'Filecoin.ChainHead' }); - return ret as TipSet; - } - /** * call back on chain head updates. * @param cb @@ -81,12 +48,12 @@ export class JsonRpcChainMethodGroup { } } - public stopChainNotify(id?: any) { - if (this.conn instanceof HttpJsonRpcConnector && id) { - clearInterval(id); - } else if (this.conn instanceof WsJsonRpcConnector) { - this.conn.closeSubscription(id); - } + /** + * returns the current head of the chain + */ + public async getHead(): Promise { + const ret = await this.conn.request({ method: 'Filecoin.ChainHead' }); + return ret as TipSet; } /** @@ -99,16 +66,37 @@ export class JsonRpcChainMethodGroup { } /** - * reads a message referenced by the specified CID from the chain blockstore - * @param messageCid + * Returns the tipset specified by the given TipSetKey. + * @param tipSetKey */ - public async getMessage(messageCid: Cid): Promise { - const ret = await this.conn.request({ method: 'Filecoin.ChainGetMessage', params: [messageCid] }); - return ret as Message; + public async getTipSet(tipSetKey: TipSetKey): Promise { + const ret: TipSet = await this.conn.request({ method: 'Filecoin.ChainGetTipSet', params: [tipSetKey] }); + return ret; } /** - * returns receipts for messages in parent tipset of the specified block + * returns messages stored in the specified block. + * @param blockCid + * + * Note: If there are multiple blocks in a tipset, it's likely that some + * messages will be duplicated. It's also possible for blocks in a tipset to have + * different messages from the same sender at the same nonce. When that happens, + * only the first message (in a block with lowest ticket) will be considered + * for execution + * + * NOTE: THIS METHOD SHOULD ONLY BE USED FOR GETTING MESSAGES IN A SPECIFIC BLOCK + * + * DO NOT USE THIS METHOD TO GET MESSAGES INCLUDED IN A TIPSET + * Use ChainGetParentMessages, which will perform correct message deduplication + */ + public async getBlockMessages(blockCid: Cid): Promise { + const ret = await this.conn.request({ method: 'Filecoin.ChainGetBlockMessages', params: [blockCid] }); + return ret as BlockMessages; + } + + /** + * returns receipts for messages in parent tipset of the specified block. The receipts in the list returned are one-to-one with the + * messages returned by a call to ChainGetParentMessages with the same blockCid. * @param blockCid */ public async getParentReceipts(blockCid: Cid): Promise { @@ -125,6 +113,53 @@ export class JsonRpcChainMethodGroup { return ret as WrappedMessage[]; } + + /** + * returns message stores in current tipset + * @param tipSetKey + */ + public async getMessagesInTipset(tipSetKey: TipSetKey): Promise { + const ret = await this.conn.request({ method: 'Filecoin.ChainGetMessagesInTipset', params: [tipSetKey] }); + return ret as WrappedMessage[]; + } + + /** + * looks back for a tipset at the specified epoch. If there are no blocks at the specified epoch, a tipset at an earlier epoch will be returned. + * @param epochNumber + */ + public async getTipSetByHeight(epochNumber: number): Promise { + const ret: TipSet = await this.conn.request({ method: 'Filecoin.ChainGetTipSetByHeight', params: [epochNumber, []] }); + return ret; + } + + /** + * looks back for a tipset at the specified epoch. If there are no blocks at the specified epoch, the first non-nil tipset at a later epoch + * will be returned. + * @param epochNumber + */ + public async getTipSetAfterHeight(epochNumber: number, tipSetKey?: TipSetKey): Promise { + const ret: TipSet = await this.conn.request({ method: 'Filecoin.ChainGetTipSetAfterHeight', params: [epochNumber, tipSetKey] }); + return ret; + } + + /** + * reads ipld nodes referenced by the specified CID from chain blockstore and returns raw bytes. + * @param cid + */ + public async readObj(cid: Cid): Promise { + const ret = await this.conn.request({ method: 'Filecoin.ChainReadObj', params: [cid] }); + return ret as string; + } + + /** + * deletes node referenced by the given CID + * @param cid + */ + public async deleteObj(cid: Cid): Promise { + const error = await this.conn.request({ method: 'Filecoin.ChainDeleteObj', params: [cid] }); + return error as string; + } + /** * checks if a given CID exists in the chain blockstore * @param cid @@ -173,16 +208,25 @@ export class JsonRpcChainMethodGroup { } /** - * looks back for a tipset at the specified epoch. - * @param epochNumber + * @param p */ - public async getTipSetByHeight(epochNumber: number): Promise { - const ret: TipSet = await this.conn.request({ method: 'Filecoin.ChainGetTipSetByHeight', params: [epochNumber, []] }); - return ret; + public async getNode(p: string): Promise { + const node: IpldObject = await this.conn.request({ method: 'Filecoin.ChainGetNode', params: [p] }); + return node; } /** - * Returns a set of revert/apply operations needed to get from + * reads a message referenced by the specified CID from the chain blockstore + * @param messageCid + */ + public async getMessage(messageCid: Cid): Promise { + const ret = await this.conn.request({ method: 'Filecoin.ChainGetMessage', params: [messageCid] }); + return ret as Message; + } + + /** + * Returns a set of revert/apply operations needed to get from one tipset to another, for example: + * * @param from * @param to */ @@ -203,4 +247,54 @@ export class JsonRpcChainMethodGroup { const path: HeadChange[] = await this.conn.request({ method: 'Filecoin.ChainExport', params: [nroots, oldmsgskip, tipSetKey] }); return path; } + + /** + * Prunes the stored chain state and garbage collects; only supported if you are using the splitstore + * + * @param opts + */ + public async prune(opts: PruneOpts) { + return this.conn.request({ method: 'Filecoin.ChainPrune', params: [opts] }); + } + + /** + * Performs an (asynchronous) health check on the chain/state blockstore if supported by the underlying implementation. + */ + public async checkBlockstore() { + return this.conn.request({ method: 'Filecoin.ChainCheckBlockstore', params: [] }); + } + + /** + * Returns some basic information about the blockstore + */ + public async blockstoreInfo(): Promise { + return this.conn.request({ method: 'Filecoin.ChainBlockstoreInfo', params: [] }); + } + + /** + * Estimates gas fee cap + * @param message + * @param n + * @param tipSetKey + */ + public async gasEstimateFeeCap(message: Message, n: number, tipSetKey?: TipSetKey): Promise { + return this.conn.request({ method: 'Filecoin.GasEstimateFeeCap', params: [message, n, tipSetKey] }); + } + + /** + * Estimates gas used by the message and returns it. It fails if message fails to execute. + * @param message + * @param tipSetKey + */ + public async gasEstimateGasLimit(message: Message, tipSetKey?: TipSetKey): Promise { + return this.conn.request({ method: 'Filecoin.GasEstimateGasLimit', params: [message, tipSetKey] }); + } + + public stopChainNotify(id?: any) { + if (this.conn instanceof HttpJsonRpcConnector && id) { + clearInterval(id); + } else if (this.conn instanceof WsJsonRpcConnector) { + this.conn.closeSubscription(id); + } + } } diff --git a/src/providers/method-groups/mpool.ts b/src/providers/method-groups/mpool.ts index ceb7ca6..3b7ff97 100644 --- a/src/providers/method-groups/mpool.ts +++ b/src/providers/method-groups/mpool.ts @@ -1,5 +1,5 @@ import { Connector } from '../../connectors/Connector'; -import { Cid, Message, MpoolConfig, MpoolUpdate, SignedMessage, TipSetKey } from '../Types'; +import { Address, Cid, Message, MessageCheckStatus, MessagePrototype, MpoolConfig, MpoolUpdate, SignedMessage, TipSetKey } from '../Types'; import { WsJsonRpcConnector } from '../../index'; /** @@ -139,4 +139,32 @@ export class JsonRpcMPoolMethodGroup { const ret = await this.conn.request({ method: 'Filecoin.MpoolBatchPushMessage', params: [messages] }); return ret; } + + /** + * Performs logical checks on a batch of messages + * @param msgPrototype + */ + public async checkMessages(msgPrototype: MessagePrototype[]): Promise { + const ret = await this.conn.request({ method: 'Filecoin.MpoolCheckMessages', params: [msgPrototype] }); + return ret; + } + + + /** + * Performs logical checks for all pending messages from a given address + * @param address + */ + public async checkPendingMessages(address: Address[]): Promise { + const ret = await this.conn.request({ method: 'Filecoin.MpoolCheckPendingMessages', params: [address] }); + return ret; + } + + /** + * Performs logical checks on pending messages with replacement + * @param msg + */ + public async checkReplaceMessages(msg: Message[]): Promise { + const ret = await this.conn.request({ method: 'Filecoin.MpoolCheckReplaceMessages', params: [msg] }); + return ret; + } } diff --git a/src/providers/wallet/BaseWalletProvider.ts b/src/providers/wallet/BaseWalletProvider.ts index 2c4df59..28d4cbe 100644 --- a/src/providers/wallet/BaseWalletProvider.ts +++ b/src/providers/wallet/BaseWalletProvider.ts @@ -1,9 +1,49 @@ -import { Message, SignedMessage, Cid, MessagePartial, HeadChange, TipSet, BlockHeader, BlockMessages, MessageReceipt, WrappedMessage, ObjStat, TipSetKey, SyncState, MpoolUpdate, PeerID, Address, StorageAsk, Actor, ActorState, NetworkName, SectorOnChainInfo, DeadlineInfo, MinerPower, MinerInfo, Deadline, Partition, BitField, ChainEpoch, Fault, SectorPreCommitInfo, SectorNumber, SectorPreCommitOnChainInfo, SectorExpiration, SectorLocation, MsgLookup, MarketBalance, MarketDeal, DealID, MinerSectors, MsigVesting } from '../Types'; +import { + Message, + SignedMessage, + Cid, + MessagePartial, + HeadChange, + TipSet, + BlockHeader, + BlockMessages, + MessageReceipt, + WrappedMessage, + ObjStat, + TipSetKey, + SyncState, + MpoolUpdate, + PeerID, + Address, + StorageAsk, + Actor, + ActorState, + NetworkName, + SectorOnChainInfo, + DeadlineInfo, + MinerPower, + MinerInfo, + Deadline, + Partition, + BitField, + ChainEpoch, + Fault, + SectorPreCommitInfo, + SectorNumber, + SectorPreCommitOnChainInfo, + SectorExpiration, + SectorLocation, + MsgLookup, + MarketBalance, + MarketDeal, + DealID, + MinerSectors, + MsigVesting, +} from '../Types'; import BigNumber from 'bignumber.js'; import { LotusClient } from '../..'; export class BaseWalletProvider { - public client: LotusClient; constructor(client: LotusClient) { @@ -37,37 +77,48 @@ export class BaseWalletProvider { * @param msg */ public async sendSignedMessage(msg: SignedMessage): Promise { - const ret = await this.client.mpool.push(msg) + const ret = await this.client.mpool.push(msg); return ret as Cid; } /** - * estimate gas fee cap - * @param message - * @param nblocksincl - */ - public async estimateMessageGasFeeCap(message: Message, nblocksincl: number): Promise { + * estimate gas fee cap + * @param message + * @param nblocksincl + */ + public async estimateMessageGasFeeCap( + message: Message, + nblocksincl: number, + ): Promise { const ret = await this.client.gasEstimate.feeCap(message, nblocksincl); return ret as string; } /** - * estimate gas limit, it fails if message fails to execute. - * @param message - */ + * estimate gas limit, it fails if message fails to execute. + * @param message + */ public async estimateMessageGasLimit(message: Message): Promise { const ret = await this.client.gasEstimate.gasLimit(message); return ret as number; } /** - * estimate gas to succesufully send message, and have it likely be included in the next nblocksincl blocks - * @param nblocksincl - * @param sender - * @param gasLimit - */ - public async estimateMessageGasPremium(nblocksincl: number, sender: string, gasLimit: number): Promise { - const ret = await this.client.gasEstimate.gasPremium(nblocksincl, sender, gasLimit); + * estimate gas to succesufully send message, and have it likely be included in the next nblocksincl blocks + * @param nblocksincl + * @param sender + * @param gasLimit + */ + public async estimateMessageGasPremium( + nblocksincl: number, + sender: string, + gasLimit: number, + ): Promise { + const ret = await this.client.gasEstimate.gasPremium( + nblocksincl, + sender, + gasLimit, + ); return ret as string; } @@ -96,7 +147,7 @@ export class BaseWalletProvider { Params: message.Params ? message.Params : '', Version: message.Version ? message.Version : 0, Nonce: message.Nonce ? message.Nonce : await this.getNonce(message.From), - } + }; if (msg.GasLimit === 0) msg = await this.estimateMessageGas(msg); @@ -282,7 +333,10 @@ export class BaseWalletProvider { * @param miner */ public async queryAsk(peerId: PeerID, miner: Address): Promise { - const queryAsk: StorageAsk = await this.client.client.queryAsk(peerId, miner); + const queryAsk: StorageAsk = await this.client.client.queryAsk( + peerId, + miner, + ); return queryAsk; } @@ -293,7 +347,10 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async getActor(address: string, tipSetKey?: TipSetKey): Promise { + public async getActor( + address: string, + tipSetKey?: TipSetKey, + ): Promise { const data = await this.client.state.getActor(address, tipSetKey); return data as Actor; } @@ -303,7 +360,10 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async readState(address: string, tipSetKey?: TipSetKey): Promise { + public async readState( + address: string, + tipSetKey?: TipSetKey, + ): Promise { const data = await this.client.state.readState(address, tipSetKey); return data as ActorState; } @@ -314,8 +374,16 @@ export class BaseWalletProvider { * @param tipSetKey * @param toHeight */ - public async listMessages(filter: { To?: string, From?: string }, tipSetKey?: TipSetKey, toHeight?: number): Promise { - const messages: Cid[] = await this.client.state.listMessages(filter, tipSetKey, toHeight); + public async listMessages( + filter: { To?: string; From?: string }, + tipSetKey?: TipSetKey, + toHeight?: number, + ): Promise { + const messages: Cid[] = await this.client.state.listMessages( + filter, + tipSetKey, + toHeight, + ); return messages ? messages : []; } @@ -332,8 +400,14 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async minerSectors(address: string, tipSetKey?: TipSetKey): Promise { - const sectorsInfo: SectorOnChainInfo[] = await this.client.state.minerSectors(address, tipSetKey); + public async minerSectors( + address: string, + tipSetKey?: TipSetKey, + ): Promise { + const sectorsInfo: SectorOnChainInfo[] = await this.client.state.minerSectors( + address, + tipSetKey, + ); return sectorsInfo; } @@ -342,8 +416,14 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async minerActiveSectors(address: string, tipSetKey?: TipSetKey): Promise { - const activeSectors: SectorOnChainInfo[] = await this.minerActiveSectors(address, tipSetKey); + public async minerActiveSectors( + address: string, + tipSetKey?: TipSetKey, + ): Promise { + const activeSectors: SectorOnChainInfo[] = await this.minerActiveSectors( + address, + tipSetKey, + ); return activeSectors; } @@ -352,8 +432,14 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async minerProvingDeadline(address: string, tipSetKey?: TipSetKey): Promise { - const provingDeadline: DeadlineInfo = await this.client.state.minerProvingDeadline(address, tipSetKey); + public async minerProvingDeadline( + address: string, + tipSetKey?: TipSetKey, + ): Promise { + const provingDeadline: DeadlineInfo = await this.client.state.minerProvingDeadline( + address, + tipSetKey, + ); return provingDeadline; } @@ -362,8 +448,14 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async minerPower(address: string, tipSetKey?: TipSetKey): Promise { - const power: MinerPower = await this.client.state.minerPower(address, tipSetKey); + public async minerPower( + address: string, + tipSetKey?: TipSetKey, + ): Promise { + const power: MinerPower = await this.client.state.minerPower( + address, + tipSetKey, + ); return power; } @@ -372,8 +464,14 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async minerInfo(address: string, tipSetKey?: TipSetKey): Promise { - const minerInfo: MinerInfo = await this.client.state.minerInfo(address, tipSetKey); + public async minerInfo( + address: string, + tipSetKey?: TipSetKey, + ): Promise { + const minerInfo: MinerInfo = await this.client.state.minerInfo( + address, + tipSetKey, + ); return minerInfo; } @@ -382,8 +480,14 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async minerDeadlines(address: string, tipSetKey?: TipSetKey): Promise { - const minerDeadlines: Deadline[] = await this.client.state.minerDeadlines(address, tipSetKey); + public async minerDeadlines( + address: string, + tipSetKey?: TipSetKey, + ): Promise { + const minerDeadlines: Deadline[] = await this.client.state.minerDeadlines( + address, + tipSetKey, + ); return minerDeadlines; } @@ -393,8 +497,16 @@ export class BaseWalletProvider { * @param idx * @param tipSetKey */ - public async minerPartitions(address: string, idx?: number, tipSetKey?: TipSetKey): Promise { - const minerPartitions: Partition[] = await this.client.state.minerPartitions(address, idx, tipSetKey); + public async minerPartitions( + address: string, + idx?: number, + tipSetKey?: TipSetKey, + ): Promise { + const minerPartitions: Partition[] = await this.client.state.minerPartitions( + address, + idx, + tipSetKey, + ); return minerPartitions; } @@ -403,8 +515,14 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async minerFaults(address: string, tipSetKey?: TipSetKey): Promise { - const minerFaults: BitField = await this.client.state.minerFaults(address, tipSetKey); + public async minerFaults( + address: string, + tipSetKey?: TipSetKey, + ): Promise { + const minerFaults: BitField = await this.client.state.minerFaults( + address, + tipSetKey, + ); return minerFaults; } @@ -414,8 +532,14 @@ export class BaseWalletProvider { * @param epoch * @param tipSetKey */ - public async allMinerFaults(epoch: ChainEpoch, tipSetKey?: TipSetKey): Promise { - const allFaults: Fault[] = await this.client.state.allMinerFaults(epoch, tipSetKey); + public async allMinerFaults( + epoch: ChainEpoch, + tipSetKey?: TipSetKey, + ): Promise { + const allFaults: Fault[] = await this.client.state.allMinerFaults( + epoch, + tipSetKey, + ); return allFaults; } @@ -424,8 +548,14 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async minerRecoveries(address: string, tipSetKey?: TipSetKey): Promise { - const recoveries: BitField = await this.client.state.minerRecoveries(address, tipSetKey); + public async minerRecoveries( + address: string, + tipSetKey?: TipSetKey, + ): Promise { + const recoveries: BitField = await this.client.state.minerRecoveries( + address, + tipSetKey, + ); return recoveries; } @@ -436,8 +566,16 @@ export class BaseWalletProvider { * @param sectorPreCommitInfo * @param tipSetKey */ - public async minerPreCommitDepositForPower(address: string, sectorPreCommitInfo: SectorPreCommitInfo, tipSetKey?: TipSetKey): Promise { - const deposit: string = await this.client.state.minerPreCommitDepositForPower(address, sectorPreCommitInfo, tipSetKey); + public async minerPreCommitDepositForPower( + address: string, + sectorPreCommitInfo: SectorPreCommitInfo, + tipSetKey?: TipSetKey, + ): Promise { + const deposit: string = await this.client.state.minerPreCommitDepositForPower( + address, + sectorPreCommitInfo, + tipSetKey, + ); return deposit; } @@ -447,8 +585,16 @@ export class BaseWalletProvider { * @param sectorPreCommitInfo * @param tipSetKey */ - public async minerInitialPledgeCollateral(address: string, sectorPreCommitInfo: SectorPreCommitInfo, tipSetKey?: TipSetKey): Promise { - const deposit: string = await this.client.state.minerInitialPledgeCollateral(address, sectorPreCommitInfo, tipSetKey); + public async minerInitialPledgeCollateral( + address: string, + sectorPreCommitInfo: SectorPreCommitInfo, + tipSetKey?: TipSetKey, + ): Promise { + const deposit: string = await this.client.state.minerInitialPledgeCollateral( + address, + sectorPreCommitInfo, + tipSetKey, + ); return deposit; } @@ -457,8 +603,14 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async minerAvailableBalance(address: string, tipSetKey?: TipSetKey): Promise { - const balance: string = await this.client.state.minerAvailableBalance(address, tipSetKey); + public async minerAvailableBalance( + address: string, + tipSetKey?: TipSetKey, + ): Promise { + const balance: string = await this.client.state.minerAvailableBalance( + address, + tipSetKey, + ); return balance; } @@ -468,8 +620,16 @@ export class BaseWalletProvider { * @param sector * @param tipSetKey */ - public async sectorPreCommitInfo(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise { - const preCommitInfo: SectorPreCommitOnChainInfo = await this.client.state.sectorPreCommitInfo(address, sector, tipSetKey); + public async sectorPreCommitInfo( + address: string, + sector: SectorNumber, + tipSetKey?: TipSetKey, + ): Promise { + const preCommitInfo: SectorPreCommitOnChainInfo = await this.client.state.sectorPreCommitInfo( + address, + sector, + tipSetKey, + ); return preCommitInfo; } @@ -482,8 +642,16 @@ export class BaseWalletProvider { * @remarks * NOTE: returned Expiration may not be accurate in some cases, use StateSectorExpiration to get accurate expiration epoch */ - public async sectorGetInfo(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise { - const sectorInfo: SectorOnChainInfo = await this.client.state.sectorGetInfo(address, sector, tipSetKey); + public async sectorGetInfo( + address: string, + sector: SectorNumber, + tipSetKey?: TipSetKey, + ): Promise { + const sectorInfo: SectorOnChainInfo = await this.client.state.sectorGetInfo( + address, + sector, + tipSetKey, + ); return sectorInfo; } @@ -493,8 +661,16 @@ export class BaseWalletProvider { * @param sector * @param tipSetKey */ - public async sectorExpiration(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise { - const sectorExpiration: SectorExpiration = await this.client.state.sectorExpiration(address, sector, tipSetKey); + public async sectorExpiration( + address: string, + sector: SectorNumber, + tipSetKey?: TipSetKey, + ): Promise { + const sectorExpiration: SectorExpiration = await this.client.state.sectorExpiration( + address, + sector, + tipSetKey, + ); return sectorExpiration; } @@ -504,8 +680,16 @@ export class BaseWalletProvider { * @param sector * @param tipSetKey */ - public async sectorPartition(address: string, sector: SectorNumber, tipSetKey?: TipSetKey): Promise { - const sectorLocation: SectorLocation = await this.client.state.sectorPartition(address, sector, tipSetKey); + public async sectorPartition( + address: string, + sector: SectorNumber, + tipSetKey?: TipSetKey, + ): Promise { + const sectorLocation: SectorLocation = await this.client.state.sectorPartition( + address, + sector, + tipSetKey, + ); return sectorLocation; } @@ -541,8 +725,14 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async marketBalance(address: Address, tipSetKey?: TipSetKey): Promise { - const marketBalance: MarketBalance = await this.client.state.marketBalance(address, tipSetKey); + public async marketBalance( + address: Address, + tipSetKey?: TipSetKey, + ): Promise { + const marketBalance: MarketBalance = await this.client.state.marketBalance( + address, + tipSetKey, + ); return marketBalance; } @@ -550,8 +740,12 @@ export class BaseWalletProvider { * returns the Escrow and Locked balances of every participant in the Storage Market * @param tipSetKey */ - public async marketParticipants(tipSetKey?: TipSetKey): Promise<{ [k: string]: MarketBalance }> { - const marketBalanceMap = await this.client.state.marketParticipants(tipSetKey); + public async marketParticipants( + tipSetKey?: TipSetKey, + ): Promise<{ [k: string]: MarketBalance }> { + const marketBalanceMap = await this.client.state.marketParticipants( + tipSetKey, + ); return marketBalanceMap; } @@ -559,7 +753,9 @@ export class BaseWalletProvider { * returns information about every deal in the Storage Market * @param tipSetKey */ - public async marketDeals(tipSetKey?: TipSetKey): Promise<{ [k: string]: MarketDeal }> { + public async marketDeals( + tipSetKey?: TipSetKey, + ): Promise<{ [k: string]: MarketDeal }> { const marketDealsMap = await this.client.state.marketDeals(tipSetKey); return marketDealsMap; } @@ -569,8 +765,14 @@ export class BaseWalletProvider { * @param dealId * @param tipSetKey */ - public async marketStorageDeal(dealId: DealID, tipSetKey?: TipSetKey): Promise { - const marketDeal: MarketDeal = await this.client.state.marketStorageDeal(dealId, tipSetKey); + public async marketStorageDeal( + dealId: DealID, + tipSetKey?: TipSetKey, + ): Promise { + const marketDeal: MarketDeal = await this.client.state.marketStorageDeal( + dealId, + tipSetKey, + ); return marketDeal; } @@ -579,7 +781,10 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async lookupId(address: Address, tipSetKey?: TipSetKey): Promise
{ + public async lookupId( + address: Address, + tipSetKey?: TipSetKey, + ): Promise
{ const id: Address = await this.client.state.lookupId(address, tipSetKey); return id; } @@ -589,7 +794,10 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async accountKey(address: Address, tipSetKey?: TipSetKey): Promise
{ + public async accountKey( + address: Address, + tipSetKey?: TipSetKey, + ): Promise
{ const key: Address = await this.client.state.accountKey(address, tipSetKey); return key; } @@ -599,7 +807,10 @@ export class BaseWalletProvider { * @param cid1 * @param cid2 */ - public async changedActors(cid1?: Cid, cid2?: Cid): Promise<{ [k: string]: Actor }> { + public async changedActors( + cid1?: Cid, + cid2?: Cid, + ): Promise<{ [k: string]: Actor }> { const actors = await this.client.state.changedActors(cid1, cid2); return actors; } @@ -609,7 +820,10 @@ export class BaseWalletProvider { * @param cid * @param tipSetKey */ - public async getReceipt(cid: Cid, tipSetKey?: TipSetKey): Promise { + public async getReceipt( + cid: Cid, + tipSetKey?: TipSetKey, + ): Promise { const receipt = await this.client.state.getReceipt(cid, tipSetKey); return receipt; } @@ -619,23 +833,32 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async minerSectorCount(address: Address, tipSetKey?: TipSetKey): Promise { - const sectors = await this.client.state.minerSectorCount(address, tipSetKey); + public async minerSectorCount( + address: Address, + tipSetKey?: TipSetKey, + ): Promise { + const sectors = await this.client.state.minerSectorCount( + address, + tipSetKey, + ); return sectors; } //Multisig wallet methods /** - * returns the vesting details of a given multisig. - * @param address - * @param tipSetKey - */ + * returns the vesting details of a given multisig. + * @param address + * @param tipSetKey + */ public async msigGetVestingSchedule( address: string, tipSetKey: TipSetKey, ): Promise { - const schedule = await this.client.msig.getVestingSchedule(address, tipSetKey); + const schedule = await this.client.msig.getVestingSchedule( + address, + tipSetKey, + ); return schedule; } @@ -644,7 +867,10 @@ export class BaseWalletProvider { * @param address * @param tipSetKey */ - public async msigGetAvailableBalance(address: string, tipSetKey: TipSetKey): Promise { + public async msigGetAvailableBalance( + address: string, + tipSetKey: TipSetKey, + ): Promise { const ret = await this.client.msig.getAvailableBalance(address, tipSetKey); return ret; } @@ -655,9 +881,12 @@ export class BaseWalletProvider { * @param startEpoch * @param endEpoch */ - public async msigGetVested(address: string, startEpoch: TipSetKey, endEpoch: TipSetKey): Promise { + public async msigGetVested( + address: string, + startEpoch: TipSetKey, + endEpoch: TipSetKey, + ): Promise { const ret = await this.client.msig.getVested(address, startEpoch, endEpoch); return ret; } } - diff --git a/src/providers/wallet/LightWalletProvider.ts b/src/providers/wallet/LightWalletProvider.ts index 69b8b0b..ee01079 100644 --- a/src/providers/wallet/LightWalletProvider.ts +++ b/src/providers/wallet/LightWalletProvider.ts @@ -1,14 +1,32 @@ -import { Message, SignedMessage, Signature, KeyInfo, DEFAULT_HD_PATH, TEST_DEFAULT_HD_PATH, MethodMultisig, Cid, ChainEpoch, MethodInit } from "../Types"; -import { BaseWalletProvider } from "./BaseWalletProvider"; -import { MultisigProviderInterface, WalletProviderInterface } from "../ProviderInterfaces"; -import { Keystore } from "../../utils/keystore"; -import { LightWalletSigner } from "../../signers/LightWalletSigner"; -import { LotusClient } from "../.."; -import { addressAsBytes } from "@zondax/filecoin-signing-tools" -import cbor from "ipld-dag-cbor"; -import cid from "cids"; -import BigNumber from "bignumber.js"; -import { createApproveMessage, createCancelMessage, createProposeMessage } from "../../utils/msig"; +import { + Message, + SignedMessage, + Signature, + KeyInfo, + DEFAULT_HD_PATH, + TEST_DEFAULT_HD_PATH, + MethodMultisig, + Cid, + ChainEpoch, + MethodInit, +} from '../Types'; +import { BaseWalletProvider } from './BaseWalletProvider'; +import { + MultisigProviderInterface, + WalletProviderInterface, +} from '../ProviderInterfaces'; +import { Keystore } from '../../utils/keystore'; +import { LightWalletSigner } from '../../signers/LightWalletSigner'; +import { LotusClient } from '../..'; +import { addressAsBytes } from '@zondax/filecoin-signing-tools'; +import cbor from 'ipld-dag-cbor'; +import cid from 'cids'; +import BigNumber from 'bignumber.js'; +import { + createApproveMessage, + createCancelMessage, + createProposeMessage, +} from '../../utils/msig'; interface LighWalletOptions { encKeystore?: string; @@ -17,23 +35,28 @@ interface LighWalletOptions { password?: string; } -export class LightWalletProvider extends BaseWalletProvider implements WalletProviderInterface, MultisigProviderInterface { - +export class LightWalletProvider + extends BaseWalletProvider + implements WalletProviderInterface, MultisigProviderInterface { public keystore!: Keystore; private hdPathString = DEFAULT_HD_PATH; private signer!: LightWalletSigner; private pwdCallback: Function; - constructor(client: LotusClient, pwdCallback: Function, path: string = DEFAULT_HD_PATH,) { + constructor( + client: LotusClient, + pwdCallback: Function, + path: string = DEFAULT_HD_PATH, + ) { super(client); this.pwdCallback = pwdCallback; if (path === 'test' || !path) this.hdPathString = TEST_DEFAULT_HD_PATH; } public async newAddress(): Promise { - await this.keystore.newAddress(1, this.pwdCallback()) + await this.keystore.newAddress(1, this.pwdCallback()); const addresses = await this.getAddresses(); - return addresses[addresses.length -1]; + return addresses[addresses.length - 1]; } public async deleteAddress(address: string): Promise { @@ -61,11 +84,13 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro } public async setDefaultAddress(address: string): Promise { - this.keystore.setDefaultAddress(address) + this.keystore.setDefaultAddress(address); } public async sendMessage(msg: Message): Promise { - const signedMessage: SignedMessage | undefined = await this.signMessage(msg); + const signedMessage: SignedMessage | undefined = await this.signMessage( + msg, + ); if (signedMessage) { await this.sendSignedMessage(signedMessage); return signedMessage as SignedMessage; @@ -83,7 +108,11 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro } //todo - public async verify(address: string, data: string | ArrayBuffer, sign: Signature): Promise { + public async verify( + address: string, + data: string | ArrayBuffer, + sign: Signature, + ): Promise { return undefined as any; } @@ -105,27 +134,31 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro senderAddressOfCreateMsg: string, ): Promise { const addresses: any[] = []; - approvingAddresses.forEach(address => { + approvingAddresses.forEach((address) => { addresses.push(addressAsBytes(address)); }); - const constructorParams = [addresses, requiredNumberOfSenders, unlockDuration, startEpoch]; + const constructorParams = [ + addresses, + requiredNumberOfSenders, + unlockDuration, + startEpoch, + ]; const serializedConstructorParams = cbor.util.serialize(constructorParams); - const MultisigActorCodeID = new cid('bafkqadtgnfwc6mrpnv2wy5djonuwo'); + const MultisigActorCodeID = new cid( + 'bafk2bzaced4gcxjwy6garxwfw6y5a2k4jewj4t5nzopjy4qwnimhjtnsgo3ss', + ); - const execParams = [ - MultisigActorCodeID, - serializedConstructorParams, - ]; + const execParams = [MultisigActorCodeID, serializedConstructorParams]; const serializedParams = cbor.util.serialize(execParams); const buff = Buffer.from(serializedParams); let messageWithoutGasParams = { From: senderAddressOfCreateMsg, - To: "t01", + To: 't01', Value: new BigNumber(initialBalance), Method: MethodInit.Exec, - Params: buff.toString('base64') + Params: buff.toString('base64'), }; const message = await this.createMessage(messageWithoutGasParams as any); @@ -149,7 +182,14 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro senderAddressOfProposeMsg: string, ): Promise { const params: any[] = []; - const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, recipientAddres, value, 0, params) + const messageWithoutGasParams = await createProposeMessage( + address, + senderAddressOfProposeMsg, + recipientAddres, + value, + 0, + params, + ); const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -197,7 +237,7 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro recipientAddres, 0, value, - [] + [], ); const message = await this.createMessage(messageWithoutGasParams as any); @@ -223,7 +263,9 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro recipientAddres: string, value: string, ): Promise { - const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); + const proposerId = await this.client.state.lookupId( + senderAddressOfCancelMsg, + ); const messageWithoutGasParams = await createCancelMessage( address, @@ -233,7 +275,7 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro recipientAddres, 0, value, - [] + [], ); const message = await this.createMessage(messageWithoutGasParams as any); @@ -256,8 +298,18 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro newSignerAddress: string, increaseNumberOfRequiredSigners: boolean, ): Promise { - const params: any[] = [addressAsBytes(newSignerAddress), increaseNumberOfRequiredSigners]; - const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, address, '0', MethodMultisig.AddSigner, params) + const params: any[] = [ + addressAsBytes(newSignerAddress), + increaseNumberOfRequiredSigners, + ]; + const messageWithoutGasParams = await createProposeMessage( + address, + senderAddressOfProposeMsg, + address, + '0', + MethodMultisig.AddSigner, + params, + ); const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -279,9 +331,12 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro proposedMessageId: number, proposerAddress: string, newSignerAddress: string, - increaseNumberOfRequiredSigners: boolean + increaseNumberOfRequiredSigners: boolean, ): Promise { - const values = [addressAsBytes(newSignerAddress), increaseNumberOfRequiredSigners]; + const values = [ + addressAsBytes(newSignerAddress), + increaseNumberOfRequiredSigners, + ]; const proposerId = await this.client.state.lookupId(proposerAddress); const messageWithoutGasParams = await createApproveMessage( @@ -292,8 +347,8 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro address, MethodMultisig.AddSigner, '0', - values - ) + values, + ); const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -314,10 +369,15 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro senderAddressOfCancelMsg: string, proposedMessageId: number, newSignerAddress: string, - increaseNumberOfRequiredSigners: boolean + increaseNumberOfRequiredSigners: boolean, ): Promise { - const values = [addressAsBytes(newSignerAddress), increaseNumberOfRequiredSigners]; - const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); + const values = [ + addressAsBytes(newSignerAddress), + increaseNumberOfRequiredSigners, + ]; + const proposerId = await this.client.state.lookupId( + senderAddressOfCancelMsg, + ); const messageWithoutGasParams = await createCancelMessage( address, @@ -327,8 +387,8 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro address, MethodMultisig.AddSigner, '0', - values - ) + values, + ); const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -349,9 +409,18 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro oldSignerAddress: string, newSignerAddress: string, ): Promise { - - const params: any[] = [addressAsBytes(oldSignerAddress), addressAsBytes(newSignerAddress)]; - const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, address, '0', MethodMultisig.SwapSigner, params) + const params: any[] = [ + addressAsBytes(oldSignerAddress), + addressAsBytes(newSignerAddress), + ]; + const messageWithoutGasParams = await createProposeMessage( + address, + senderAddressOfProposeMsg, + address, + '0', + MethodMultisig.SwapSigner, + params, + ); const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -376,7 +445,10 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro oldSignerAddress: string, newSignerAddress: string, ): Promise { - const values = [addressAsBytes(oldSignerAddress), addressAsBytes(newSignerAddress)]; + const values = [ + addressAsBytes(oldSignerAddress), + addressAsBytes(newSignerAddress), + ]; const proposerId = await this.client.state.lookupId(proposerAddress); const messageWithoutGasParams = await createApproveMessage( @@ -387,7 +459,7 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro address, MethodMultisig.SwapSigner, '0', - values + values, ); const message = await this.createMessage(messageWithoutGasParams as any); @@ -412,8 +484,13 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro oldSignerAddress: string, newSignerAddress: string, ): Promise { - const values = [addressAsBytes(oldSignerAddress), addressAsBytes(newSignerAddress)]; - const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); + const values = [ + addressAsBytes(oldSignerAddress), + addressAsBytes(newSignerAddress), + ]; + const proposerId = await this.client.state.lookupId( + senderAddressOfCancelMsg, + ); const messageWithoutGasParams = await createCancelMessage( address, @@ -423,7 +500,7 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro address, MethodMultisig.SwapSigner, '0', - values + values, ); const message = await this.createMessage(messageWithoutGasParams as any); @@ -446,13 +523,23 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro addressToRemove: string, decreaseNumberOfRequiredSigners: boolean, ): Promise { - const params: any[] = [addressAsBytes(addressToRemove), decreaseNumberOfRequiredSigners]; - const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, address, '0', MethodMultisig.RemoveSigner, params) + const params: any[] = [ + addressAsBytes(addressToRemove), + decreaseNumberOfRequiredSigners, + ]; + const messageWithoutGasParams = await createProposeMessage( + address, + senderAddressOfProposeMsg, + address, + '0', + MethodMultisig.RemoveSigner, + params, + ); const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; - }; + } /** * approves a previously proposed RemoveSigner message @@ -463,31 +550,36 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ - public async msigApproveRemoveSigner(address: string, + public async msigApproveRemoveSigner( + address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, addressToRemove: string, - decreaseNumberOfRequiredSigners: boolean): Promise { - const values = [addressAsBytes(addressToRemove), decreaseNumberOfRequiredSigners]; - const proposerId = await this.client.state.lookupId(proposerAddress); - - const messageWithoutGasParams = await createApproveMessage( - address, - senderAddressOfApproveMsg, - proposedMessageId, - proposerId, - address, - MethodMultisig.RemoveSigner, - '0', - values - ) - const message = await this.createMessage(messageWithoutGasParams as any); - const signedMessage = await this.signMessage(message); - const msgCid = await this.sendSignedMessage(signedMessage); - - return msgCid; - }; + decreaseNumberOfRequiredSigners: boolean, + ): Promise { + const values = [ + addressAsBytes(addressToRemove), + decreaseNumberOfRequiredSigners, + ]; + const proposerId = await this.client.state.lookupId(proposerAddress); + + const messageWithoutGasParams = await createApproveMessage( + address, + senderAddressOfApproveMsg, + proposedMessageId, + proposerId, + address, + MethodMultisig.RemoveSigner, + '0', + values, + ); + const message = await this.createMessage(messageWithoutGasParams as any); + const signedMessage = await this.signMessage(message); + const msgCid = await this.sendSignedMessage(signedMessage); + + return msgCid; + } /** * cancels a previously proposed RemoveSigner message @@ -497,30 +589,37 @@ export class LightWalletProvider extends BaseWalletProvider implements WalletPro * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ - public async msigCancelRemoveSigner(address: string, + public async msigCancelRemoveSigner( + address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, addressToRemove: string, - decreaseNumberOfRequiredSigners: boolean): Promise { - const values = [addressAsBytes(addressToRemove), decreaseNumberOfRequiredSigners]; - const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); - - const messageWithoutGasParams = await createCancelMessage( - address, - senderAddressOfCancelMsg, - proposedMessageId, - proposerId, - address, - MethodMultisig.RemoveSigner, - '0', - values - ) - const message = await this.createMessage(messageWithoutGasParams as any); - const signedMessage = await this.signMessage(message); - const msgCid = await this.sendSignedMessage(signedMessage); - - return msgCid; - }; + decreaseNumberOfRequiredSigners: boolean, + ): Promise { + const values = [ + addressAsBytes(addressToRemove), + decreaseNumberOfRequiredSigners, + ]; + const proposerId = await this.client.state.lookupId( + senderAddressOfCancelMsg, + ); + + const messageWithoutGasParams = await createCancelMessage( + address, + senderAddressOfCancelMsg, + proposedMessageId, + proposerId, + address, + MethodMultisig.RemoveSigner, + '0', + values, + ); + const message = await this.createMessage(messageWithoutGasParams as any); + const signedMessage = await this.signMessage(message); + const msgCid = await this.sendSignedMessage(signedMessage); + + return msgCid; + } // Own functions public async createLightWallet(password: string) { diff --git a/src/providers/wallet/MnemonicWalletProvider.ts b/src/providers/wallet/MnemonicWalletProvider.ts index 81cb805..4a49feb 100644 --- a/src/providers/wallet/MnemonicWalletProvider.ts +++ b/src/providers/wallet/MnemonicWalletProvider.ts @@ -1,21 +1,40 @@ -import { Message, SignedMessage, Signature, KeyInfo, Cid, ChainEpoch, DEFAULT_HD_PATH, TEST_DEFAULT_HD_PATH, MethodInit, MethodMultisig } from "../Types"; -import { BaseWalletProvider } from "./BaseWalletProvider"; -import { MnemonicSigner } from "../../signers/MnemonicSigner"; -import { StringGetter } from "../Types"; -import { LotusClient } from "../.."; -import { MultisigProviderInterface, WalletProviderInterface } from "../ProviderInterfaces"; -import { addressAsBytes } from "@zondax/filecoin-signing-tools" -import cbor from "ipld-dag-cbor"; -import cid from "cids"; -import BigNumber from "bignumber.js"; -import { createApproveMessage, createCancelMessage, createProposeMessage } from "../../utils/msig"; - - -export class MnemonicWalletProvider extends BaseWalletProvider implements WalletProviderInterface, MultisigProviderInterface { - +import { + Message, + SignedMessage, + Signature, + KeyInfo, + Cid, + ChainEpoch, + DEFAULT_HD_PATH, + TEST_DEFAULT_HD_PATH, + MethodInit, + MethodMultisig, +} from '../Types'; +import { BaseWalletProvider } from './BaseWalletProvider'; +import { MnemonicSigner } from '../../signers/MnemonicSigner'; +import { StringGetter } from '../Types'; +import { LotusClient } from '../..'; +import { + MultisigProviderInterface, + WalletProviderInterface, +} from '../ProviderInterfaces'; +import { addressAsBytes } from '@zondax/filecoin-signing-tools'; +import cbor from 'ipld-dag-cbor'; +import cid from 'cids'; +import BigNumber from 'bignumber.js'; +import { + createApproveMessage, + createCancelMessage, + createProposeMessage, +} from '../../utils/msig'; + +export class MnemonicWalletProvider + extends BaseWalletProvider + implements WalletProviderInterface, MultisigProviderInterface { private signer: MnemonicSigner; - constructor(client: LotusClient, + constructor( + client: LotusClient, mnemonic: string | StringGetter, path: string = DEFAULT_HD_PATH, ) { @@ -25,7 +44,7 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet } public async newAddress(): Promise { - await this.signer.newAddress(1) + await this.signer.newAddress(1); const addresses = await this.getAddresses(); return addresses[addresses.length - 1]; } @@ -72,7 +91,11 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet return undefined as any; } - public async verify(address: string, data: string | ArrayBuffer, sign: Signature): Promise { + public async verify( + address: string, + data: string | ArrayBuffer, + sign: Signature, + ): Promise { return undefined as any; } @@ -99,29 +122,32 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet senderAddressOfCreateMsg: string, ): Promise { const addresses: any[] = []; - approvingAddresses.forEach(address => { + approvingAddresses.forEach((address) => { addresses.push(addressAsBytes(address)); }); - const constructorParams = [addresses, requiredNumberOfSenders, unlockDuration, startEpoch]; + const constructorParams = [ + addresses, + requiredNumberOfSenders, + unlockDuration, + startEpoch, + ]; const serializedConstructorParams = cbor.util.serialize(constructorParams); - const MultisigActorCodeID = new cid('bafkqadtgnfwc6mrpnv2wy5djonuwo'); + const MultisigActorCodeID = new cid( + 'bafk2bzaced4gcxjwy6garxwfw6y5a2k4jewj4t5nzopjy4qwnimhjtnsgo3ss', + ); - const execParams = [ - MultisigActorCodeID, - serializedConstructorParams, - ]; + const execParams = [MultisigActorCodeID, serializedConstructorParams]; const serializedParams = cbor.util.serialize(execParams); const buff = Buffer.from(serializedParams); let messageWithoutGasParams = { From: senderAddressOfCreateMsg, - To: "t01", + To: 't01', Value: new BigNumber(initialBalance), Method: MethodInit.Exec, - Params: buff.toString('base64') + Params: buff.toString('base64'), }; - const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -143,7 +169,14 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet senderAddressOfProposeMsg: string, ): Promise { const params: any[] = []; - const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, recipientAddres, value, 0, params) + const messageWithoutGasParams = await createProposeMessage( + address, + senderAddressOfProposeMsg, + recipientAddres, + value, + 0, + params, + ); const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -191,7 +224,7 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet recipientAddres, 0, value, - [] + [], ); const message = await this.createMessage(messageWithoutGasParams as any); @@ -216,7 +249,9 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet recipientAddres: string, value: string, ): Promise { - const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); + const proposerId = await this.client.state.lookupId( + senderAddressOfCancelMsg, + ); const messageWithoutGasParams = await createCancelMessage( address, @@ -226,7 +261,7 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet recipientAddres, 0, value, - [] + [], ); const message = await this.createMessage(messageWithoutGasParams as any); @@ -249,8 +284,18 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet newSignerAddress: string, increaseNumberOfRequiredSigners: boolean, ): Promise { - const params: any[] = [addressAsBytes(newSignerAddress), increaseNumberOfRequiredSigners]; - const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, address, '0', MethodMultisig.AddSigner, params) + const params: any[] = [ + addressAsBytes(newSignerAddress), + increaseNumberOfRequiredSigners, + ]; + const messageWithoutGasParams = await createProposeMessage( + address, + senderAddressOfProposeMsg, + address, + '0', + MethodMultisig.AddSigner, + params, + ); const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -272,9 +317,12 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet proposedMessageId: number, proposerAddress: string, newSignerAddress: string, - increaseNumberOfRequiredSigners: boolean + increaseNumberOfRequiredSigners: boolean, ): Promise { - const values = [addressAsBytes(newSignerAddress), increaseNumberOfRequiredSigners]; + const values = [ + addressAsBytes(newSignerAddress), + increaseNumberOfRequiredSigners, + ]; const proposerId = await this.client.state.lookupId(proposerAddress); const messageWithoutGasParams = await createApproveMessage( @@ -285,8 +333,8 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet address, MethodMultisig.AddSigner, '0', - values - ) + values, + ); const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -307,10 +355,15 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet senderAddressOfCancelMsg: string, proposedMessageId: number, newSignerAddress: string, - increaseNumberOfRequiredSigners: boolean + increaseNumberOfRequiredSigners: boolean, ): Promise { - const values = [addressAsBytes(newSignerAddress), increaseNumberOfRequiredSigners]; - const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); + const values = [ + addressAsBytes(newSignerAddress), + increaseNumberOfRequiredSigners, + ]; + const proposerId = await this.client.state.lookupId( + senderAddressOfCancelMsg, + ); const messageWithoutGasParams = await createCancelMessage( address, @@ -320,8 +373,8 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet address, MethodMultisig.AddSigner, '0', - values - ) + values, + ); const message = await this.createMessage(messageWithoutGasParams as any); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -342,9 +395,18 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet oldSignerAddress: string, newSignerAddress: string, ): Promise { - - const params: any[] = [addressAsBytes(oldSignerAddress), addressAsBytes(newSignerAddress)]; - const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, address, '0', MethodMultisig.SwapSigner, params) + const params: any[] = [ + addressAsBytes(oldSignerAddress), + addressAsBytes(newSignerAddress), + ]; + const messageWithoutGasParams = await createProposeMessage( + address, + senderAddressOfProposeMsg, + address, + '0', + MethodMultisig.SwapSigner, + params, + ); const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); @@ -369,7 +431,10 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet oldSignerAddress: string, newSignerAddress: string, ): Promise { - const values = [addressAsBytes(oldSignerAddress), addressAsBytes(newSignerAddress)]; + const values = [ + addressAsBytes(oldSignerAddress), + addressAsBytes(newSignerAddress), + ]; const proposerId = await this.client.state.lookupId(proposerAddress); const messageWithoutGasParams = await createApproveMessage( @@ -380,7 +445,7 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet address, MethodMultisig.SwapSigner, '0', - values + values, ); const message = await this.createMessage(messageWithoutGasParams as any); @@ -405,8 +470,13 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet oldSignerAddress: string, newSignerAddress: string, ): Promise { - const values = [addressAsBytes(oldSignerAddress), addressAsBytes(newSignerAddress)]; - const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); + const values = [ + addressAsBytes(oldSignerAddress), + addressAsBytes(newSignerAddress), + ]; + const proposerId = await this.client.state.lookupId( + senderAddressOfCancelMsg, + ); const messageWithoutGasParams = await createCancelMessage( address, @@ -416,7 +486,7 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet address, MethodMultisig.SwapSigner, '0', - values + values, ); const message = await this.createMessage(messageWithoutGasParams as any); @@ -439,13 +509,23 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet addressToRemove: string, decreaseNumberOfRequiredSigners: boolean, ): Promise { - const params: any[] = [addressAsBytes(addressToRemove), decreaseNumberOfRequiredSigners]; - const messageWithoutGasParams = await createProposeMessage(address, senderAddressOfProposeMsg, address, '0', MethodMultisig.RemoveSigner, params) + const params: any[] = [ + addressAsBytes(addressToRemove), + decreaseNumberOfRequiredSigners, + ]; + const messageWithoutGasParams = await createProposeMessage( + address, + senderAddressOfProposeMsg, + address, + '0', + MethodMultisig.RemoveSigner, + params, + ); const message = await this.createMessage(messageWithoutGasParams); const signedMessage = await this.signMessage(message); const msgCid = await this.sendSignedMessage(signedMessage); return msgCid; - }; + } /** * approves a previously proposed RemoveSigner message @@ -456,31 +536,36 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ - public async msigApproveRemoveSigner(address: string, + public async msigApproveRemoveSigner( + address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, addressToRemove: string, - decreaseNumberOfRequiredSigners: boolean): Promise { - const values = [addressAsBytes(addressToRemove), decreaseNumberOfRequiredSigners]; - const proposerId = await this.client.state.lookupId(proposerAddress); - - const messageWithoutGasParams = await createApproveMessage( - address, - senderAddressOfApproveMsg, - proposedMessageId, - proposerId, - address, - MethodMultisig.RemoveSigner, - '0', - values - ) - const message = await this.createMessage(messageWithoutGasParams as any); - const signedMessage = await this.signMessage(message); - const msgCid = await this.sendSignedMessage(signedMessage); - - return msgCid; - }; + decreaseNumberOfRequiredSigners: boolean, + ): Promise { + const values = [ + addressAsBytes(addressToRemove), + decreaseNumberOfRequiredSigners, + ]; + const proposerId = await this.client.state.lookupId(proposerAddress); + + const messageWithoutGasParams = await createApproveMessage( + address, + senderAddressOfApproveMsg, + proposedMessageId, + proposerId, + address, + MethodMultisig.RemoveSigner, + '0', + values, + ); + const message = await this.createMessage(messageWithoutGasParams as any); + const signedMessage = await this.signMessage(message); + const msgCid = await this.sendSignedMessage(signedMessage); + + return msgCid; + } /** * cancels a previously proposed RemoveSigner message @@ -490,28 +575,35 @@ export class MnemonicWalletProvider extends BaseWalletProvider implements Wallet * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ - public async msigCancelRemoveSigner(address: string, + public async msigCancelRemoveSigner( + address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, addressToRemove: string, - decreaseNumberOfRequiredSigners: boolean): Promise { - const values = [addressAsBytes(addressToRemove), decreaseNumberOfRequiredSigners]; - const proposerId = await this.client.state.lookupId(senderAddressOfCancelMsg); - - const messageWithoutGasParams = await createCancelMessage( - address, - senderAddressOfCancelMsg, - proposedMessageId, - proposerId, - address, - MethodMultisig.RemoveSigner, - '0', - values - ) - const message = await this.createMessage(messageWithoutGasParams as any); - const signedMessage = await this.signMessage(message); - const msgCid = await this.sendSignedMessage(signedMessage); - - return msgCid; - }; + decreaseNumberOfRequiredSigners: boolean, + ): Promise { + const values = [ + addressAsBytes(addressToRemove), + decreaseNumberOfRequiredSigners, + ]; + const proposerId = await this.client.state.lookupId( + senderAddressOfCancelMsg, + ); + + const messageWithoutGasParams = await createCancelMessage( + address, + senderAddressOfCancelMsg, + proposedMessageId, + proposerId, + address, + MethodMultisig.RemoveSigner, + '0', + values, + ); + const message = await this.createMessage(messageWithoutGasParams as any); + const signedMessage = await this.signMessage(message); + const msgCid = await this.sendSignedMessage(signedMessage); + + return msgCid; + } } diff --git a/tests/src/index.ts b/tests/src/index.ts index 94d61d7..d55ac7d 100644 --- a/tests/src/index.ts +++ b/tests/src/index.ts @@ -1,21 +1,20 @@ -"use strict"; - -import "./test-auth"; -import "./test-chain"; -import "./test-client"; -import "./test-common"; -import "./test-gas"; -import "./test-lightwallet"; -import "./test-miner"; -import "./test-mpool"; -import "./test-multisig-lotus"; -import "./test-multisig-lightwallet"; -import "./test-multisig-mnemonic"; -import "./test-net"; -import "./test-paych"; -import "./test-wallet-lotus"; -import "./test-wallet-mnemonic"; -import "./test-state"; -import "./test-sync"; -import "./test-send-message"; +'use strict'; +import './test-auth'; +import './test-chain'; +import './test-client'; +import './test-common'; +import './test-gas'; +import './test-lightwallet'; +import './test-miner'; +import './test-mpool'; +import './test-multisig-lotus'; +import './test-multisig-lightwallet'; +import './test-multisig-mnemonic'; +import './test-net'; +import './test-paych'; +import './test-wallet-lotus'; +import './test-wallet-mnemonic'; +import './test-state'; +import './test-sync'; +import './test-send-message'; diff --git a/tests/src/test-chain.ts b/tests/src/test-chain.ts index 21a5ce9..d48a511 100644 --- a/tests/src/test-chain.ts +++ b/tests/src/test-chain.ts @@ -1,26 +1,39 @@ -import assert from "assert"; -import { LOTUS_AUTH_TOKEN } from "../tools/testnet/credentials/credentials"; +import assert from 'assert'; +import { LOTUS_AUTH_TOKEN } from '../tools/testnet/credentials/credentials'; import { LotusClient } from '../../src/providers/LotusClient'; import { HttpJsonRpcConnector } from '../../src/connectors/HttpJsonRpcConnector'; import { WsJsonRpcConnector } from '../../src/connectors/WsJsonRpcConnector'; import Timer = NodeJS.Timer; import { ObjStat } from '../../src/providers/Types'; -const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); -const wsConnector = new WsJsonRpcConnector({ url: 'ws://localhost:8000/rpc/v0' }); +const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, +}); +const wsConnector = new WsJsonRpcConnector({ + url: 'ws://localhost:8000/rpc/v0', +}); -describe("Chain methods", function() { - it("statistics about the graph", async () => { +describe('Chain methods', function () { + it('statistics about the graph', async () => { const provider = new LotusClient(httpConnector); const tipset1 = await provider.chain.getTipSetByHeight(1); const tipset2 = await provider.chain.getTipSetByHeight(10); const stat = await provider.chain.statObj(tipset2.Cids[0]); - const diffStat = await provider.chain.statObj(tipset2.Cids[0], tipset1.Cids[0]); - const isStatValid = (stat: ObjStat) => typeof stat.Size === 'number' && typeof stat.Links === 'number'; - assert.strictEqual(isStatValid(stat) && isStatValid(diffStat), true, 'invalid obj statistics'); + const diffStat = await provider.chain.statObj( + tipset2.Cids[0], + tipset1.Cids[0], + ); + const isStatValid = (stat: ObjStat) => + typeof stat.Size === 'number' && typeof stat.Links === 'number'; + assert.strictEqual( + isStatValid(stat) && isStatValid(diffStat), + true, + 'invalid obj statistics', + ); }); - it("get genesis", async () => { + it('get genesis', async () => { const provider = new LotusClient(httpConnector); const genesisTipSet = await provider.chain.getGenesis(); const valid = @@ -30,110 +43,243 @@ describe("Chain methods", function() { assert.strictEqual(valid, true, 'invalid genesis tipSet'); }); - it("get tipSet weight", async () => { + it('get tipSet weight', async () => { const provider = new LotusClient(httpConnector); const tipSetWeight = await provider.chain.getTipSetWeight(); - assert.strictEqual(typeof tipSetWeight === 'string', true, 'invalid tipSet weight'); + assert.strictEqual( + typeof tipSetWeight === 'string', + true, + 'invalid tipSet weight', + ); }); - it("get path", async () => { + it('get path', async () => { const provider = new LotusClient(httpConnector); const tipSet = await provider.chain.getTipSetByHeight(1); const tipSet2 = await provider.chain.getTipSetByHeight(10); - const path = await provider.chain.getPath([tipSet.Cids[0]], [tipSet2.Cids[0]]); - const typeValid = path.reduce((acc, pathItem) => acc === false ? acc : typeof pathItem.Type === 'string', true); + const path = await provider.chain.getPath( + [tipSet.Cids[0]], + [tipSet2.Cids[0]], + ); + const typeValid = path.reduce( + (acc, pathItem) => + acc === false ? acc : typeof pathItem.Type === 'string', + true, + ); assert.strictEqual(typeValid, true, 'invalid path'); }); - it("should read obj", async () => { + it('should read obj', async () => { const provider = new LotusClient(httpConnector); const tipSet = await provider.chain.getTipSetByHeight(1); const obj = await provider.chain.readObj(tipSet.Cids[0]); assert.strictEqual(typeof obj === 'string', true, 'invalid obj'); }); - it("should get messages in block [ws]", async function() { + it('should get messages in block [ws]', async function () { const provider = new LotusClient(wsConnector); const tipSet = await provider.chain.getTipSetByHeight(1); const messages = await provider.chain.getBlockMessages(tipSet.Cids[0]); - assert.strictEqual(JSON.stringify(Object.keys(messages)), JSON.stringify(['BlsMessages', 'SecpkMessages', 'Cids']), "wrong block messages"); + assert.strictEqual( + JSON.stringify(Object.keys(messages)), + JSON.stringify(['BlsMessages', 'SecpkMessages', 'Cids']), + 'wrong block messages', + ); await provider.release(); }); - it("should get messages in block [http]", async function() { + it('should get messages in block [http]', async function () { const provider = new LotusClient(httpConnector); const tipSet = await provider.chain.getTipSetByHeight(1); const messages = await provider.chain.getBlockMessages(tipSet.Cids[0]); - assert.strictEqual(JSON.stringify(Object.keys(messages)), JSON.stringify(['BlsMessages', 'SecpkMessages', 'Cids']), "wrong block messages"); + assert.strictEqual( + JSON.stringify(Object.keys(messages)), + JSON.stringify(['BlsMessages', 'SecpkMessages', 'Cids']), + 'wrong block messages', + ); }); - it("should be notified on chain head change [ws]", function(done) { + it('should be notified on chain head change [ws]', function (done) { this.timeout(4000); const provider = new LotusClient(wsConnector); - provider.chain.chainNotify(headChange => { + provider.chain.chainNotify((headChange) => { const type = headChange[0].Type; - assert.equal(typeof(type), "string", "wrong chain head type"); - provider.release().then(() => { done() }); - }) + assert.equal(typeof type, 'string', 'wrong chain head type'); + provider.release().then(() => { + done(); + }); + }); }); - it("should be notified on chain head change [http]", function(done) { + it('should be notified on chain head change [http]', function (done) { this.timeout(4000); let intervalId: Timer | undefined; const provider = new LotusClient(httpConnector); - provider.chain.chainNotify(headChange => { - const type = headChange[0].Type; - assert.strictEqual(typeof(type), "string", "wrong chain head type"); - if (intervalId) { - provider.chain.stopChainNotify(intervalId); - } - done(); - }).then(intervalIdResponse => { - intervalId = intervalIdResponse; - }) + provider.chain + .chainNotify((headChange) => { + const type = headChange[0].Type; + assert.strictEqual(typeof type, 'string', 'wrong chain head type'); + if (intervalId) { + provider.chain.stopChainNotify(intervalId); + } + done(); + }) + .then((intervalIdResponse) => { + intervalId = intervalIdResponse; + }); }); - it("should get head [http]", async function() { + it('should get head [http]', async function () { const con = new LotusClient(httpConnector); const head = await con.chain.getHead(); - assert.strictEqual(JSON.stringify(Object.keys(head)), JSON.stringify(['Cids', 'Blocks', 'Height']), "wrong chain head"); + assert.strictEqual( + JSON.stringify(Object.keys(head)), + JSON.stringify(['Cids', 'Blocks', 'Height']), + 'wrong chain head', + ); }); - it("should get chain head [ws]", async function() { + it('should get chain head [ws]', async function () { const provider = new LotusClient(wsConnector); const head = await provider.chain.getHead(); - assert.strictEqual(JSON.stringify(Object.keys(head)), JSON.stringify(['Cids', 'Blocks', 'Height']), "wrong chain head"); + assert.strictEqual( + JSON.stringify(Object.keys(head)), + JSON.stringify(['Cids', 'Blocks', 'Height']), + 'wrong chain head', + ); await provider.release(); }); - it("should get block", async function() { + it('should get block', async function () { const provider = new LotusClient(httpConnector); const tipSet = await provider.chain.getTipSetByHeight(1); const block = await provider.chain.getBlock(tipSet.Cids[0]); - assert.strictEqual(typeof block.Miner === 'string', true, "invalid block"); + assert.strictEqual(typeof block.Miner === 'string', true, 'invalid block'); }); - it("should get message", async function() { + it('should get message', async function () { const con = new LotusClient(httpConnector); const messages = await con.state.listMessages({ - To: 't01000' + To: 't01000', }); const message = await con.chain.getMessage(messages[0]); - assert.strictEqual(message.To === 't01000', true, "invalid message"); + assert.strictEqual(message.To === 't01000', true, 'invalid message'); }); - it("should check obj exists in the chain [http]", async function() { + it('should check obj exists in the chain [http]', async function () { const con = new LotusClient(httpConnector); const tipSet = await con.chain.getTipSetByHeight(1); const isInChain = await con.chain.hasObj(tipSet.Cids[0]); - assert.strictEqual(isInChain, true, "CID doesn't exists in the chain blockstore"); + assert.strictEqual( + isInChain, + true, + "CID doesn't exists in the chain blockstore", + ); }); - it("should check obj exists in the chain [ws]", async function() { + it('should check obj exists in the chain [ws]', async function () { const provider = new LotusClient(wsConnector); const tipSet = await provider.chain.getTipSetByHeight(1); const isInChain = await provider.chain.hasObj(tipSet.Cids[0]); - assert.strictEqual(isInChain, true, "CID doesn't exists in the chain blockstore"); + assert.strictEqual( + isInChain, + true, + "CID doesn't exists in the chain blockstore", + ); + await provider.release(); + }); + + it('should get tipset [http]', async function () { + const provider = new LotusClient(httpConnector); + const tipSetKey = await provider.chain.getTipSetByHeight(10); + await provider.chain.getTipSet([tipSetKey.Cids[0]]); + }); + + it('should get tipset [ws]', async function () { + const provider = new LotusClient(wsConnector); + const tipSetKey = await provider.chain.getTipSetByHeight(10); + await provider.chain.getTipSet([tipSetKey.Cids[0]]); + await provider.release(); + }); + + it('should check tipset after height [http]', async function () { + const con = new LotusClient(httpConnector); + const tipSet = await con.chain.getTipSetAfterHeight(1); + assert.strictEqual( + typeof tipSet.Height === 'number', + true, + 'invalid tipset after height', + ); + }); + + it('should check tipset after height [ws]', async function () { + const provider = new LotusClient(wsConnector); + const tipSet = await provider.chain.getTipSetAfterHeight(1); + assert.strictEqual( + typeof tipSet.Height === 'number', + true, + 'invalid tipset after height', + ); + await provider.release(); + }); + + it('should get gas fee cap [http]', async function () { + const con = new LotusClient(httpConnector); + const messages = await con.state.listMessages({ + To: 't01000', + }); + const message = await con.chain.getMessage(messages[0]); + const cap = await con.chain.gasEstimateFeeCap(message, 0); + assert.strictEqual(typeof cap === 'string', true, 'invalid gas fee cap'); + }); + + it('should get gas fee cap [ws]', async function () { + const provider = new LotusClient(wsConnector); + const messages = await provider.state.listMessages({ + To: 't01000', + }); + const message = await provider.chain.getMessage(messages[0]); + const cap = await provider.chain.gasEstimateFeeCap(message, 0); + assert.strictEqual(typeof cap === 'string', true, 'invalid gas fee cap'); + await provider.release(); + }); + + it('should get estimate gas limit [http]', async function () { + const con = new LotusClient(httpConnector); + const messages = await con.state.listMessages({ + To: 't01000', + }); + let i = 0; + let message; + do { + message = await con.chain.getMessage(messages[i]); + i++; + } while (message.Method == 5); + const cap = await con.chain.gasEstimateGasLimit(message); + assert.strictEqual( + typeof cap === 'number', + true, + 'invalid estimate gas limit', + ); + }); + + it('should get estimate gas limit [ws]', async function () { + const provider = new LotusClient(wsConnector); + const messages = await provider.state.listMessages({ + To: 't01000', + }); + let i = 0; + let message; + do { + message = await provider.chain.getMessage(messages[i]); + i++; + } while (message.Method == 5); + const cap = await provider.chain.gasEstimateGasLimit(message); + assert.strictEqual( + typeof cap === 'number', + true, + 'invalid estimate gas limit', + ); await provider.release(); }); diff --git a/tests/src/test-client.ts b/tests/src/test-client.ts index 2dcf402..b6e615e 100644 --- a/tests/src/test-client.ts +++ b/tests/src/test-client.ts @@ -1,38 +1,47 @@ import { LotusWalletProvider, LotusClient } from '../../src'; -import assert from "assert"; +import assert from 'assert'; import { HttpJsonRpcConnector } from '../../src/connectors/HttpJsonRpcConnector'; -import { LOTUS_AUTH_TOKEN } from "../tools/testnet/credentials/credentials"; +import { LOTUS_AUTH_TOKEN } from '../tools/testnet/credentials/credentials'; import { WsJsonRpcConnector } from '../../src/connectors/WsJsonRpcConnector'; -const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); -const wsConnector = new WsJsonRpcConnector({ url: 'ws://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); +const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, +}); +const wsConnector = new WsJsonRpcConnector({ + url: 'ws://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, +}); const lotusClient = new LotusClient(httpConnector); const walletLotus = new LotusWalletProvider(lotusClient); -describe("Client tests", function() { - it("should import file", async function() { +describe('Client tests', function () { + it('should import file', async function () { const provider = new LotusClient(httpConnector); const result = await provider.client.import({ - Path: "/filecoin_miner/original-data.txt", + Path: '/filecoin_miner/original-data.txt', IsCAR: false, }); - const valid = typeof result.Root["/"] === 'string' && typeof result.ImportID === 'number'; + const valid = + typeof result.Root['/'] === 'string' && + typeof result.ImportID === 'number'; assert.strictEqual(valid, true, 'import file failed'); }); - it("should delete imported file", async function() { - const provider = new LotusClient(httpConnector); - const importResult = await provider.client.import({ - Path: "/filecoin_miner/original-data.txt", - IsCAR: false, - }); - await provider.client.removeImport(importResult.ImportID); - }); + // it('should delete imported file', async function () { + // const provider = new LotusClient(httpConnector); + // const importResult = await provider.client.import({ + // Path: '/filecoin_miner/original-data.txt', + // IsCAR: false, + // }); + // console.log(importResult); + // await provider.client.removeImport(importResult.ImportID); + // }); - it("should start deal", async function() { + it('should start deal', async function () { const provider = new LotusClient(httpConnector); const importResult = await provider.client.import({ - Path: "/filecoin_miner/original-data.txt", + Path: '/filecoin_miner/original-data.txt', IsCAR: false, }); const dealCid = await provider.client.startDeal({ @@ -45,13 +54,17 @@ describe("Client tests", function() { EpochPrice: '1001', MinBlocksDuration: 800, }); - assert.strictEqual(typeof dealCid["/"] === 'string', true, 'deal start failed'); + assert.strictEqual( + typeof dealCid['/'] === 'string', + true, + 'deal start failed', + ); }); - it("should get deal info", async function() { + it('should get deal info', async function () { const provider = new LotusClient(httpConnector); const importResult = await provider.client.import({ - Path: "/filecoin_miner/original-data.txt", + Path: '/filecoin_miner/original-data.txt', IsCAR: false, }); const dealCid = await provider.client.startDeal({ @@ -69,26 +82,26 @@ describe("Client tests", function() { assert.strictEqual(valid, true, 'invalid deal info'); }); - it("should list all deals", async function() { + it('should list all deals', async function () { const provider = new LotusClient(httpConnector); const deals = await provider.client.listDeals(); assert.strictEqual(Array.isArray(deals), true, 'invalid deals list'); }); - it("should verify if has local", async function() { + it('should verify if has local', async function () { const provider = new LotusClient(httpConnector); const importResult = await provider.client.import({ - Path: "/filecoin_miner/original-data.txt", + Path: '/filecoin_miner/original-data.txt', IsCAR: false, }); const hasLocal = await provider.client.hasLocal(importResult.Root); assert.strictEqual(hasLocal, true, 'invalid has local'); }); - it("should find data", async function() { + it('should find data', async function () { const provider = new LotusClient(httpConnector); const importResult = await provider.client.import({ - Path: "/filecoin_miner/original-data.txt", + Path: '/filecoin_miner/original-data.txt', IsCAR: false, }); await provider.client.startDeal({ @@ -102,18 +115,25 @@ describe("Client tests", function() { MinBlocksDuration: 800, }); const queryOffers = await provider.client.findData(importResult.Root); - const isValid = queryOffers.reduce((acc, offer, idx) => acc === false ? acc : offer.Root["/"] === importResult.Root["/"], true); + const isValid = queryOffers.reduce( + (acc, offer, idx) => + acc === false ? acc : offer.Root['/'] === importResult.Root['/'], + true, + ); assert.strictEqual(isValid, true, 'invalid found data'); }); - it("should get miner query offer", async function() { + it('should get miner query offer', async function () { const provider = new LotusClient(httpConnector); const importResult = await provider.client.import({ - Path: "/filecoin_miner/original-data.txt", + Path: '/filecoin_miner/original-data.txt', IsCAR: false, }); - const queryOffer = await provider.client.minerQueryOffer('t01000', importResult.Root); - const isValid = importResult.Root["/"] === queryOffer.Root["/"]; + const queryOffer = await provider.client.minerQueryOffer( + 't01000', + importResult.Root, + ); + const isValid = importResult.Root['/'] === queryOffer.Root['/']; assert.strictEqual(isValid, true, 'invalid miner query offer'); }); @@ -154,100 +174,135 @@ describe("Client tests", function() { // }); // }); - it("should perform query ask ", async function() { + it('should perform query ask ', async function () { const provider = new LotusClient(httpConnector); const minerInfo = await provider.state.minerInfo('t01000'); const queryAsk = await provider.client.queryAsk(minerInfo.PeerId, 't01000'); - const valid = typeof queryAsk.Price === 'string' && typeof queryAsk.Miner === 'string'; + const valid = + typeof queryAsk.Price === 'string' && typeof queryAsk.Miner === 'string'; assert.strictEqual(valid, true, 'failed query ask'); }); - it("should compute commP", async function() { + it('should generate CAR file', async function () { const provider = new LotusClient(httpConnector); - const { Root, Size } = await provider.client.calcCommP("/filecoin_miner/original-data.txt"); - assert.strictEqual(!!Root && !!Size, true, 'failed to compute commP'); + const car = await provider.client.genCar( + { + IsCAR: false, + Path: '/filecoin_miner/original-data.txt', + }, + '/filecoin_miner/car.txt', + ); }); - it("should generate CAR file", async function() { + it('should compute commP', async function () { const provider = new LotusClient(httpConnector); - const car = await provider.client.genCar({ - IsCAR: false, - Path: "/filecoin_miner/original-data.txt", - }, "/filecoin_miner/car.txt"); + const { Root, Size } = await provider.client.calcCommP( + '/filecoin_miner/car.txt', + ); + assert.strictEqual(!!Root && !!Size, true, 'failed to compute commP'); }); - it("should calculate deal size", async function() { + it('should calculate deal size', async function () { const provider = new LotusClient(httpConnector); const importResult = await provider.client.import({ - Path: "/filecoin_miner/original-data.txt", + Path: '/filecoin_miner/original-data.txt', IsCAR: false, }); - const { PayloadSize, PieceSize } = await provider.client.dealSize(importResult.Root); - const isValid = typeof PayloadSize === 'number' && typeof PieceSize === 'number'; + const { PayloadSize, PieceSize } = await provider.client.dealSize( + importResult.Root, + ); + const isValid = + typeof PayloadSize === 'number' && typeof PieceSize === 'number'; assert.strictEqual(isValid, true, 'invalid deal size'); }); - it("should get transfers status", async function() { + it('should get transfers status', async function () { const provider = new LotusClient(httpConnector); const transfers = await provider.client.listDataTransfers(); - assert.strictEqual(Array.isArray(transfers), true, 'invalid transfers status'); + assert.strictEqual( + Array.isArray(transfers), + true, + 'invalid transfers status', + ); }); - it("should list imports", async function() { + it('should list imports', async function () { const provider = new LotusClient(httpConnector); const importResult = await provider.client.import({ - Path: "/filecoin_miner/original-data.txt", + Path: '/filecoin_miner/original-data.txt', IsCAR: false, }); const imports = await provider.client.listImports(); - const isValid = imports.filter(importItem => ( - importItem.Root && importItem.Root['/'] === importResult.Root['/'] && importItem.Key === importResult.ImportID - )).length > 0; + const isValid = + imports.filter( + (importItem) => + importItem.Root && + importItem.Root['/'] === importResult.Root['/'] && + importItem.Key === importResult.ImportID, + ).length > 0; assert.strictEqual(isValid, true, 'invalid imports list'); }); - it("should get updated deals", function(done) { + it('should get updated deals', function (done) { this.timeout(10000); const con = new LotusClient(wsConnector); let isDone = false; walletLotus.getDefaultAddress().then((account: string) => { - con.client.import({ - Path: "/filecoin_miner/original-data.txt", - IsCAR: false, - }).then((importResult) => { - con.client.startDeal({ - Data: { - TransferType: 'graphsync', - Root: importResult.Root, - }, - Miner: 't01000', - Wallet: account, - EpochPrice: '1004', - MinBlocksDuration: 800, - }).then(() => { - con.client.getDealUpdates((dealInfo) => { - if (!isDone) { - isDone = true; - assert.strictEqual(typeof dealInfo.State === 'number', true, 'invalid updated deal info'); - con.release().then(() => { done() }); - } - }); + con.client + .import({ + Path: '/filecoin_miner/original-data.txt', + IsCAR: false, + }) + .then((importResult) => { + con.client + .startDeal({ + Data: { + TransferType: 'graphsync', + Root: importResult.Root, + }, + Miner: 't01000', + Wallet: account, + EpochPrice: '1004', + MinBlocksDuration: 800, + }) + .then(() => { + con.client.getDealUpdates((dealInfo) => { + if (!isDone) { + isDone = true; + assert.strictEqual( + typeof dealInfo.State === 'number', + true, + 'invalid updated deal info', + ); + con.release().then(() => { + done(); + }); + } + }); + }); }); - }); }); }); - it("should return deal status given a code [http]", async function() { + it('should return deal status given a code [http]', async function () { const provider = new LotusClient(httpConnector); const status = await provider.client.getDealStatus(0); - assert.strictEqual(status === 'StorageDealUnknown', true, 'wrong deal status given a code'); + assert.strictEqual( + status === 'StorageDealUnknown', + true, + 'wrong deal status given a code', + ); }); - it("should return deal status given a code [ws]", async function() { + it('should return deal status given a code [ws]', async function () { const provider = new LotusClient(wsConnector); const status = await provider.client.getDealStatus(0); - assert.strictEqual(status === 'StorageDealUnknown', true, 'wrong deal status given a code'); + assert.strictEqual( + status === 'StorageDealUnknown', + true, + 'wrong deal status given a code', + ); provider.release(); }); }); diff --git a/tests/src/test-multisig-lightwallet.ts b/tests/src/test-multisig-lightwallet.ts index 8a05802..01da291 100644 --- a/tests/src/test-multisig-lightwallet.ts +++ b/tests/src/test-multisig-lightwallet.ts @@ -1,16 +1,22 @@ -import assert from "assert"; +import assert from 'assert'; import BigNumber from 'bignumber.js'; -import { LOTUS_AUTH_TOKEN } from "../tools/testnet/credentials/credentials"; +import { LOTUS_AUTH_TOKEN } from '../tools/testnet/credentials/credentials'; import { LotusClient } from '../../src/providers/LotusClient'; import { HttpJsonRpcConnector } from '../../src/connectors/HttpJsonRpcConnector'; import { LotusWalletProvider } from '../../src/providers/wallet/LotusWalletProvider'; import { MnemonicWalletProvider } from '../../src/providers/wallet/MnemonicWalletProvider'; -import { LightWalletProvider } from "../../src"; +import { LightWalletProvider } from '../../src'; -const testMnemonic = 'equip will roof matter pink blind book anxiety banner elbow sun young'; +const testMnemonic = + 'equip will roof matter pink blind book anxiety banner elbow sun young'; -async function fundTestAddresses(source: string, destinations: string[], walletLotusHttp: LotusWalletProvider, con: LotusClient) { +async function fundTestAddresses( + source: string, + destinations: string[], + walletLotusHttp: LotusWalletProvider, + con: LotusClient, +) { for (let i = 0; i < destinations.length; i++) { const destination = destinations[i]; let message = await walletLotusHttp.createMessage({ @@ -19,20 +25,27 @@ async function fundTestAddresses(source: string, destinations: string[], walletL Value: new BigNumber(100000000000000), }); - console.log(`${source} -> ${destination}`) const signedMessage = await walletLotusHttp.signMessage(message); const msgCid = await walletLotusHttp.sendSignedMessage(signedMessage); const receiptInitialTransfer = await con.state.waitMsg(msgCid, 0); - console.log(receiptInitialTransfer); } } -describe("Multisig Wallets Lightwallet implementation", function () { - it("should provide accounts with initial funds", async function () { +describe('Multisig Wallets Lightwallet implementation', function () { + it('should provide accounts with initial funds', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const lightWalletHttp = new LightWalletProvider(con, () => { return 'testPwd' }, 'test'); + const lightWalletHttp = new LightWalletProvider( + con, + () => { + return 'testPwd'; + }, + 'test', + ); await lightWalletHttp.recoverLightWallet(testMnemonic, 'testPwd'); const walletLotusHttp = new LotusWalletProvider(con); @@ -40,14 +53,28 @@ describe("Multisig Wallets Lightwallet implementation", function () { await lightWalletHttp.newAddress(); const addresses = await lightWalletHttp.getAddresses(); - await fundTestAddresses(await walletLotusHttp.getDefaultAddress(), addresses, walletLotusHttp, con); + await fundTestAddresses( + await walletLotusHttp.getDefaultAddress(), + addresses, + walletLotusHttp, + con, + ); }); - it("should create multisig wallet and transfer funds [http]", async function () { + it('should create multisig wallet and transfer funds [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const lightWalletHttp = new LightWalletProvider(con, () => { return 'testPwd' }, 'test'); + const lightWalletHttp = new LightWalletProvider( + con, + () => { + return 'testPwd'; + }, + 'test', + ); await lightWalletHttp.recoverLightWallet(testMnemonic, 'testPwd'); await lightWalletHttp.newAddress(); @@ -55,100 +82,209 @@ describe("Multisig Wallets Lightwallet implementation", function () { const addresses = await lightWalletHttp.getAddresses(); const mnemonicAddress = await lightWalletHttp.newAddress(); - const multisigCid = await lightWalletHttp.msigCreate(2, addresses, 0, 0, '1000', addresses[0]); + const multisigCid = await lightWalletHttp.msigCreate( + 2, + addresses, + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await lightWalletHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await lightWalletHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initTransferCid = await lightWalletHttp.msigProposeTransfer(multisigAddress, mnemonicAddress, '1', addresses[0]); + const initTransferCid = await lightWalletHttp.msigProposeTransfer( + multisigAddress, + mnemonicAddress, + '1', + addresses[0], + ); const receiptTransferStart = await con.state.waitMsg(initTransferCid, 0); - console.log('receipt init transfer:', receiptTransferStart); const txnID = receiptTransferStart.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating transfer'); - const approveTransferCid = await lightWalletHttp.msigApproveTransferTxHash(multisigAddress, txnID, addresses[0], mnemonicAddress, '1', addresses[1]); - const receiptTransferApprove = await con.state.waitMsg(approveTransferCid, 0); - console.log('receipt approve transfer:', receiptTransferApprove); - - assert.strictEqual(receiptTransferApprove.ReturnDec.Applied, true, 'error approving transfer'); - - const balanceAfterTransfer = await lightWalletHttp.msigGetAvailableBalance(multisigAddress, []); - assert.strictEqual(balanceAfterTransfer, '999', 'wrong balance after approve transfer'); + const approveTransferCid = await lightWalletHttp.msigApproveTransferTxHash( + multisigAddress, + txnID, + addresses[0], + mnemonicAddress, + '1', + addresses[1], + ); + const receiptTransferApprove = await con.state.waitMsg( + approveTransferCid, + 0, + ); + + assert.strictEqual( + receiptTransferApprove.ReturnDec.Applied, + true, + 'error approving transfer', + ); + + const balanceAfterTransfer = await lightWalletHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); + assert.strictEqual( + balanceAfterTransfer, + '999', + 'wrong balance after approve transfer', + ); }); - it("should create multisig wallet and add signer [http]", async function () { + it('should create multisig wallet and add signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const lightWalletHttp = new LightWalletProvider(con, () => { return 'testPwd' }, 'test'); + const lightWalletHttp = new LightWalletProvider( + con, + () => { + return 'testPwd'; + }, + 'test', + ); await lightWalletHttp.recoverLightWallet(testMnemonic, 'testPwd'); await lightWalletHttp.newAddress(); await lightWalletHttp.newAddress(); const addresses = await lightWalletHttp.getAddresses(); - const multisigCid = await lightWalletHttp.msigCreate(2, [addresses[0], addresses[1]], 0, 0, '1000', addresses[0]); + const multisigCid = await lightWalletHttp.msigCreate( + 2, + [addresses[0], addresses[1]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await lightWalletHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await lightWalletHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initAddProposeCid = await lightWalletHttp.msigProposeAddSigner(multisigAddress, addresses[0], addresses[2], true); + const initAddProposeCid = await lightWalletHttp.msigProposeAddSigner( + multisigAddress, + addresses[0], + addresses[2], + true, + ); const receiptAddProposeCid = await con.state.waitMsg(initAddProposeCid, 0); - console.log('receipt init add signer:', receiptAddProposeCid); const txnID = receiptAddProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating add proposal'); - const approveAddCid = await lightWalletHttp.msigApproveAddSigner(multisigAddress, addresses[1], txnID, addresses[0], addresses[2], true); + const approveAddCid = await lightWalletHttp.msigApproveAddSigner( + multisigAddress, + addresses[1], + txnID, + addresses[0], + addresses[2], + true, + ); const receiptAddApprove = await con.state.waitMsg(approveAddCid, 0); - console.log('receipt approve add signer:', receiptAddApprove); - assert.strictEqual(receiptAddApprove.ReturnDec.Applied, true, 'error approving add proposal'); + assert.strictEqual( + receiptAddApprove.ReturnDec.Applied, + true, + 'error approving add proposal', + ); }); - it("should create multisig wallet and swap signer [http]", async function () { + it('should create multisig wallet and swap signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const lightWalletHttp = new LightWalletProvider(con, () => { return 'testPwd' }, 'test'); + const lightWalletHttp = new LightWalletProvider( + con, + () => { + return 'testPwd'; + }, + 'test', + ); await lightWalletHttp.recoverLightWallet(testMnemonic, 'testPwd'); await lightWalletHttp.newAddress(); await lightWalletHttp.newAddress(); const addresses = await lightWalletHttp.getAddresses(); - const multisigCid = await lightWalletHttp.msigCreate(2, [addresses[0], addresses[1]], 0, 0, '1000', addresses[0]); + const multisigCid = await lightWalletHttp.msigCreate( + 2, + [addresses[0], addresses[1]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await lightWalletHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await lightWalletHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initSwapProposeCid = await lightWalletHttp.msigProposeSwapSigner(multisigAddress, addresses[0], addresses[1], addresses[2]); - const receiptSwapProposeCid = await con.state.waitMsg(initSwapProposeCid, 0); - console.log('receipt init swap signer:', receiptSwapProposeCid); + const initSwapProposeCid = await lightWalletHttp.msigProposeSwapSigner( + multisigAddress, + addresses[0], + addresses[1], + addresses[2], + ); + const receiptSwapProposeCid = await con.state.waitMsg( + initSwapProposeCid, + 0, + ); const txnID = receiptSwapProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating swap proposal'); - const approveSwapCid = await lightWalletHttp.msigApproveSwapSigner(multisigAddress, addresses[1], txnID, addresses[0], addresses[1], addresses[2] ); + const approveSwapCid = await lightWalletHttp.msigApproveSwapSigner( + multisigAddress, + addresses[1], + txnID, + addresses[0], + addresses[1], + addresses[2], + ); const receiptSwapApprove = await con.state.waitMsg(approveSwapCid, 0); - console.log('receipt approve swap signer:', receiptSwapApprove); - assert.strictEqual(receiptSwapApprove.ReturnDec.Applied, true, 'error approving swap proposal'); + assert.strictEqual( + receiptSwapApprove.ReturnDec.Applied, + true, + 'error approving swap proposal', + ); }); - it("should create multisig wallet and cancel transfer funds [http]", async function () { + it('should create multisig wallet and cancel transfer funds [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const lightWalletHttp = new LightWalletProvider(con, () => { return 'testPwd' }, 'test'); + const lightWalletHttp = new LightWalletProvider( + con, + () => { + return 'testPwd'; + }, + 'test', + ); await lightWalletHttp.recoverLightWallet(testMnemonic, 'testPwd'); await lightWalletHttp.newAddress(); @@ -156,153 +292,309 @@ describe("Multisig Wallets Lightwallet implementation", function () { const addresses = await lightWalletHttp.getAddresses(); const mnemonicAddress = await lightWalletHttp.newAddress(); - const multisigCid = await lightWalletHttp.msigCreate(2, addresses, 0, 0, '1000', addresses[0]); + const multisigCid = await lightWalletHttp.msigCreate( + 2, + addresses, + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await lightWalletHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await lightWalletHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initTransferCid = await lightWalletHttp.msigProposeTransfer(multisigAddress, mnemonicAddress, '1', addresses[0]); + const initTransferCid = await lightWalletHttp.msigProposeTransfer( + multisigAddress, + mnemonicAddress, + '1', + addresses[0], + ); const receiptTransferStart = await con.state.waitMsg(initTransferCid, 0); - console.log('receipt init transfer:', receiptTransferStart); const txnID = receiptTransferStart.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating transfer'); - const cancelTransferCid = await lightWalletHttp.msigCancelTransfer(multisigAddress, addresses[0], txnID, mnemonicAddress, '1'); + const cancelTransferCid = await lightWalletHttp.msigCancelTransfer( + multisigAddress, + addresses[0], + txnID, + mnemonicAddress, + '1', + ); const receiptTransferCancel = await con.state.waitMsg(cancelTransferCid, 0); - console.log('receipt cancel transfer:', receiptTransferCancel); - assert.strictEqual(receiptTransferCancel.Receipt.ExitCode, 0, 'error canceling transfer'); + assert.strictEqual( + receiptTransferCancel.Receipt.ExitCode, + 0, + 'error canceling transfer', + ); }); - it("should create multisig wallet cancel add signer [http]", async function () { + it('should create multisig wallet cancel add signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const lightWalletHttp = new LightWalletProvider(con, () => { return 'testPwd' }, 'test'); + const lightWalletHttp = new LightWalletProvider( + con, + () => { + return 'testPwd'; + }, + 'test', + ); await lightWalletHttp.recoverLightWallet(testMnemonic, 'testPwd'); await lightWalletHttp.newAddress(); await lightWalletHttp.newAddress(); const addresses = await lightWalletHttp.getAddresses(); - const multisigCid = await lightWalletHttp.msigCreate(2, [addresses[0], addresses[1]], 0, 0, '1000', addresses[0]); + const multisigCid = await lightWalletHttp.msigCreate( + 2, + [addresses[0], addresses[1]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await lightWalletHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await lightWalletHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initAddProposeCid = await lightWalletHttp.msigProposeAddSigner(multisigAddress, addresses[0], addresses[2], true); + const initAddProposeCid = await lightWalletHttp.msigProposeAddSigner( + multisigAddress, + addresses[0], + addresses[2], + true, + ); const receiptAddProposeCid = await con.state.waitMsg(initAddProposeCid, 0); - console.log('receipt init add signer:', receiptAddProposeCid); const txnID = receiptAddProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating add proposal'); - const cancelAddCid = await lightWalletHttp.msigCancelAddSigner(multisigAddress, addresses[0], txnID, addresses[2], true); + const cancelAddCid = await lightWalletHttp.msigCancelAddSigner( + multisigAddress, + addresses[0], + txnID, + addresses[2], + true, + ); const receiptAddCancel = await con.state.waitMsg(cancelAddCid, 0); - console.log('receipt cancel add signer:', receiptAddCancel); - assert.strictEqual(receiptAddCancel.Receipt.ExitCode, 0, 'error canceling add signer'); + assert.strictEqual( + receiptAddCancel.Receipt.ExitCode, + 0, + 'error canceling add signer', + ); }); - it("should create multisig wallet and cancel swap signer [http]", async function () { + it('should create multisig wallet and cancel swap signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const lightWalletHttp = new LightWalletProvider(con, () => { return 'testPwd' }, 'test'); + const lightWalletHttp = new LightWalletProvider( + con, + () => { + return 'testPwd'; + }, + 'test', + ); await lightWalletHttp.recoverLightWallet(testMnemonic, 'testPwd'); await lightWalletHttp.newAddress(); await lightWalletHttp.newAddress(); const addresses = await lightWalletHttp.getAddresses(); - const multisigCid = await lightWalletHttp.msigCreate(2, [addresses[0], addresses[1]], 0, 0, '1000', addresses[0]); + const multisigCid = await lightWalletHttp.msigCreate( + 2, + [addresses[0], addresses[1]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await lightWalletHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await lightWalletHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initSwapProposeCid = await lightWalletHttp.msigProposeSwapSigner(multisigAddress, addresses[0], addresses[1], addresses[2]); - const receiptSwapProposeCid = await con.state.waitMsg(initSwapProposeCid, 0); - console.log('receipt init swap signer:', receiptSwapProposeCid); + const initSwapProposeCid = await lightWalletHttp.msigProposeSwapSigner( + multisigAddress, + addresses[0], + addresses[1], + addresses[2], + ); + const receiptSwapProposeCid = await con.state.waitMsg( + initSwapProposeCid, + 0, + ); const txnID = receiptSwapProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating swap proposal'); - const cancelSwapCid = await lightWalletHttp.msigCancelSwapSigner(multisigAddress, addresses[0], txnID, addresses[1], addresses[2] ); + const cancelSwapCid = await lightWalletHttp.msigCancelSwapSigner( + multisigAddress, + addresses[0], + txnID, + addresses[1], + addresses[2], + ); const receiptSwapCancel = await con.state.waitMsg(cancelSwapCid, 0); - console.log('receipt cancel swap signer:', receiptSwapCancel); - assert.strictEqual(receiptSwapCancel.Receipt.ExitCode, 0, 'error canceling swap proposal'); + assert.strictEqual( + receiptSwapCancel.Receipt.ExitCode, + 0, + 'error canceling swap proposal', + ); }); - it("should create multisig wallet and remove signer [http]", async function () { + it('should create multisig wallet and remove signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const lightWalletHttp = new LightWalletProvider(con, () => { return 'testPwd' }, 'test'); + const lightWalletHttp = new LightWalletProvider( + con, + () => { + return 'testPwd'; + }, + 'test', + ); await lightWalletHttp.recoverLightWallet(testMnemonic, 'testPwd'); await lightWalletHttp.newAddress(); await lightWalletHttp.newAddress(); const addresses = await lightWalletHttp.getAddresses(); - const multisigCid = await lightWalletHttp.msigCreate(2, [addresses[0], addresses[1], addresses[2]], 0, 0, '1000', addresses[0]); + const multisigCid = await lightWalletHttp.msigCreate( + 2, + [addresses[0], addresses[1], addresses[2]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await lightWalletHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await lightWalletHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initRemoveProposeCid = await lightWalletHttp.msigProposeRemoveSigner(multisigAddress, addresses[0], addresses[2], true); - const receiptRemoveProposeCid = await con.state.waitMsg(initRemoveProposeCid, 0); - console.log('receipt init remove signer:', receiptRemoveProposeCid); + const initRemoveProposeCid = await lightWalletHttp.msigProposeRemoveSigner( + multisigAddress, + addresses[0], + addresses[2], + true, + ); + const receiptRemoveProposeCid = await con.state.waitMsg( + initRemoveProposeCid, + 0, + ); const txnID = receiptRemoveProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating add proposal'); - const approveRemoveCid = await lightWalletHttp.msigApproveRemoveSigner(multisigAddress, addresses[1], txnID, addresses[0], addresses[2], true); + const approveRemoveCid = await lightWalletHttp.msigApproveRemoveSigner( + multisigAddress, + addresses[1], + txnID, + addresses[0], + addresses[2], + true, + ); const receiptRemoveApprove = await con.state.waitMsg(approveRemoveCid, 0); - console.log('receipt approve remove signer:', receiptRemoveApprove); - assert.strictEqual(receiptRemoveApprove.ReturnDec.Applied, true, 'error approving add proposal'); + assert.strictEqual( + receiptRemoveApprove.ReturnDec.Applied, + true, + 'error approving add proposal', + ); }); - it("should create multisig wallet and remove signer [http]", async function () { + it('should create multisig wallet and remove signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const lightWalletHttp = new LightWalletProvider(con, () => { return 'testPwd' }, 'test'); + const lightWalletHttp = new LightWalletProvider( + con, + () => { + return 'testPwd'; + }, + 'test', + ); await lightWalletHttp.recoverLightWallet(testMnemonic, 'testPwd'); await lightWalletHttp.newAddress(); await lightWalletHttp.newAddress(); const addresses = await lightWalletHttp.getAddresses(); - const multisigCid = await lightWalletHttp.msigCreate(2, [addresses[0], addresses[1], addresses[2]], 0, 0, '1000', addresses[0]); + const multisigCid = await lightWalletHttp.msigCreate( + 2, + [addresses[0], addresses[1], addresses[2]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await lightWalletHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await lightWalletHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initRemoveProposeCid = await lightWalletHttp.msigProposeRemoveSigner(multisigAddress, addresses[0], addresses[2], true); - const receiptRemoveProposeCid = await con.state.waitMsg(initRemoveProposeCid, 0); - console.log('receipt init remove signer:', receiptRemoveProposeCid); + const initRemoveProposeCid = await lightWalletHttp.msigProposeRemoveSigner( + multisigAddress, + addresses[0], + addresses[2], + true, + ); + const receiptRemoveProposeCid = await con.state.waitMsg( + initRemoveProposeCid, + 0, + ); const txnID = receiptRemoveProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating add proposal'); - const cancelRemoveCid = await lightWalletHttp.msigCancelRemoveSigner(multisigAddress, addresses[0], txnID, addresses[2], true); + const cancelRemoveCid = await lightWalletHttp.msigCancelRemoveSigner( + multisigAddress, + addresses[0], + txnID, + addresses[2], + true, + ); const receiptRemoveCancel = await con.state.waitMsg(cancelRemoveCid, 0); - console.log('receipt approve remove signer:', receiptRemoveCancel); - assert.strictEqual(receiptRemoveCancel.Receipt.ExitCode, 0, 'error canceling add proposal'); + assert.strictEqual( + receiptRemoveCancel.Receipt.ExitCode, + 0, + 'error canceling add proposal', + ); }); }); diff --git a/tests/src/test-multisig-lotus.ts b/tests/src/test-multisig-lotus.ts index b78330a..cb5502a 100644 --- a/tests/src/test-multisig-lotus.ts +++ b/tests/src/test-multisig-lotus.ts @@ -1,19 +1,23 @@ -import assert from "assert"; +import assert from 'assert'; import BigNumber from 'bignumber.js'; -import { LOTUS_AUTH_TOKEN } from "../tools/testnet/credentials/credentials"; +import { LOTUS_AUTH_TOKEN } from '../tools/testnet/credentials/credentials'; import { LotusClient } from '../../src/providers/LotusClient'; import { HttpJsonRpcConnector } from '../../src/connectors/HttpJsonRpcConnector'; import { LotusWalletProvider } from '../../src/providers/wallet/LotusWalletProvider'; import { MnemonicWalletProvider } from '../../src/providers/wallet/MnemonicWalletProvider'; -const testMnemonic = 'equip will roof matter pink blind book anxiety banner elbow sun young'; +const testMnemonic = + 'equip will roof matter pink blind book anxiety banner elbow sun young'; function sleep(ms: any) { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); } -async function extractAddressesWithFunds(addresses: string[], wallet: LotusWalletProvider): Promise<{ blsAddresses: string[], secpAddreses: string[] }> { +async function extractAddressesWithFunds( + addresses: string[], + wallet: LotusWalletProvider, +): Promise<{ blsAddresses: string[]; secpAddreses: string[] }> { let blsAddresses: string[] = []; let secpAddreses: string[] = []; @@ -26,65 +30,121 @@ async function extractAddressesWithFunds(addresses: string[], wallet: LotusWalle if (balance.gt(new BigNumber(0)) && address.startsWith('t1')) { secpAddreses.push(address); } - }; + } return { blsAddresses, secpAddreses }; } -describe("Multisig Wallets Lotus implementation", function () { - it("should create multisig wallet and transfer funds [http]", async function () { +describe('Multisig Wallets Lotus implementation', function () { + it('should create multisig wallet and transfer funds [http]', async function () { this.timeout(40000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, ''); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + '', + ); const walletLotusHttp = new LotusWalletProvider(con); const addresses = await walletLotusHttp.getAddresses(); const defaultAccount = await walletLotusHttp.getDefaultAddress(); - const { blsAddresses, secpAddreses } = await extractAddressesWithFunds (addresses, walletLotusHttp); - const t3address = blsAddresses [0] + const { blsAddresses, secpAddreses } = await extractAddressesWithFunds( + addresses, + walletLotusHttp, + ); + const t3address = blsAddresses[0]; const t11address = secpAddreses[1]; const t12address = secpAddreses[0]; const mnemonicAddress = await mnemonicWalletProvider.getDefaultAddress(); - const multisigCid = await walletLotusHttp.msigCreate(2, addresses, 0, 0, '1000', defaultAccount); + const multisigCid = await walletLotusHttp.msigCreate( + 2, + addresses, + 0, + 0, + '1000', + defaultAccount, + ); const receipt = await con.state.waitMsg(multisigCid, 0); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await walletLotusHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await walletLotusHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); const initialDefaultWallet = await walletLotusHttp.getDefaultAddress(); await walletLotusHttp.setDefaultAddress(t3address); - const initTransferCid = await walletLotusHttp.msigProposeTransfer(multisigAddress, mnemonicAddress, '1', t3address); + const initTransferCid = await walletLotusHttp.msigProposeTransfer( + multisigAddress, + mnemonicAddress, + '1', + t3address, + ); const receiptTransferStart = await con.state.waitMsg(initTransferCid, 0); const txnID = receiptTransferStart.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating transfer'); await walletLotusHttp.setDefaultAddress(t11address); - const approveTransferCid = await walletLotusHttp.msigApproveTransferTxHash(multisigAddress, txnID, t3address, mnemonicAddress, '1', t11address); - const receiptTransferApprove = await con.state.waitMsg(approveTransferCid, 0); - assert.strictEqual(receiptTransferApprove.ReturnDec.Applied, true, 'error approving transfer'); - - const balanceAfterTransfer = await walletLotusHttp.msigGetAvailableBalance(multisigAddress, []); - assert.strictEqual(balanceAfterTransfer, '999', 'wrong balance after approve transfer'); + const approveTransferCid = await walletLotusHttp.msigApproveTransferTxHash( + multisigAddress, + txnID, + t3address, + mnemonicAddress, + '1', + t11address, + ); + const receiptTransferApprove = await con.state.waitMsg( + approveTransferCid, + 0, + ); + assert.strictEqual( + receiptTransferApprove.ReturnDec.Applied, + true, + 'error approving transfer', + ); + + const balanceAfterTransfer = await walletLotusHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); + assert.strictEqual( + balanceAfterTransfer, + '999', + 'wrong balance after approve transfer', + ); await walletLotusHttp.setDefaultAddress(initialDefaultWallet); }); - it("should create multisig wallet and add signer [http]", async function () { + it('should create multisig wallet and add signer [http]', async function () { this.timeout(40000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, ''); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + '', + ); const walletLotusHttp = new LotusWalletProvider(con); const addresses = await walletLotusHttp.getAddresses(); - const { blsAddresses, secpAddreses } = await extractAddressesWithFunds (addresses, walletLotusHttp); + const { blsAddresses, secpAddreses } = await extractAddressesWithFunds( + addresses, + walletLotusHttp, + ); const defaultAccount = await walletLotusHttp.getDefaultAddress(); @@ -94,114 +154,227 @@ describe("Multisig Wallets Lotus implementation", function () { const mnemonicAddress = await mnemonicWalletProvider.getDefaultAddress(); - const multisigCid = await walletLotusHttp.msigCreate(2, [ t3address, t11address ], 0, 0, '1000', defaultAccount); + const multisigCid = await walletLotusHttp.msigCreate( + 2, + [t3address, t11address], + 0, + 0, + '1000', + defaultAccount, + ); const receipt = await con.state.waitMsg(multisigCid, 0); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await walletLotusHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await walletLotusHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); const initialDefaultWallet = await walletLotusHttp.getDefaultAddress(); await walletLotusHttp.setDefaultAddress(t3address); - const initAddProposeCid = await walletLotusHttp.msigProposeAddSigner(multisigAddress,t3address,t12address,false); + const initAddProposeCid = await walletLotusHttp.msigProposeAddSigner( + multisigAddress, + t3address, + t12address, + false, + ); const receiptAddStart = await con.state.waitMsg(initAddProposeCid, 0); const txnID = receiptAddStart.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating add proposal'); await walletLotusHttp.setDefaultAddress(t11address); - const approveAddCid = await walletLotusHttp.msigApproveAddSigner(multisigAddress, t11address, txnID, t3address, t12address, false); + const approveAddCid = await walletLotusHttp.msigApproveAddSigner( + multisigAddress, + t11address, + txnID, + t3address, + t12address, + false, + ); const receiptAddApprove = await con.state.waitMsg(approveAddCid, 0); - assert.strictEqual(receiptAddApprove.ReturnDec.Applied, true, 'error approving add proposal'); + assert.strictEqual( + receiptAddApprove.ReturnDec.Applied, + true, + 'error approving add proposal', + ); await walletLotusHttp.setDefaultAddress(initialDefaultWallet); }); - it("should create multisig wallet and swap signer [http]", async function () { + it('should create multisig wallet and swap signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, ''); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + '', + ); const walletLotusHttp = new LotusWalletProvider(con); const addresses = await walletLotusHttp.getAddresses(); const defaultAccount = await walletLotusHttp.getDefaultAddress(); - const { blsAddresses, secpAddreses } = await extractAddressesWithFunds (addresses, walletLotusHttp); - const t3address = blsAddresses [0] + const { blsAddresses, secpAddreses } = await extractAddressesWithFunds( + addresses, + walletLotusHttp, + ); + const t3address = blsAddresses[0]; const t11address = secpAddreses[1]; const t12address = secpAddreses[0]; const mnemonicAddress = await mnemonicWalletProvider.getDefaultAddress(); - const multisigCid = await walletLotusHttp.msigCreate(2, [t3address, t11address], 0, 0, '1000', defaultAccount); + const multisigCid = await walletLotusHttp.msigCreate( + 2, + [t3address, t11address], + 0, + 0, + '1000', + defaultAccount, + ); const receipt = await con.state.waitMsg(multisigCid, 0); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await walletLotusHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await walletLotusHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); const initialDefaultWallet = await walletLotusHttp.getDefaultAddress(); await walletLotusHttp.setDefaultAddress(t3address); - const iniSwapProposeCid = await walletLotusHttp.msigProposeSwapSigner(multisigAddress, t3address, t11address, t12address); + const iniSwapProposeCid = await walletLotusHttp.msigProposeSwapSigner( + multisigAddress, + t3address, + t11address, + t12address, + ); const receiptProposeStart = await con.state.waitMsg(iniSwapProposeCid, 0); const txnID = receiptProposeStart.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating swap proposal'); await walletLotusHttp.setDefaultAddress(t11address); - const approveSwapCid = await walletLotusHttp.msigApproveSwapSigner(multisigAddress, t11address, txnID, t3address, t11address, t12address); + const approveSwapCid = await walletLotusHttp.msigApproveSwapSigner( + multisigAddress, + t11address, + txnID, + t3address, + t11address, + t12address, + ); const receiptSwapApprove = await con.state.waitMsg(approveSwapCid, 0); - assert.strictEqual(receiptSwapApprove.ReturnDec.Applied, true, 'error approving add proposal'); + assert.strictEqual( + receiptSwapApprove.ReturnDec.Applied, + true, + 'error approving add proposal', + ); await walletLotusHttp.setDefaultAddress(t3address); - const initTransferCid = await walletLotusHttp.msigProposeTransfer(multisigAddress, mnemonicAddress, '1', t3address); + const initTransferCid = await walletLotusHttp.msigProposeTransfer( + multisigAddress, + mnemonicAddress, + '1', + t3address, + ); const receiptTransferStart = await con.state.waitMsg(initTransferCid, 0); const txnIDTransfer = receiptTransferStart.ReturnDec.TxnID; - await walletLotusHttp.setDefaultAddress(t12address); - const approveTransferCid = await walletLotusHttp.msigApproveTransferTxHash(multisigAddress, txnIDTransfer, t3address, mnemonicAddress, '1', t12address); - const receiptTransferApprove = await con.state.waitMsg(approveTransferCid, 0); - assert.strictEqual(receiptTransferApprove.ReturnDec.Applied, true, 'error approving transfer'); - - const balanceAfterTransfer = await walletLotusHttp.msigGetAvailableBalance(multisigAddress, []); - assert.strictEqual(balanceAfterTransfer, '999', 'wrong balance after approve transfer'); + const approveTransferCid = await walletLotusHttp.msigApproveTransferTxHash( + multisigAddress, + txnIDTransfer, + t3address, + mnemonicAddress, + '1', + t12address, + ); + const receiptTransferApprove = await con.state.waitMsg( + approveTransferCid, + 0, + ); + assert.strictEqual( + receiptTransferApprove.ReturnDec.Applied, + true, + 'error approving transfer', + ); + + const balanceAfterTransfer = await walletLotusHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); + assert.strictEqual( + balanceAfterTransfer, + '999', + 'wrong balance after approve transfer', + ); await walletLotusHttp.setDefaultAddress(initialDefaultWallet); }); - it("should create multisig wallet and remove signer [http]", async function () { + it('should create multisig wallet and remove signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, ''); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + '', + ); const walletLotusHttp = new LotusWalletProvider(con); const addresses = await walletLotusHttp.getAddresses(); - const { blsAddresses, secpAddreses } = await extractAddressesWithFunds(addresses, walletLotusHttp); - const t3address = blsAddresses[0] + const { blsAddresses, secpAddreses } = await extractAddressesWithFunds( + addresses, + walletLotusHttp, + ); + const t3address = blsAddresses[0]; const t11address = secpAddreses[1]; const t12address = secpAddreses[0]; - - const multisigCid = await walletLotusHttp.msigCreate(2, [t3address, t11address, t12address], 0, 0, '1000', t11address); + const multisigCid = await walletLotusHttp.msigCreate( + 2, + [t3address, t11address, t12address], + 0, + 0, + '1000', + t11address, + ); const receipt = await con.state.waitMsg(multisigCid, 0); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await walletLotusHttp.msigGetAvailableBalance(multisigAddress, []); + const balance = await walletLotusHttp.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initRemoveProposeCid = await walletLotusHttp.msigProposeRemoveSigner(multisigAddress, t11address, t3address, true); - const receiptRemoveProposeCid = await con.state.waitMsg(initRemoveProposeCid, 0); + const initRemoveProposeCid = await walletLotusHttp.msigProposeRemoveSigner( + multisigAddress, + t11address, + t3address, + true, + ); + const receiptRemoveProposeCid = await con.state.waitMsg( + initRemoveProposeCid, + 0, + ); const txnID = receiptRemoveProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating remove proposal'); }); - }); diff --git a/tests/src/test-multisig-mnemonic.ts b/tests/src/test-multisig-mnemonic.ts index be80f2d..642f0aa 100644 --- a/tests/src/test-multisig-mnemonic.ts +++ b/tests/src/test-multisig-mnemonic.ts @@ -1,15 +1,21 @@ -import assert from "assert"; +import assert from 'assert'; import BigNumber from 'bignumber.js'; -import { LOTUS_AUTH_TOKEN } from "../tools/testnet/credentials/credentials"; +import { LOTUS_AUTH_TOKEN } from '../tools/testnet/credentials/credentials'; import { LotusClient } from '../../src/providers/LotusClient'; import { HttpJsonRpcConnector } from '../../src/connectors/HttpJsonRpcConnector'; import { LotusWalletProvider } from '../../src/providers/wallet/LotusWalletProvider'; import { MnemonicWalletProvider } from '../../src/providers/wallet/MnemonicWalletProvider'; -const testMnemonic = 'equip will roof matter pink blind book anxiety banner elbow sun young'; +const testMnemonic = + 'equip will roof matter pink blind book anxiety banner elbow sun young'; -async function fundTestAddresses(source: string, destinations: string[], walletLotusHttp: LotusWalletProvider, con: LotusClient) { +async function fundTestAddresses( + source: string, + destinations: string[], + walletLotusHttp: LotusWalletProvider, + con: LotusClient, +) { for (let i = 0; i < destinations.length; i++) { const destination = destinations[i]; let message = await walletLotusHttp.createMessage({ @@ -17,282 +23,549 @@ async function fundTestAddresses(source: string, destinations: string[], walletL To: destination, Value: new BigNumber(100000000000000), }); - - console.log(`${source} -> ${destination}`) const signedMessage = await walletLotusHttp.signMessage(message); const msgCid = await walletLotusHttp.sendSignedMessage(signedMessage); const receiptInitialTransfer = await con.state.waitMsg(msgCid, 0); - console.log(receiptInitialTransfer); } } -describe("Multisig Wallets Mnemonic implementation", function () { - it("should provide accounts with initial funds", async function () { +describe('Multisig Wallets Mnemonic implementation', function () { + it('should provide accounts with initial funds', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, ''); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + '', + ); const walletLotusHttp = new LotusWalletProvider(con); await mnemonicWalletProvider.newAddress(); await mnemonicWalletProvider.newAddress(); const addresses = await mnemonicWalletProvider.getAddresses(); - await fundTestAddresses(await walletLotusHttp.getDefaultAddress(), addresses, walletLotusHttp, con); + await fundTestAddresses( + await walletLotusHttp.getDefaultAddress(), + addresses, + walletLotusHttp, + con, + ); }); - it("should create multisig wallet and transfer funds [http]", async function () { + it('should create multisig wallet and transfer funds [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, ''); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + '', + ); await mnemonicWalletProvider.newAddress(); await mnemonicWalletProvider.newAddress(); const addresses = await mnemonicWalletProvider.getAddresses(); const mnemonicAddress = await mnemonicWalletProvider.newAddress(); - const multisigCid = await mnemonicWalletProvider.msigCreate(2, addresses, 0, 0, '1000', addresses[0]); + const multisigCid = await mnemonicWalletProvider.msigCreate( + 2, + addresses, + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await mnemonicWalletProvider.msigGetAvailableBalance(multisigAddress, []); + const balance = await mnemonicWalletProvider.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initTransferCid = await mnemonicWalletProvider.msigProposeTransfer(multisigAddress, mnemonicAddress, '1', addresses[0]); + const initTransferCid = await mnemonicWalletProvider.msigProposeTransfer( + multisigAddress, + mnemonicAddress, + '1', + addresses[0], + ); const receiptTransferStart = await con.state.waitMsg(initTransferCid, 0); - console.log('receipt init transfer:', receiptTransferStart); const txnID = receiptTransferStart.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating transfer'); - const approveTransferCid = await mnemonicWalletProvider.msigApproveTransferTxHash(multisigAddress, txnID, addresses[0], mnemonicAddress, '1', addresses[1]); - const receiptTransferApprove = await con.state.waitMsg(approveTransferCid, 0); - console.log('receipt approve transfer:', receiptTransferApprove); - - assert.strictEqual(receiptTransferApprove.ReturnDec.Applied, true, 'error approving transfer'); - - const balanceAfterTransfer = await mnemonicWalletProvider.msigGetAvailableBalance(multisigAddress, []); - assert.strictEqual(balanceAfterTransfer, '999', 'wrong balance after approve transfer'); + const approveTransferCid = await mnemonicWalletProvider.msigApproveTransferTxHash( + multisigAddress, + txnID, + addresses[0], + mnemonicAddress, + '1', + addresses[1], + ); + const receiptTransferApprove = await con.state.waitMsg( + approveTransferCid, + 0, + ); + + assert.strictEqual( + receiptTransferApprove.ReturnDec.Applied, + true, + 'error approving transfer', + ); + + const balanceAfterTransfer = await mnemonicWalletProvider.msigGetAvailableBalance( + multisigAddress, + [], + ); + assert.strictEqual( + balanceAfterTransfer, + '999', + 'wrong balance after approve transfer', + ); }); - it("should create multisig wallet and add signer [http]", async function () { + it('should create multisig wallet and add signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, 'test'); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + 'test', + ); await mnemonicWalletProvider.newAddress(); await mnemonicWalletProvider.newAddress(); const addresses = await mnemonicWalletProvider.getAddresses(); - const multisigCid = await mnemonicWalletProvider.msigCreate(2, [addresses[0], addresses[1]], 0, 0, '1000', addresses[0]); + const multisigCid = await mnemonicWalletProvider.msigCreate( + 2, + [addresses[0], addresses[1]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await mnemonicWalletProvider.msigGetAvailableBalance(multisigAddress, []); + const balance = await mnemonicWalletProvider.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initAddProposeCid = await mnemonicWalletProvider.msigProposeAddSigner(multisigAddress, addresses[0], addresses[2], true); + const initAddProposeCid = await mnemonicWalletProvider.msigProposeAddSigner( + multisigAddress, + addresses[0], + addresses[2], + true, + ); const receiptAddProposeCid = await con.state.waitMsg(initAddProposeCid, 0); - console.log('receipt init add signer:', receiptAddProposeCid); const txnID = receiptAddProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating add proposal'); - const approveAddCid = await mnemonicWalletProvider.msigApproveAddSigner(multisigAddress, addresses[1], txnID, addresses[0], addresses[2], true); + const approveAddCid = await mnemonicWalletProvider.msigApproveAddSigner( + multisigAddress, + addresses[1], + txnID, + addresses[0], + addresses[2], + true, + ); const receiptAddApprove = await con.state.waitMsg(approveAddCid, 0); - console.log('receipt approve add signer:', receiptAddApprove); - assert.strictEqual(receiptAddApprove.ReturnDec.Applied, true, 'error approving add proposal'); + assert.strictEqual( + receiptAddApprove.ReturnDec.Applied, + true, + 'error approving add proposal', + ); }); - it("should create multisig wallet and swap signer [http]", async function () { + it('should create multisig wallet and swap signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, 'test'); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + 'test', + ); await mnemonicWalletProvider.newAddress(); await mnemonicWalletProvider.newAddress(); const addresses = await mnemonicWalletProvider.getAddresses(); - const multisigCid = await mnemonicWalletProvider.msigCreate(2, [addresses[0], addresses[1]], 0, 0, '1000', addresses[0]); + const multisigCid = await mnemonicWalletProvider.msigCreate( + 2, + [addresses[0], addresses[1]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await mnemonicWalletProvider.msigGetAvailableBalance(multisigAddress, []); + const balance = await mnemonicWalletProvider.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initSwapProposeCid = await mnemonicWalletProvider.msigProposeSwapSigner(multisigAddress, addresses[0], addresses[1], addresses[2]); - const receiptSwapProposeCid = await con.state.waitMsg(initSwapProposeCid, 0); - console.log('receipt init swap signer:', receiptSwapProposeCid); + const initSwapProposeCid = await mnemonicWalletProvider.msigProposeSwapSigner( + multisigAddress, + addresses[0], + addresses[1], + addresses[2], + ); + const receiptSwapProposeCid = await con.state.waitMsg( + initSwapProposeCid, + 0, + ); const txnID = receiptSwapProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating swap proposal'); - const approveSwapCid = await mnemonicWalletProvider.msigApproveSwapSigner(multisigAddress, addresses[1], txnID, addresses[0], addresses[1], addresses[2] ); + const approveSwapCid = await mnemonicWalletProvider.msigApproveSwapSigner( + multisigAddress, + addresses[1], + txnID, + addresses[0], + addresses[1], + addresses[2], + ); const receiptSwapApprove = await con.state.waitMsg(approveSwapCid, 0); - console.log('receipt approve swap signer:', receiptSwapApprove); - assert.strictEqual(receiptSwapApprove.ReturnDec.Applied, true, 'error approving swap proposal'); + assert.strictEqual( + receiptSwapApprove.ReturnDec.Applied, + true, + 'error approving swap proposal', + ); }); - it("should create multisig wallet and cancel transfer funds [http]", async function () { + it('should create multisig wallet and cancel transfer funds [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, ''); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + '', + ); await mnemonicWalletProvider.newAddress(); await mnemonicWalletProvider.newAddress(); const addresses = await mnemonicWalletProvider.getAddresses(); const mnemonicAddress = await mnemonicWalletProvider.newAddress(); - const multisigCid = await mnemonicWalletProvider.msigCreate(2, addresses, 0, 0, '1000', addresses[0]); + const multisigCid = await mnemonicWalletProvider.msigCreate( + 2, + addresses, + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await mnemonicWalletProvider.msigGetAvailableBalance(multisigAddress, []); + const balance = await mnemonicWalletProvider.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initTransferCid = await mnemonicWalletProvider.msigProposeTransfer(multisigAddress, mnemonicAddress, '1', addresses[0]); + const initTransferCid = await mnemonicWalletProvider.msigProposeTransfer( + multisigAddress, + mnemonicAddress, + '1', + addresses[0], + ); const receiptTransferStart = await con.state.waitMsg(initTransferCid, 0); - console.log('receipt init transfer:', receiptTransferStart); const txnID = receiptTransferStart.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating transfer'); - const cancelTransferCid = await mnemonicWalletProvider.msigCancelTransfer(multisigAddress, addresses[0], txnID, mnemonicAddress, '1'); + const cancelTransferCid = await mnemonicWalletProvider.msigCancelTransfer( + multisigAddress, + addresses[0], + txnID, + mnemonicAddress, + '1', + ); const receiptTransferCancel = await con.state.waitMsg(cancelTransferCid, 0); - console.log('receipt cancel transfer:', receiptTransferCancel); - assert.strictEqual(receiptTransferCancel.Receipt.ExitCode, 0, 'error canceling transfer'); + assert.strictEqual( + receiptTransferCancel.Receipt.ExitCode, + 0, + 'error canceling transfer', + ); }); - it("should create multisig wallet cancel add signer [http]", async function () { + it('should create multisig wallet cancel add signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, 'test'); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + 'test', + ); await mnemonicWalletProvider.newAddress(); await mnemonicWalletProvider.newAddress(); const addresses = await mnemonicWalletProvider.getAddresses(); - const multisigCid = await mnemonicWalletProvider.msigCreate(2, [addresses[0], addresses[1]], 0, 0, '1000', addresses[0]); + const multisigCid = await mnemonicWalletProvider.msigCreate( + 2, + [addresses[0], addresses[1]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await mnemonicWalletProvider.msigGetAvailableBalance(multisigAddress, []); + const balance = await mnemonicWalletProvider.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initAddProposeCid = await mnemonicWalletProvider.msigProposeAddSigner(multisigAddress, addresses[0], addresses[2], true); + const initAddProposeCid = await mnemonicWalletProvider.msigProposeAddSigner( + multisigAddress, + addresses[0], + addresses[2], + true, + ); const receiptAddProposeCid = await con.state.waitMsg(initAddProposeCid, 0); - console.log('receipt init add signer:', receiptAddProposeCid); const txnID = receiptAddProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating add proposal'); - const cancelAddCid = await mnemonicWalletProvider.msigCancelAddSigner(multisigAddress, addresses[0], txnID, addresses[2], true); + const cancelAddCid = await mnemonicWalletProvider.msigCancelAddSigner( + multisigAddress, + addresses[0], + txnID, + addresses[2], + true, + ); const receiptAddCancel = await con.state.waitMsg(cancelAddCid, 0); - console.log('receipt cancel add signer:', receiptAddCancel); - assert.strictEqual(receiptAddCancel.Receipt.ExitCode, 0, 'error canceling add signer'); + assert.strictEqual( + receiptAddCancel.Receipt.ExitCode, + 0, + 'error canceling add signer', + ); }); - it("should create multisig wallet and cancel swap signer [http]", async function () { + it('should create multisig wallet and cancel swap signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, 'test'); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + 'test', + ); await mnemonicWalletProvider.newAddress(); await mnemonicWalletProvider.newAddress(); const addresses = await mnemonicWalletProvider.getAddresses(); - const multisigCid = await mnemonicWalletProvider.msigCreate(2, [addresses[0], addresses[1]], 0, 0, '1000', addresses[0]); + const multisigCid = await mnemonicWalletProvider.msigCreate( + 2, + [addresses[0], addresses[1]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await mnemonicWalletProvider.msigGetAvailableBalance(multisigAddress, []); + const balance = await mnemonicWalletProvider.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initSwapProposeCid = await mnemonicWalletProvider.msigProposeSwapSigner(multisigAddress, addresses[0], addresses[1], addresses[2]); - const receiptSwapProposeCid = await con.state.waitMsg(initSwapProposeCid, 0); - console.log('receipt init swap signer:', receiptSwapProposeCid); + const initSwapProposeCid = await mnemonicWalletProvider.msigProposeSwapSigner( + multisigAddress, + addresses[0], + addresses[1], + addresses[2], + ); + const receiptSwapProposeCid = await con.state.waitMsg( + initSwapProposeCid, + 0, + ); const txnID = receiptSwapProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating swap proposal'); - const cancelSwapCid = await mnemonicWalletProvider.msigCancelSwapSigner(multisigAddress, addresses[0], txnID, addresses[1], addresses[2] ); + const cancelSwapCid = await mnemonicWalletProvider.msigCancelSwapSigner( + multisigAddress, + addresses[0], + txnID, + addresses[1], + addresses[2], + ); const receiptSwapCancel = await con.state.waitMsg(cancelSwapCid, 0); - console.log('receipt cancel swap signer:', receiptSwapCancel); - assert.strictEqual(receiptSwapCancel.Receipt.ExitCode, 0, 'error canceling swap proposal'); + assert.strictEqual( + receiptSwapCancel.Receipt.ExitCode, + 0, + 'error canceling swap proposal', + ); }); - it("should create multisig wallet and remove signer [http]", async function () { + it('should create multisig wallet and remove signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, 'test'); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + 'test', + ); await mnemonicWalletProvider.newAddress(); await mnemonicWalletProvider.newAddress(); const addresses = await mnemonicWalletProvider.getAddresses(); - const multisigCid = await mnemonicWalletProvider.msigCreate(2, [addresses[0], addresses[1], addresses[2]], 0, 0, '1000', addresses[0]); + const multisigCid = await mnemonicWalletProvider.msigCreate( + 2, + [addresses[0], addresses[1], addresses[2]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await mnemonicWalletProvider.msigGetAvailableBalance(multisigAddress, []); + const balance = await mnemonicWalletProvider.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initRemoveProposeCid = await mnemonicWalletProvider.msigProposeRemoveSigner(multisigAddress, addresses[0], addresses[2], true); - const receiptRemoveProposeCid = await con.state.waitMsg(initRemoveProposeCid, 0); - console.log('receipt init remove signer:', receiptRemoveProposeCid); + const initRemoveProposeCid = await mnemonicWalletProvider.msigProposeRemoveSigner( + multisigAddress, + addresses[0], + addresses[2], + true, + ); + const receiptRemoveProposeCid = await con.state.waitMsg( + initRemoveProposeCid, + 0, + ); const txnID = receiptRemoveProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating add proposal'); - const approveRemoveCid = await mnemonicWalletProvider.msigApproveRemoveSigner(multisigAddress, addresses[1], txnID, addresses[0], addresses[2], true); + const approveRemoveCid = await mnemonicWalletProvider.msigApproveRemoveSigner( + multisigAddress, + addresses[1], + txnID, + addresses[0], + addresses[2], + true, + ); const receiptRemoveApprove = await con.state.waitMsg(approveRemoveCid, 0); - console.log('receipt approve remove signer:', receiptRemoveApprove); - assert.strictEqual(receiptRemoveApprove.ReturnDec.Applied, true, 'error approving add proposal'); + assert.strictEqual( + receiptRemoveApprove.ReturnDec.Applied, + true, + 'error approving add proposal', + ); }); - it("should create multisig wallet and cancel remove signer [http]", async function () { + it('should create multisig wallet and cancel remove signer [http]', async function () { this.timeout(60000); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); const con = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(con, testMnemonic, 'test'); + const mnemonicWalletProvider = new MnemonicWalletProvider( + con, + testMnemonic, + 'test', + ); await mnemonicWalletProvider.newAddress(); await mnemonicWalletProvider.newAddress(); const addresses = await mnemonicWalletProvider.getAddresses(); - const multisigCid = await mnemonicWalletProvider.msigCreate(2, [addresses[0], addresses[1], addresses[2]], 0, 0, '1000', addresses[0]); + const multisigCid = await mnemonicWalletProvider.msigCreate( + 2, + [addresses[0], addresses[1], addresses[2]], + 0, + 0, + '1000', + addresses[0], + ); const receipt = await con.state.waitMsg(multisigCid, 0); - console.log('receipt create:', receipt); const multisigAddress = receipt.ReturnDec.RobustAddress; - const balance = await mnemonicWalletProvider.msigGetAvailableBalance(multisigAddress, []); + const balance = await mnemonicWalletProvider.msigGetAvailableBalance( + multisigAddress, + [], + ); assert.strictEqual(balance, '1000', 'wrong balance'); - const initRemoveProposeCid = await mnemonicWalletProvider.msigProposeRemoveSigner(multisigAddress, addresses[0], addresses[2], true); - const receiptRemoveProposeCid = await con.state.waitMsg(initRemoveProposeCid, 0); - console.log('receipt init remove signer:', receiptRemoveProposeCid); + const initRemoveProposeCid = await mnemonicWalletProvider.msigProposeRemoveSigner( + multisigAddress, + addresses[0], + addresses[2], + true, + ); + const receiptRemoveProposeCid = await con.state.waitMsg( + initRemoveProposeCid, + 0, + ); const txnID = receiptRemoveProposeCid.ReturnDec.TxnID; assert.strictEqual(txnID, 0, 'error initiating add proposal'); - const cancelRemoveCid = await mnemonicWalletProvider.msigCancelRemoveSigner(multisigAddress, addresses[0], txnID, addresses[2], true); + const cancelRemoveCid = await mnemonicWalletProvider.msigCancelRemoveSigner( + multisigAddress, + addresses[0], + txnID, + addresses[2], + true, + ); const receiptRemoveCancel = await con.state.waitMsg(cancelRemoveCid, 0); - console.log('receipt cancel remove signer:', receiptRemoveCancel); - assert.strictEqual(receiptRemoveCancel.Receipt.ExitCode, 0, 'error canceling remove proposal'); + assert.strictEqual( + receiptRemoveCancel.Receipt.ExitCode, + 0, + 'error canceling remove proposal', + ); }); }); diff --git a/tests/src/test-state.ts b/tests/src/test-state.ts index 2a70876..669794d 100644 --- a/tests/src/test-state.ts +++ b/tests/src/test-state.ts @@ -1,16 +1,22 @@ -import assert from "assert"; -import { LOTUS_AUTH_TOKEN } from "../tools/testnet/credentials/credentials"; +import assert from 'assert'; +import { LOTUS_AUTH_TOKEN } from '../tools/testnet/credentials/credentials'; import { LotusClient } from '../../src/providers/LotusClient'; import { HttpJsonRpcConnector } from '../../src/connectors/HttpJsonRpcConnector'; import { WsJsonRpcConnector } from '../../src/connectors/WsJsonRpcConnector'; -const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); -const wsConnector = new WsJsonRpcConnector({ url: 'ws://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); +const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, +}); +const wsConnector = new WsJsonRpcConnector({ + url: 'ws://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, +}); -describe("State", function () { +describe('State', function () { const blocksWithMessages: any = []; - it("get blocks with messages [http]", async function() { + it('get blocks with messages [http]', async function () { const con = new LotusClient(httpConnector); const res: any = await con.chain.getTipSetByHeight(30); @@ -20,133 +26,205 @@ describe("State", function () { let block: any = undefined; try { block = await con.chain.getBlock(parentCid); - } catch(e) {}; + } catch (e) {} - if (block){ + if (block) { const messages = await con.chain.getBlockMessages(parentCid); - if (messages.BlsMessages.length > 0) blocksWithMessages.push (crtBlock); + if (messages.BlsMessages.length > 0) blocksWithMessages.push(crtBlock); crtBlock = parentCid; - parentCid = block.Parents? block.Parents[0] : null; + parentCid = block.Parents ? block.Parents[0] : null; } else { parentCid = undefined; } } - }); - it("should get block parent receipts [http]", async function() { + it('should get block parent receipts [http]', async function () { const con = new LotusClient(httpConnector); const receipts = await con.chain.getParentReceipts(blocksWithMessages[0]); - assert.strictEqual(typeof receipts[0].GasUsed, "number", "invalid receipts"); + assert.strictEqual( + typeof receipts[0].GasUsed, + 'number', + 'invalid receipts', + ); }); - it("should get block parent receipts [ws]", async function() { + it('should get block parent receipts [ws]', async function () { const provider = new LotusClient(wsConnector); - const receipts = await provider.chain.getParentReceipts(blocksWithMessages[0]); - assert.strictEqual(typeof receipts[0].GasUsed, "number", "invalid receipts"); + const receipts = await provider.chain.getParentReceipts( + blocksWithMessages[0], + ); + assert.strictEqual( + typeof receipts[0].GasUsed, + 'number', + 'invalid receipts', + ); await provider.release(); }); - it("should get block parent messages [http]", async function() { + it('should get block parent messages [http]', async function () { const con = new LotusClient(httpConnector); const messages = await con.chain.getParentMessages(blocksWithMessages[0]); - assert.strictEqual(typeof messages[0].Message.Nonce, "number", "invalid message"); + assert.strictEqual( + typeof messages[0].Message.Nonce, + 'number', + 'invalid message', + ); }); - it("should get block parent messages [ws]", async function() { + it('should get block parent messages [ws]', async function () { const provider = new LotusClient(wsConnector); - const messages = await provider.chain.getParentMessages(blocksWithMessages[0]); - assert.strictEqual(typeof messages[0].Message.Nonce, "number", "invalid message"); + const messages = await provider.chain.getParentMessages( + blocksWithMessages[0], + ); + assert.strictEqual( + typeof messages[0].Message.Nonce, + 'number', + 'invalid message', + ); await provider.release(); }); - it("should run the given message", async function() { + it('should run the given message', async function () { const provider = new LotusClient(httpConnector); const messages = await provider.state.listMessages({ - To: 't01000' + To: 't01000', }); - const message = await provider.chain.getMessage(messages[0]) + let i = 0; + let message; + do { + message = await provider.chain.getMessage(messages[i]); + i++; + } while (message.Method == 5); const result = await provider.state.stateCall(message); const valid = !!result.ExecutionTrace && !!result.Msg && !!result.MsgRct; - assert.strictEqual(valid, true, "failed to run message"); + assert.strictEqual(valid, true, 'failed to run message'); }); - it("should get actor [http]", async function() { + it('should get actor [http]', async function () { const con = new LotusClient(httpConnector); const actor = await con.state.getActor('t01000'); - assert.strictEqual( typeof actor.Balance === 'string', true, "invalid actor"); + assert.strictEqual( + typeof actor.Balance === 'string', + true, + 'invalid actor', + ); }); - it("should get state [http]", async function() { + it('should get state [http]', async function () { const con = new LotusClient(httpConnector); const state = await con.state.readState('t01000'); - assert.strictEqual(JSON.stringify(Object.keys(state)), JSON.stringify(['Balance', 'State']), 'invalid state'); + assert.strictEqual( + JSON.stringify(Object.keys(state)), + JSON.stringify(['Balance', 'Code', 'State']), + 'invalid state', + ); }); - it("should list messages [http]", async function () { + it('should list messages [http]', async function () { const con = new LotusClient(httpConnector); const messages = await con.state.listMessages({ - To: 't01000' + To: 't01000', }); - assert.strictEqual(Array.isArray(messages) && messages.length > 0, true, 'invalid list of messages'); + assert.strictEqual( + Array.isArray(messages) && messages.length > 0, + true, + 'invalid list of messages', + ); }); - it("should get network name [http]", async function () { + it('should get network name [http]', async function () { const con = new LotusClient(httpConnector); const network = await con.state.networkName(); - assert.strictEqual(typeof network === 'string', true, 'invalid network name'); + assert.strictEqual( + typeof network === 'string', + true, + 'invalid network name', + ); }); - it("should get miner sectors info [http]", async function () { + it('should get miner sectors info [http]', async function () { const con = new LotusClient(httpConnector); const sectors = await con.state.minerSectors('t01000'); - const valid = sectors.reduce((acc, sector) => acc === false ? acc : typeof sector.SectorNumber === 'number', true); + const valid = sectors.reduce( + (acc, sector) => + acc === false ? acc : typeof sector.SectorNumber === 'number', + true, + ); assert.strictEqual(valid, true, 'invalid sectors info'); }); - it("should get miner active sectors info [http]", async function () { + it('should get miner active sectors info [http]', async function () { const con = new LotusClient(httpConnector); const sectors = await con.state.minerActiveSectors('t01000'); - const valid = sectors.reduce((acc, sector) => acc === false ? acc : typeof sector.SectorNumber === 'number', true); + const valid = sectors.reduce( + (acc, sector) => + acc === false ? acc : typeof sector.SectorNumber === 'number', + true, + ); assert.strictEqual(valid, true, 'invalid active sectors info'); }); - it("should get miner proving deadline", async function () { + it('should get miner proving deadline', async function () { const con = new LotusClient(httpConnector); const provingDeadline = await con.state.minerProvingDeadline('t01000'); - assert.strictEqual(typeof provingDeadline.Index === 'number', true, 'invalid miner proving deadline'); + assert.strictEqual( + typeof provingDeadline.Index === 'number', + true, + 'invalid miner proving deadline', + ); }); - it("should get miner power", async function () { + it('should get miner power', async function () { const con = new LotusClient(httpConnector); const power = await con.state.minerPower('t01000'); - assert.strictEqual(typeof power.MinerPower.RawBytePower === 'string', true, 'invalid miner power'); + assert.strictEqual( + typeof power.MinerPower.RawBytePower === 'string', + true, + 'invalid miner power', + ); }); - it("should get miner info", async function () { + it('should get miner info', async function () { const con = new LotusClient(httpConnector); const minerInfo = await con.state.minerInfo('t01000'); - assert.strictEqual(typeof minerInfo.Owner === 'string', true, 'invalid miner info'); + assert.strictEqual( + typeof minerInfo.Owner === 'string', + true, + 'invalid miner info', + ); }); - it("should get miner deadlines", async function () { + it('should get miner deadlines', async function () { const con = new LotusClient(httpConnector); const minerDeadlines = await con.state.minerDeadlines('t01000'); - const valid = minerDeadlines.reduce((acc, deadline) => acc === false ? false : Array.isArray(deadline.PostSubmissions), true); + const valid = minerDeadlines.reduce( + (acc, deadline) => + acc === false ? false : Array.isArray(deadline.PostSubmissions), + true, + ); assert.strictEqual(valid, true, 'invalid miner deadlines'); }); - it("should get miner partitions", async function () { + it('should get miner partitions', async function () { const con = new LotusClient(httpConnector); const minerPartitions = await con.state.minerPartitions('t01000', 0); - const valid = minerPartitions.reduce((acc, partition) => acc === false ? false : Array.isArray(partition.AllSectors), true); + const valid = minerPartitions.reduce( + (acc, partition) => + acc === false ? false : Array.isArray(partition.AllSectors), + true, + ); assert.strictEqual(valid, true, 'invalid miner partitions'); }); - it("should get the faulty sectors of a miner", async function () { + it('should get the faulty sectors of a miner', async function () { const con = new LotusClient(httpConnector); const minerFaults = await con.state.minerFaults('t01000'); - assert.strictEqual(minerFaults === null || Array.isArray(minerFaults), true, 'invalid miner faulty sectors'); + assert.strictEqual( + minerFaults === null || Array.isArray(minerFaults), + true, + 'invalid miner faulty sectors', + ); }); // TODO: test on hold. The method has a bug @@ -155,19 +233,23 @@ describe("State", function () { // const minerFaults = await con.allMinerFaults(182); // }); - it("should get the recovering sectors of a miner", async function () { + it('should get the recovering sectors of a miner', async function () { const con = new LotusClient(httpConnector); const recoveries = await con.state.minerRecoveries('t01000'); - assert.strictEqual(recoveries === null || Array.isArray(recoveries), true, 'invalid miner recovering sectors'); + assert.strictEqual( + recoveries === null || Array.isArray(recoveries), + true, + 'invalid miner recovering sectors', + ); }); it("should get the precommit deposit for the specified miner's sector", async function () { const con = new LotusClient(httpConnector); - const deposit = await con.state.minerPreCommitDepositForPower('t01000', { + const deposit = await con.state.minerPreCommitDepositForPower('t01000', { SealProof: 1, SectorNumber: 1, SealedCID: { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + '/': 'bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4', }, SealRandEpoch: 10101, DealIDs: null, @@ -175,18 +257,22 @@ describe("State", function () { ReplaceCapacity: true, ReplaceSectorDeadline: 42, ReplaceSectorPartition: 42, - ReplaceSectorNumber: 9 + ReplaceSectorNumber: 9, }); - assert.strictEqual(typeof deposit === 'string', true, "invalid precommit deposit for the specified miner's sector"); + assert.strictEqual( + typeof deposit === 'string', + true, + "invalid precommit deposit for the specified miner's sector", + ); }); it("should get the initial pledge collateral for the specified miner's sector", async function () { const con = new LotusClient(httpConnector); - const collateral = await con.state.minerInitialPledgeCollateral('t01000', { + const collateral = await con.state.minerInitialPledgeCollateral('t01000', { SealProof: 1, SectorNumber: 1, SealedCID: { - "/": "bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4" + '/': 'bafy2bzacea3wsdh6y3a36tb3skempjoxqpuyompjbmfeyf34fi3uy6uue42v4', }, SealRandEpoch: 10101, DealIDs: null, @@ -194,15 +280,23 @@ describe("State", function () { ReplaceCapacity: true, ReplaceSectorDeadline: 42, ReplaceSectorPartition: 42, - ReplaceSectorNumber: 9 + ReplaceSectorNumber: 9, }); - assert.strictEqual(typeof collateral === 'string', true, "invalid pledge collateral for the specified miner's sector"); + assert.strictEqual( + typeof collateral === 'string', + true, + "invalid pledge collateral for the specified miner's sector", + ); }); it("should get the miner's balance that can be withdrawn or spent", async function () { const con = new LotusClient(httpConnector); const balance = await con.state.minerAvailableBalance('t01000'); - assert.strictEqual(typeof balance === 'string', true, "invalid miner's balance that can be withdrawn or spent"); + assert.strictEqual( + typeof balance === 'string', + true, + "invalid miner's balance that can be withdrawn or spent", + ); }); // TODO: It throws an error: precommit not found @@ -211,69 +305,97 @@ describe("State", function () { // const preCommitInfo = await con.state.sectorPreCommitInfo('t01000', 0); // }); - it("should return info for the specified miner's sector", async function() { + it("should return info for the specified miner's sector", async function () { const con = new LotusClient(httpConnector); const info = await con.state.sectorGetInfo('t01000', 0); - assert.strictEqual(info.SectorNumber === 0, true, "invalid info for the specified miner's sector"); + assert.strictEqual( + info.SectorNumber === 0, + true, + "invalid info for the specified miner's sector", + ); }); - it("should get epoch at which given sector will expire", async function() { + it('should get epoch at which given sector will expire', async function () { const con = new LotusClient(httpConnector); const expiration = await con.state.sectorExpiration('t01000', 0); - assert.strictEqual(typeof expiration.OnTime === 'number', true, "invalid epoch at which given sector will expire"); + assert.strictEqual( + typeof expiration.OnTime === 'number', + true, + 'invalid epoch at which given sector will expire', + ); }); - it("should get deadline/partition with the specified sector", async function() { + it('should get deadline/partition with the specified sector', async function () { const con = new LotusClient(httpConnector); const partition = await con.state.sectorPartition('t01000', 0); - assert.strictEqual(typeof partition.Partition === 'number', true, "invalid deadline/partition with the specified sector"); + assert.strictEqual( + typeof partition.Partition === 'number', + true, + 'invalid deadline/partition with the specified sector', + ); }); - it("should search for message and return its receipt and the tipset where it was executed", async function() { + it('should search for message and return its receipt and the tipset where it was executed', async function () { const con = new LotusClient(httpConnector); const messages = await con.state.listMessages({ To: 't01000', }); const receipt = await con.state.searchMsg(messages[0]); - assert.strictEqual(typeof receipt.Height === 'number', true, "invalid height for searched messages"); + assert.strictEqual( + typeof receipt.Height === 'number', + true, + 'invalid height for searched messages', + ); }); - it("should wait for message", async function() { + it('should wait for message', async function () { this.timeout(10000); const con = new LotusClient(httpConnector); const messages = await con.state.listMessages({ To: 't01000', }); const lookup = await con.state.waitMsg(messages[0], 10); - assert.strictEqual(typeof lookup.Height === 'number', true, "invalid lookup info for waited messages"); + assert.strictEqual( + typeof lookup.Height === 'number', + true, + 'invalid lookup info for waited messages', + ); }); - it("should wait message limited", async function() { + it('should wait message limited', async function () { this.timeout(10000); const con = new LotusClient(httpConnector); const messages = await con.state.listMessages({ - To: 't01000' + To: 't01000', }); const lookup = await con.state.waitMsgLimited(messages[0], 10, 10000000); - assert.strictEqual(typeof lookup.Height === 'number', true, "invalid lookup info for limited waited messages"); + assert.strictEqual( + typeof lookup.Height === 'number', + true, + 'invalid lookup info for limited waited messages', + ); }); - it("should list miners", async function() { + it('should list miners', async function () { const con = new LotusClient(httpConnector); const miners = await con.state.listMiners(); - assert.strictEqual(Array.isArray(miners), true, "invalid list of miners"); + assert.strictEqual(Array.isArray(miners), true, 'invalid list of miners'); }); - it("should list actors", async function() { + it('should list actors', async function () { const con = new LotusClient(httpConnector); const actors = await con.state.listActors(); - assert.strictEqual(Array.isArray(actors), true, "invalid list of actors"); + assert.strictEqual(Array.isArray(actors), true, 'invalid list of actors'); }); - it("should get market balance", async function() { + it('should get market balance', async function () { const con = new LotusClient(httpConnector); const marketBalance = await con.state.marketBalance('t01000'); - assert.strictEqual(typeof marketBalance.Escrow === 'string', true, "invalid market balance"); + assert.strictEqual( + typeof marketBalance.Escrow === 'string', + true, + 'invalid market balance', + ); }); /* @@ -285,7 +407,7 @@ describe("State", function () { }); */ - it("should get market deals", async function() { + it('should get market deals', async function () { const con = new LotusClient(httpConnector); const marketDeals = await con.state.marketDeals(); let valid = typeof marketDeals === 'object'; @@ -295,25 +417,33 @@ describe("State", function () { valid = typeof marketDeals[keys[0]].Proposal.PieceSize === 'number'; } - assert.strictEqual(valid, true, "invalid market deals"); + assert.strictEqual(valid, true, 'invalid market deals'); }); - it("should get information about the storage deal", async function() { + it('should get information about the storage deal', async function () { const con = new LotusClient(httpConnector); const marketDeal = await con.state.marketStorageDeal(0); - assert.strictEqual(!!marketDeal.Proposal.PieceCID, true, "invalid information about the storage deal"); + assert.strictEqual( + !!marketDeal.Proposal.PieceCID, + true, + 'invalid information about the storage deal', + ); }); - it("should get the ID address of the given address", async function() { + it('should get the ID address of the given address', async function () { const con = new LotusClient(httpConnector); const id = await con.state.lookupId('t01000'); - assert.strictEqual(typeof id === 'string', true, "invalid ID address"); + assert.strictEqual(typeof id === 'string', true, 'invalid ID address'); }); - it("should get the public key address of the given ID address", async function() { + it('should get the public key address of the given ID address', async function () { const con = new LotusClient(httpConnector); const key = await con.state.accountKey('t01002'); - assert.strictEqual(typeof key === 'string', true, "public key address of the given ID address"); + assert.strictEqual( + typeof key === 'string', + true, + 'public key address of the given ID address', + ); }); // TODO: Fix error: "failed to load hamt node: cbor input had wrong number of fields" and add assertion @@ -324,98 +454,141 @@ describe("State", function () { // const actors = await con.changedActors(tipSet.Cids[0], tipSet2.Cids[0]); // }); - it("should return the message receipt for the given message", async function() { + it('should return the message receipt for the given message', async function () { const con = new LotusClient(httpConnector); const messages = await con.state.listMessages({ - To: 't01000' + To: 't01000', }); const receipt = await con.state.getReceipt(messages[0]); - assert.strictEqual(typeof receipt.ExitCode === 'number', true, "invalid message receipt"); + assert.strictEqual( + typeof receipt.ExitCode === 'number', + true, + 'invalid message receipt', + ); }); - it("should return the number of sectors in a miner's sector set", async function() { + it("should return the number of sectors in a miner's sector set", async function () { const con = new LotusClient(httpConnector); const sectors = await con.state.minerSectorCount('t01000'); - assert.strictEqual(typeof sectors.Active === 'number', true, "invalid number of sectors"); + assert.strictEqual( + typeof sectors.Active === 'number', + true, + 'invalid number of sectors', + ); }); - it("should apply the messages", async function() { + it('should apply the messages', async function () { const con = new LotusClient(httpConnector); const messages = await con.state.listMessages({ - To: 't01000' + To: 't01000', }); const message = await con.chain.getMessage(messages[0]); const state = await con.state.compute(10, [message]); - assert.strictEqual(!!state.Root['/'], true, "invalid state after compute"); + assert.strictEqual(!!state.Root['/'], true, 'invalid state after compute'); }); - it("should return the data cap for the given address", async function() { + it('should return the data cap for the given address', async function () { const con = new LotusClient(httpConnector); const status = await con.state.verifiedClientStatus('t01000'); - assert.strictEqual(status === null || typeof status === 'string', true, "invalid data cap"); + assert.strictEqual( + status === null || typeof status === 'string', + true, + 'invalid data cap', + ); }); - it("should return min and max collateral a storage provider can issue", async function() { + it('should return min and max collateral a storage provider can issue', async function () { const con = new LotusClient(httpConnector); - const collateralBounds = await con.state.dealProviderCollateralBounds(Math.pow(1024, 2), true); - const valid = typeof collateralBounds.Min === 'string' && typeof collateralBounds.Max === 'string' - assert.strictEqual(valid, true, "invalid collateral a storage provider can issue"); + const collateralBounds = await con.state.dealProviderCollateralBounds( + Math.pow(1024, 2), + true, + ); + const valid = + typeof collateralBounds.Min === 'string' && + typeof collateralBounds.Max === 'string'; + assert.strictEqual( + valid, + true, + 'invalid collateral a storage provider can issue', + ); }); - it("the circulating supply of Filecoin at the given tipset", async function() { + it('the circulating supply of Filecoin at the given tipset', async function () { const con = new LotusClient(httpConnector); const supply = await con.state.circulatingSupply(); - const valid = Object - .keys(supply) - .reduce((acc, key) => acc === false ? acc : typeof key === 'string', true); - assert.strictEqual(valid, true, "invalid circulating supply of Filecoin"); + const valid = Object.keys(supply).reduce( + (acc, key) => (acc === false ? acc : typeof key === 'string'), + true, + ); + assert.strictEqual(valid, true, 'invalid circulating supply of Filecoin'); }); - it("the vm circulating supply of Filecoin at the given tipset", async function() { + it('the vm circulating supply of Filecoin at the given tipset', async function () { const con = new LotusClient(httpConnector); const supply = await con.state.vmCirculatingSupply(); - const valid = Object - .keys(supply) - .reduce((acc, key) => acc === false ? acc : typeof key === 'string', true); - assert.strictEqual(valid, true, "invalid vm circulating supply of Filecoin"); + const valid = Object.keys(supply).reduce( + (acc, key) => (acc === false ? acc : typeof key === 'string'), + true, + ); + assert.strictEqual( + valid, + true, + 'invalid vm circulating supply of Filecoin', + ); }); - it("should return the data cap for the verifier address [http]", async function() { + it('should return the data cap for the verifier address [http]', async function () { const con = new LotusClient(httpConnector); const status = await con.state.verifierStatus('t01000'); - assert.strictEqual(status === null || typeof status === 'string', true, "invalid data cap"); + assert.strictEqual( + status === null || typeof status === 'string', + true, + 'invalid data cap', + ); }); - it("should return the data cap for the verifier address [ws]", async function() { + it('should return the data cap for the verifier address [ws]', async function () { const con = new LotusClient(wsConnector); const status = await con.state.verifierStatus('t01000'); - assert.strictEqual(status === null || typeof status === 'string', true, "invalid data cap"); + assert.strictEqual( + status === null || typeof status === 'string', + true, + 'invalid data cap', + ); await con.release(); }); - it("should return the network version [http]", async function() { + it('should return the network version [http]', async function () { const con = new LotusClient(httpConnector); const version = await con.state.networkVersion(); - assert.strictEqual(typeof version === 'number', true, "invalid network version"); + assert.strictEqual( + typeof version === 'number', + true, + 'invalid network version', + ); }); - it("should return the network version [ws]", async function() { + it('should return the network version [ws]', async function () { const con = new LotusClient(wsConnector); - const version = await con.state.networkVersion() - assert.strictEqual(typeof version === 'number', true, "invalid network version"); + const version = await con.state.networkVersion(); + assert.strictEqual( + typeof version === 'number', + true, + 'invalid network version', + ); await con.release(); }); - it("should return the address of the Verified Registry's root key [http]", async function() { + it("should return the address of the Verified Registry's root key [http]", async function () { const con = new LotusClient(httpConnector); const address = await con.state.verifiedRegistryRootKey(); - assert.strictEqual(typeof address === 'string', true, "invalid address"); + assert.strictEqual(typeof address === 'string', true, 'invalid address'); }); - it("should return the address of the Verified Registry's root key [ws]", async function() { + it("should return the address of the Verified Registry's root key [ws]", async function () { const con = new LotusClient(wsConnector); - const address = await con.state.verifiedRegistryRootKey() - assert.strictEqual(typeof address === 'string', true, "invalid address"); + const address = await con.state.verifiedRegistryRootKey(); + assert.strictEqual(typeof address === 'string', true, 'invalid address'); await con.release(); }); }); diff --git a/tests/src/test-wallet-mnemonic.ts b/tests/src/test-wallet-mnemonic.ts index 8a57ed7..ae5112f 100644 --- a/tests/src/test-wallet-mnemonic.ts +++ b/tests/src/test-wallet-mnemonic.ts @@ -1,76 +1,123 @@ -import assert from "assert"; -import { LOTUS_AUTH_TOKEN } from "../tools/testnet/credentials/credentials"; +import assert from 'assert'; +import { LOTUS_AUTH_TOKEN } from '../tools/testnet/credentials/credentials'; import { HttpJsonRpcConnector } from '../../src/connectors/HttpJsonRpcConnector'; import { LotusWalletProvider } from '../../src/providers/wallet/LotusWalletProvider'; -import { LotusClient, MnemonicWalletProvider } from "../../src"; +import { LotusClient, MnemonicWalletProvider } from '../../src'; function sleep(ms: any) { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); } -const testMnemonic = 'equip will roof matter pink blind book anxiety banner elbow sun young'; +const testMnemonic = + 'equip will roof matter pink blind book anxiety banner elbow sun young'; -describe("Mnemonic Wallet methods", function () { - it("should retrieve wallet list [http]", async function () { - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); - const lotusClient = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(lotusClient, testMnemonic, ''); - - const accountsList = await mnemonicWalletProvider.getAddresses(); - assert.strictEqual(typeof accountsList, "object", 'couldn not retrieve address list'); +describe('Mnemonic Wallet methods', function () { + it('should retrieve wallet list [http]', async function () { + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, }); - - it("should create new wallet [http]", async function () { - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); - const lotusClient = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(lotusClient, testMnemonic, ''); - - const account = await mnemonicWalletProvider.newAddress(); - - const hasWallet = await mnemonicWalletProvider.hasAddress(account); - assert.strictEqual(hasWallet, true, 'newly created wallet not found in key store'); + const lotusClient = new LotusClient(httpConnector); + const mnemonicWalletProvider = new MnemonicWalletProvider( + lotusClient, + testMnemonic, + '', + ); + + const accountsList = await mnemonicWalletProvider.getAddresses(); + assert.strictEqual( + typeof accountsList, + 'object', + 'couldn not retrieve address list', + ); + }); + + it('should create new wallet [http]', async function () { + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, }); + const lotusClient = new LotusClient(httpConnector); + const mnemonicWalletProvider = new MnemonicWalletProvider( + lotusClient, + testMnemonic, + '', + ); + + const account = await mnemonicWalletProvider.newAddress(); + + const hasWallet = await mnemonicWalletProvider.hasAddress(account); + assert.strictEqual( + hasWallet, + true, + 'newly created wallet not found in key store', + ); + }); + + it('should change default address [http]', async function () { + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, + }); + const lotusClient = new LotusClient(httpConnector); + const mnemonicWalletProvider = new MnemonicWalletProvider( + lotusClient, + testMnemonic, + '', + ); + await mnemonicWalletProvider.newAddress(); - it("should change default address [http]", async function () { - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); - const lotusClient = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(lotusClient, testMnemonic, ''); - await mnemonicWalletProvider.newAddress(); - - const addressList = await mnemonicWalletProvider.getAddresses(); - const defaultAccount = await mnemonicWalletProvider.getDefaultAddress(); - - await mnemonicWalletProvider.setDefaultAddress(addressList[1]); - - let newDefault = await mnemonicWalletProvider.getDefaultAddress(); - - assert.strictEqual(newDefault, addressList[1], 'incorrect default address'); - - await mnemonicWalletProvider.setDefaultAddress(defaultAccount); - - newDefault = await mnemonicWalletProvider.getDefaultAddress(); + const addressList = await mnemonicWalletProvider.getAddresses(); + const defaultAccount = await mnemonicWalletProvider.getDefaultAddress(); - assert.strictEqual(newDefault, defaultAccount, 'incorrect default address'); - }); + await mnemonicWalletProvider.setDefaultAddress(addressList[1]); - it("should delete address [http]", async function () { - this.timeout(6000); + let newDefault = await mnemonicWalletProvider.getDefaultAddress(); - const httpConnector = new HttpJsonRpcConnector({ url: 'http://localhost:8000/rpc/v0', token: LOTUS_AUTH_TOKEN }); - const lotusClient = new LotusClient(httpConnector); - const mnemonicWalletProvider = new MnemonicWalletProvider(lotusClient, testMnemonic, ''); + assert.strictEqual(newDefault, addressList[1], 'incorrect default address'); - const defaultAddress = await mnemonicWalletProvider.getDefaultAddress(); - const privateKey = await mnemonicWalletProvider.exportPrivateKey(defaultAddress); - assert.strictEqual(typeof privateKey.PrivateKey, "string", 'could not private key'); + await mnemonicWalletProvider.setDefaultAddress(defaultAccount); - await mnemonicWalletProvider.newAddress(); + newDefault = await mnemonicWalletProvider.getDefaultAddress(); - const addresseseBeforeDelete = await mnemonicWalletProvider.getAddresses(); + assert.strictEqual(newDefault, defaultAccount, 'incorrect default address'); + }); - await mnemonicWalletProvider.deleteAddress(defaultAddress); + it('should delete address [http]', async function () { + this.timeout(6000); - const addressesAfterDelete = await mnemonicWalletProvider.getAddresses(); - assert.strictEqual(addresseseBeforeDelete.length - 1, addressesAfterDelete.length, 'wallet not deleted'); + const httpConnector = new HttpJsonRpcConnector({ + url: 'http://localhost:8000/rpc/v0', + token: LOTUS_AUTH_TOKEN, }); -}); \ No newline at end of file + const lotusClient = new LotusClient(httpConnector); + const mnemonicWalletProvider = new MnemonicWalletProvider( + lotusClient, + testMnemonic, + '', + ); + + const defaultAddress = await mnemonicWalletProvider.getDefaultAddress(); + const privateKey = await mnemonicWalletProvider.exportPrivateKey( + defaultAddress, + ); + assert.strictEqual( + typeof privateKey.PrivateKey, + 'string', + 'could not private key', + ); + + await mnemonicWalletProvider.newAddress(); + + const addresseseBeforeDelete = await mnemonicWalletProvider.getAddresses(); + + await mnemonicWalletProvider.deleteAddress(defaultAddress); + + const addressesAfterDelete = await mnemonicWalletProvider.getAddresses(); + assert.strictEqual( + addresseseBeforeDelete.length - 1, + addressesAfterDelete.length, + 'wallet not deleted', + ); + }); +}); diff --git a/tests/tools/testnet/Dockerfile b/tests/tools/testnet/Dockerfile index dc3dbe1..e612c83 100644 --- a/tests/tools/testnet/Dockerfile +++ b/tests/tools/testnet/Dockerfile @@ -1,10 +1,12 @@ -FROM ubuntu:20.10 +FROM ubuntu:20.04 #RUN rm /bin/sh && ln -s /bin/bash /bin/sh RUN apt update +RUN apt-get update RUN apt-get install -y software-properties-common RUN apt install -y --no-install-recommends build-essential git jq python netcat curl wget pkg-config libgl-dev libglu-dev libglib2.0-dev libsm-dev libxrender-dev libfontconfig1-dev libxext-dev nvidia-opencl-dev ocl-icd-opencl-dev tmux +RUN apt install -y --no-install-recommends mesa-opencl-icd gcc bzr clang hwloc libhwloc-dev wget -y RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y #install node @@ -15,8 +17,8 @@ RUN . "$NVM_DIR/nvm.sh" && nvm install v14.7.0 ENV PATH="/usr/local/versions/node/v14.7.0/bin:${PATH}" #install go -RUN wget https://dl.google.com/go/go1.14.3.linux-amd64.tar.gz -RUN tar -xvf go1.14.3.linux-amd64.tar.gz +RUN wget https://dl.google.com/go/go1.18.linux-amd64.tar.gz +RUN tar -xvf go1.18.linux-amd64.tar.gz RUN mv go /usr/local ENV PATH="/usr/local/go/bin:${PATH}" diff --git a/tests/tools/testnet/bin/build_lotus.sh b/tests/tools/testnet/bin/build_lotus.sh index 729e40d..983050e 100755 --- a/tests/tools/testnet/bin/build_lotus.sh +++ b/tests/tools/testnet/bin/build_lotus.sh @@ -27,7 +27,10 @@ deps=(printf paste jq python nc) #lotus_git_sha="4f45c623a5896637a9239d16b1836fdb635bb8f9" #master top 31 aug #lotus_git_sha="636810daa5e63a6ec132d78993d028a41f179276" #v0.8.1 #lotus_git_sha="a6b2180756db71574b385ef3c357f2b943252e78" #v0.10.0 -lotus_git_sha="d4cdc6d3340b8496c9f98e2d0daed8d1bd9b271e" #v1.1.2 +# lotus_git_sha="d4cdc6d3340b8496c9f98e2d0daed8d1bd9b271e" #v1.1.2 +lotus_git_sha="8db6a939c1e5c00bdaa79882685a78607825a2c7" #v1.17.1 + + copy_binaries_from_dir="" other_args=() @@ -59,11 +62,9 @@ cat > "${base_dir}/scripts/build.bash" </dev/null 2>&1 && pwd )" pushd \$SCRIPTDIR/../build pwd - make clean deps debug lotus-shed lotus-fountain + make 2k cp lotus lotus-miner lotus-shed lotus-seed lotus-fountain ${base_dir}/bin/ popd fi diff --git a/tests/tools/testnet/bin/start_testnet.sh b/tests/tools/testnet/bin/start_testnet.sh index 13d7cdf..e03261e 100755 --- a/tests/tools/testnet/bin/start_testnet.sh +++ b/tests/tools/testnet/bin/start_testnet.sh @@ -72,16 +72,22 @@ lotus net connect \$(cat ${base_dir}/.bootstrap-miner-multiaddr) while ! nc -z 127.0.0.1 7777