我试图验证我从用户那里得到的输入文本是一个有效的Solana地址。
根据web3.js文档,.isOnCurve()方法可以这样做:
https://solana-labs.github.io/solana-web3.js/classes/PublicKey.html#isOnCurve
我设法使它与以下代码一起工作:
import {PublicKey} from '@solana/web3.js'
function validateSolAddress(address:string){
try {
let pubkey = new PublicKey(address)
let isSolana = PublicKey.isOnCurve(pubkey.toBuffer())
return isSolana
} catch (error) {
return false
}
}
function modalSubmit(modal: any){
const firstResponse = modal.getTextInputValue(walletQuestFields.modal.componentsList[0].id)
let isSolAddress = validateSolAddress(firstResponse)
if (isSolAddress) {
console.log('The address is valid')
}else{
console.log('The address is NOT valid')
}
}
但是当我传递给let pubkey = new PublicKey(address)
一个与solana地址不类似的字符串时,它会抛出异常Error: Invalid public key input
(PublikKey需要一个PublicKeyInitData: number | string | Buffer | Uint8Array | number[] | PublicKeyData
)。
这就是为什么我必须把它放到一个试捕区。
还有其他(更好的)方法来实现这一点吗?看起来很难看..。
发布于 2022-02-21 04:02:07
要验证Solana公钥可能是钱包地址,您应该像正在做的那样使用isOnCurve()
和PublicKey
构造函数。
抛出的错误是有道理的。如果地址不是公钥,则不应该能够实例化它。
也许还会有另一种功能,它是原生于@solana/web3.js的,它可以在将来为您验证钱包地址。
发布于 2022-07-28 12:29:05
PublicKey.isOnCurve()
只在地址位于ed25519 curve
上时才返回true,这些地址是从Keypair
生成的,而对于非曲线地址(如PublicKey.findProgramAddress()
派生地址),则返回false,尽管它们可以是有效的公钥。
const owner = new PublicKey("DS2tt4BX7YwCw7yrDNwbAdnYrxjeCPeGJbHmZEYC8RTb");
console.log(PublicKey.isOnCurve(owner.toBytes())); // true
console.log(PublicKey.isOnCurve(owner.toString())); // true
const ownerPda = PublicKey.findProgramAddressSync(
[owner.toBuffer()],
new PublicKey("worm2ZoG2kUd4vFXhvjh93UUH596ayRfgQ2MgjNMTth"),
)[0];
console.log(PublicKey.isOnCurve(ownerPda.toString())); // false
console.log(PublicKey.isOnCurve([owner, 18])); // false
const RAY_MINT = new PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R");
console.log(PublicKey.isOnCurve(new PublicKey(RAY_MINT))); // true
console.log(PublicKey.isOnCurve("fasddfasevase")); // throws error
发布于 2022-03-06 20:14:21
我试图做同样的(验证一个solana钱包地址),并为我工作。
如果公钥具有有效的格式,则isOnCurve返回true,但我认为这不足以验证钱包地址,因为我从devnet和mainnet中测试了一些公钥,并且一直返回true (不关心env),除非我使用无效的密钥。
这是一个来自devnet的公钥,您可以尝试用它来测试:
8B9wLUXGFQQJ6VpzhDMpmHxByAvQBXhwSsZUwjLz971x
我的代码看起来是:
var connection = new web3.Connection(
web3.clusterApiUrl('devote'),
'confirmed',
);
const publicKey = new web3.PublicKey("8B9wLUXGFQQJ6VpzhDMpmHxByAvQBXhwSsZUwjLz971x");
console.log(await web3.PublicKey.isOnCurve(publicKey))
应该打印true
https://stackoverflow.com/questions/71200948
复制相似问题