Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IOS-7738 Add WalletManager #818

Merged

Conversation

amuraveinik
Copy link
Contributor

@amuraveinik amuraveinik commented Aug 30, 2024

IOS-7738

TODO: Учесть комменты отсюда

@amuraveinik amuraveinik requested review from tureck1y, dbaturin and a team as code owners August 30, 2024 12:05
@amuraveinik amuraveinik requested review from m3g0byt3 and Andoran90 and removed request for a team August 30, 2024 12:05
@amuraveinik amuraveinik marked this pull request as draft August 30, 2024 12:05
/// However, in Filecoin, message IDs (which are used to identify transactions) are not derived from transaction hashes.
/// Therefore, constructing a URL in the format `"\(baseExplorerUrl)/message/\(hash)"` is not applicable.
nil
URL(string: "\(baseExplorerUrl)/message/\(hash)")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По этому пункту поступила обновленная информация от андроида

let gasLimit: Int64
let gasFeeCap: BigUInt
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Просто переименование, чтобы матчилось с тем что приходит с апишки

BlockchainSdk/Extensions/JSONDecoder+.swift Outdated Show resolved Hide resolved
Base automatically changed from feature/IOS-7718_filecoin_transaction_builder to blockchains/filecoin September 3, 2024 10:29
// // https://github.com/tangem/wallet-core/blob/996bd5ab37f27e7f6e240a4ec9d0788dfb124e89/src/PublicKey.h#L35
let v = BigUInt(unmarshal.v) - 27
let encodedV = v == .zero ? Data([UInt8.zero]) : v.serialize()
let signature = unmarshal.r + unmarshal.s + encodedV
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

здесь скорее всего просто unmarshal должно хватить, так как EIP-155 как будто не валиден для Filecoin

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужно так как сейчас, иначе не проходит валидация подписи

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поправил ниже по комментам Андрея Ф

Copy link
Contributor

@m3g0byt3 m3g0byt3 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По вот этим комментам не нашел в этом пуле ничего

#816 (comment)
#816 (comment)

Или не туда смотрю?

let message = FilecoinMessage(
from: wallet.address,
to: destination,
value: bigUIntValue.description,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А у biguint нет какого-нибудь метода для перегона в строку?
description все-таки для другого и его формат недедтерминирован

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По моему эта проперти специально для этого и предназначена

extension BigUInt: CustomStringConvertible {
    /// Return the decimal representation of this integer.
    public var description: String {
        return String(self, radix: 10)
    }
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вообще сериализация использовалась, а тут надо именно строку в десятичном формате?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В десятичном виде нужна

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Явно вызывать String(self, radix: 10) выглядит корректней, на этот конструктор наверняка написаны тесты и т.д.
А description нужен по сути только для того, чтобы в логах распечатать и его реализация не гарантируется
Ну и оффдока:

Accessing a type’s description property directly or using CustomStringConvertible as a generic constraint is discouraged.

Впрочем не крит

@amuraveinik
Copy link
Contributor Author

amuraveinik commented Sep 3, 2024

По вот этим комментам не нашел в этом пуле ничего

#816 (comment) #816 (comment)

Или не туда смотрю?

Не в полной мере актуальны комменты здесь

  1. #816 (comment)

А какой тип у этого поля в апишке? Если float - то получается потеря точности. Если string - то корректнее маппить в decimal в маппере/конвертере

Возвращается тип - строка. В FilecoinAccountInfo (это там где balance: Decimal) значение из апишики сразу не парсится, оно как раз маппится в нетворк сервисе. Отдельно заводить маппер на однострочную операцию показалось оверкиллом

  1. #816 (comment)

А тут хватает uint64? В чем номинируется цена газа, я у них на сайте нашел упоминание про attoFIL, не в них случайно? Если да, то 1 attoFIL всего в 18 раз меньше uint64.max

Самого этого запроса больше нет, поменял на другой. Из апишки возвращается строка, паршу ее в Decimal. attoFIL да

@amuraveinik
Copy link
Contributor Author

amuraveinik commented Sep 3, 2024

@m3g0byt3 Про пендинг. Почему то не получилось к тому сообщение прилинковать ответ.

Вообще в доке есть метод MpoolCheckPendingMessages, и он идеально бы подошел
https://docs.filecoin.io/reference/json-rpc/mpool#mpoolcheckpendingmessages

Но апишка на запрос всегда возвращает ошибку the method Filecoin.MpoolCheckPendingMessages does not exist/is not available
На несуществующий метод всегда возвращается другая ошибка, поэтому это выглядит просто как неработающий запрос.

Предлагаю пока что оставить как есть до момента пока явно не будет сказано для файлкоина сделать возможность параллельной отправки

tureck1y
tureck1y previously approved these changes Sep 3, 2024
Copy link
Collaborator

@tureck1y tureck1y left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужно QA попросить сделать смоук вичейна

Balashov152
Balashov152 previously approved these changes Sep 3, 2024
FilecoinMessage(
from: address,
to: destination,
value: bigUIntValue.description,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

точно description? не надо там serialized() ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Выше про это
#818 (comment)

Comment on lines 63 to 64
/// VeChain is a fork of `Geth Classic`, so it expects the secp256k1's `recid` to have values in the 0...3 range.
/// Therefore we have to convert value of the standard secp256k1's `recid` to match this expectation.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: теперь этот коммент и объяснения в нем скорее к самой утилите SignatureUtils относится, офк без упоминания там VeChain
А просто что есть некоторые такие блокчейны, для которых нужно делать SignatureUtils.unmarshalledSignature

walletManager.wallet.addPendingTransaction(record)
return TransactionSendResult(hash: txId)
}
.eraseSendError()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кажется tx_id нужен в SendError, а тут он теряется

В остальных блокчейнах же не случайно делалась эта доработка, чтобы SendError содержал хеш транзы

Я приложил в прошлом комменте оба метода в экстеншене, другие сети сначала маппят в SendError с сохранением tx_id через mapSendError
А уже затем эрайзят через eraseSendError

@skibinalexander @tureck1y должны быть в контексте, зачем в SendError кладется хэш

let message = FilecoinMessage(
from: wallet.address,
to: destination,
value: bigUIntValue.description,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Явно вызывать String(self, radix: 10) выглядит корректней, на этот конструктор наверняка написаны тесты и т.д.
А description нужен по сути только для того, чтобы в логах распечатать и его реализация не гарантируется
Ну и оффдока:

Accessing a type’s description property directly or using CustomStringConvertible as a generic constraint is discouraged.

Впрочем не крит

.flatMap { walletManager, message in
walletManager.networkService
.submitTransaction(signedMessage: message)
.mapSendError(tx: try? JSONEncoder().encode(message).utf8String)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут именно так, потому что в апишку отправляем json объект, а не любого иного рода строку

@@ -9,6 +9,24 @@
import TangemSdk

enum SignatureUtils {
/// Unmarshals a signature using the provided original signature, public key, and hash.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это все будет полностью переделано в будущем и перенесено в TangemSdk

@amuraveinik amuraveinik enabled auto-merge (squash) September 4, 2024 10:53
@amuraveinik amuraveinik merged commit 0cb170c into blockchains/filecoin Sep 4, 2024
1 check passed
@amuraveinik amuraveinik deleted the feature/IOS-7738_filecoin_wallet_manager branch September 4, 2024 10:56
@amuraveinik amuraveinik mentioned this pull request Sep 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants